entities
listlengths
1
8.61k
max_stars_repo_path
stringlengths
7
172
max_stars_repo_name
stringlengths
5
89
max_stars_count
int64
0
82k
content
stringlengths
14
1.05M
id
stringlengths
2
6
new_content
stringlengths
15
1.05M
modified
bool
1 class
references
stringlengths
29
1.05M
[ { "context": "isposition\", \"attachment; filename=\"2018 resumé of Robert de Forest.#{extension}\" \"\"\".trim()\n\n res.send rendered", "end": 937, "score": 0.9347739219665527, "start": 921, "tag": "NAME", "value": "Robert de Forest" } ]
routes/resume.coffee
rdeforest/resume
0
fs = require 'fs' path = require 'path' express = require 'express' YAML = require 'js-yaml' router = express.Router() pug = require 'pug' htmlDocx = require 'html-docx-js' pdf = require 'html-pdf' cs = require 'coffeescript' moment = require 'moment' date = (t) -> moment(t).format 'YYYY-MM-DD' read = (f) -> fs.readFileSync(f).toString() config = -> conf = (require '../app').config Object.assign conf, updated: date fs.statSync conf.data generated: date() template = -> read config().template {formats} = require '../lib/formats' send = (res, resumé) -> {format} = config() {type, extension, converter} = formats[format] Promise.resolve converter resumé .catch (e) -> res.send e .then (rendered) -> if type res.set 'Content-Type', type res.set """ "Content-Disposition", "attachment; filename="2018 resumé of Robert de Forest.#{extension}" """.trim() res.send rendered router.get '/:format', (req, res, next) -> {data} = conf = config() resumé = (require path.resolve conf.data) require '../lib/builder' conf.format = req.params.format send res, resumé return module.exports = router
215476
fs = require 'fs' path = require 'path' express = require 'express' YAML = require 'js-yaml' router = express.Router() pug = require 'pug' htmlDocx = require 'html-docx-js' pdf = require 'html-pdf' cs = require 'coffeescript' moment = require 'moment' date = (t) -> moment(t).format 'YYYY-MM-DD' read = (f) -> fs.readFileSync(f).toString() config = -> conf = (require '../app').config Object.assign conf, updated: date fs.statSync conf.data generated: date() template = -> read config().template {formats} = require '../lib/formats' send = (res, resumé) -> {format} = config() {type, extension, converter} = formats[format] Promise.resolve converter resumé .catch (e) -> res.send e .then (rendered) -> if type res.set 'Content-Type', type res.set """ "Content-Disposition", "attachment; filename="2018 resumé of <NAME>.#{extension}" """.trim() res.send rendered router.get '/:format', (req, res, next) -> {data} = conf = config() resumé = (require path.resolve conf.data) require '../lib/builder' conf.format = req.params.format send res, resumé return module.exports = router
true
fs = require 'fs' path = require 'path' express = require 'express' YAML = require 'js-yaml' router = express.Router() pug = require 'pug' htmlDocx = require 'html-docx-js' pdf = require 'html-pdf' cs = require 'coffeescript' moment = require 'moment' date = (t) -> moment(t).format 'YYYY-MM-DD' read = (f) -> fs.readFileSync(f).toString() config = -> conf = (require '../app').config Object.assign conf, updated: date fs.statSync conf.data generated: date() template = -> read config().template {formats} = require '../lib/formats' send = (res, resumé) -> {format} = config() {type, extension, converter} = formats[format] Promise.resolve converter resumé .catch (e) -> res.send e .then (rendered) -> if type res.set 'Content-Type', type res.set """ "Content-Disposition", "attachment; filename="2018 resumé of PI:NAME:<NAME>END_PI.#{extension}" """.trim() res.send rendered router.get '/:format', (req, res, next) -> {data} = conf = config() resumé = (require path.resolve conf.data) require '../lib/builder' conf.format = req.params.format send res, resumé return module.exports = router
[ { "context": "ientSignature\"\n}\n\nconfigmodule.masterSecretKey = \"003464606f47e65cf514c2c8f1f007d432a46fbeba616781bbff52def803e6e8\"\nconfigmodule.masterPublicKey = \"7102da6282ec3169", "end": 552, "score": 0.9997515678405762, "start": 488, "tag": "KEY", "value": "003464606f47e65cf514c2c8f1f007d432a46fbeba616781bbff52def803e6e8" }, { "context": "bbff52def803e6e8\"\nconfigmodule.masterPublicKey = \"7102da6282ec316974e7ea6ad7d24bd077f70a969ffe865c8b99b12b314f644c\"\n\nconfigmodule.secretKey = \"447dd15e1d5ded3d662c2", "end": 650, "score": 0.9997522234916687, "start": 586, "tag": "KEY", "value": "7102da6282ec316974e7ea6ad7d24bd077f70a969ffe865c8b99b12b314f644c" }, { "context": "e865c8b99b12b314f644c\"\n\nconfigmodule.secretKey = \"447dd15e1d5ded3d662c26e0e61bf299ccab60b2d4bc86f1ec07e4561a09df63\"\nconfigmodule.publicKey = \"dc29860abee9d5783d1689", "end": 743, "score": 0.9997554421424866, "start": 679, "tag": "KEY", "value": "447dd15e1d5ded3d662c26e0e61bf299ccab60b2d4bc86f1ec07e4561a09df63" }, { "context": "bc86f1ec07e4561a09df63\"\nconfigmodule.publicKey = \"dc29860abee9d5783d1689ef249f0d3aa18bda443a524ae610e3c3f71c6b5bca\"\n\nconfigmodule.secretManagerURL = \"https://secret", "end": 835, "score": 0.9997547268867493, "start": 771, "tag": "KEY", "value": "dc29860abee9d5783d1689ef249f0d3aa18bda443a524ae610e3c3f71c6b5bca" } ]
source/configmodule/configmodule.coffee
JhonnyJason/data-manager-service-sources
0
configmodule = {name: "configmodule"} ############################################################ log = (arg) -> if allModules.debugmodule.modulesToDebug["configmodule"]? then console.log "[configmodule]: " + arg return ############################################################ configmodule.specialAuth = { "/addClientToServe": "masterSignature", "/getNodeId": "knownClientSignature", "/startSession": "knownClientSignature" } configmodule.masterSecretKey = "003464606f47e65cf514c2c8f1f007d432a46fbeba616781bbff52def803e6e8" configmodule.masterPublicKey = "7102da6282ec316974e7ea6ad7d24bd077f70a969ffe865c8b99b12b314f644c" configmodule.secretKey = "447dd15e1d5ded3d662c26e0e61bf299ccab60b2d4bc86f1ec07e4561a09df63" configmodule.publicKey = "dc29860abee9d5783d1689ef249f0d3aa18bda443a524ae610e3c3f71c6b5bca" configmodule.secretManagerURL = "https://secrets.extensivlyon.coffee" configmodule.timestampFrameMS = 10000 ############################################################ configmodule.initialize = () -> log "configmodule.initialize" return export default configmodule
50424
configmodule = {name: "configmodule"} ############################################################ log = (arg) -> if allModules.debugmodule.modulesToDebug["configmodule"]? then console.log "[configmodule]: " + arg return ############################################################ configmodule.specialAuth = { "/addClientToServe": "masterSignature", "/getNodeId": "knownClientSignature", "/startSession": "knownClientSignature" } configmodule.masterSecretKey = "<KEY>" configmodule.masterPublicKey = "<KEY>" configmodule.secretKey = "<KEY>" configmodule.publicKey = "<KEY>" configmodule.secretManagerURL = "https://secrets.extensivlyon.coffee" configmodule.timestampFrameMS = 10000 ############################################################ configmodule.initialize = () -> log "configmodule.initialize" return export default configmodule
true
configmodule = {name: "configmodule"} ############################################################ log = (arg) -> if allModules.debugmodule.modulesToDebug["configmodule"]? then console.log "[configmodule]: " + arg return ############################################################ configmodule.specialAuth = { "/addClientToServe": "masterSignature", "/getNodeId": "knownClientSignature", "/startSession": "knownClientSignature" } configmodule.masterSecretKey = "PI:KEY:<KEY>END_PI" configmodule.masterPublicKey = "PI:KEY:<KEY>END_PI" configmodule.secretKey = "PI:KEY:<KEY>END_PI" configmodule.publicKey = "PI:KEY:<KEY>END_PI" configmodule.secretManagerURL = "https://secrets.extensivlyon.coffee" configmodule.timestampFrameMS = 10000 ############################################################ configmodule.initialize = () -> log "configmodule.initialize" return export default configmodule
[ { "context": "true\n @state.stepKey().should.equal 'existing_2'\n @state.set current_level: 1, reonboarding:", "end": 642, "score": 0.615909993648529, "start": 641, "tag": "KEY", "value": "2" }, { "context": "ng: false\n @state.stepKey().should.equal 'new_1'\n @state.set current_level: 3\n @state.u", "end": 741, "score": 0.6035767197608948, "start": 740, "tag": "KEY", "value": "1" }, { "context": "eonboarding'\n @state.stepKey().should.equal 'new_3'\n\n describe '#completedSteps', ->\n describe '", "end": 853, "score": 0.5912055373191833, "start": 848, "tag": "KEY", "value": "new_3" }, { "context": "one) ->\n state = new PersonalizeState user: @user, current_level: 1\n state.on 'done', -> don", "end": 4407, "score": 0.9984238147735596, "start": 4402, "tag": "USERNAME", "value": "@user" }, { "context": "one) ->\n state = new PersonalizeState user: @user, current_level: 2\n state.on 'done', -> don", "end": 4925, "score": 0.9978073835372925, "start": 4920, "tag": "USERNAME", "value": "@user" }, { "context": "one) ->\n state = new PersonalizeState user: @user, current_level: 3\n state.on 'done', -> don", "end": 5497, "score": 0.9979307651519775, "start": 5492, "tag": "USERNAME", "value": "@user" }, { "context": "one) ->\n state = new PersonalizeState user: @user, current_level: 1, reonboarding: true\n sta", "end": 6057, "score": 0.9981063008308411, "start": 6052, "tag": "USERNAME", "value": "@user" }, { "context": "one) ->\n state = new PersonalizeState user: @user, current_level: 2, reonboarding: true\n sta", "end": 6595, "score": 0.9978415966033936, "start": 6590, "tag": "USERNAME", "value": "@user" }, { "context": "one) ->\n state = new PersonalizeState user: @user, current_level: 3, reonboarding: true\n sta", "end": 7187, "score": 0.997667133808136, "start": 7182, "tag": "USERNAME", "value": "@user" } ]
src/desktop/apps/personalize/test/client/state.coffee
streamich/force
1
_ = require 'underscore' CurrentUser = require '../../../../models/current_user' PersonalizeState = require '../../client/state' describe 'state', -> beforeEach -> @user = new CurrentUser @state = new PersonalizeState user: @user it 'has a default current_step', -> @state.get('current_step').should.equal 'collect' it 'has the appropriate set of steps for the appropriate level', -> @state.steps().should.eql @state.get('__steps__')[@state.stepKey()] describe '#stepKey', -> it 'returns the correct key', -> @state.set current_level: 2, reonboarding: true @state.stepKey().should.equal 'existing_2' @state.set current_level: 1, reonboarding: false @state.stepKey().should.equal 'new_1' @state.set current_level: 3 @state.unset 'reonboarding' @state.stepKey().should.equal 'new_3' describe '#completedSteps', -> describe 'returns an array of steps that have already been completed', -> beforeEach -> # Kill memoization @state.__completedSteps__ = null it 'is empty by default', -> @state.completedSteps().should.be.empty it 'handles a user who has a collector_level set above the default', -> @user.set collector_level: 2 @state.completedSteps().should.eql ['collect'] it 'handles a user who has a price range already set', -> @user.set price_range: 'existy' @state.completedSteps().should.eql ['price_range'] it 'doesnt skip when the price range is the default returned by the server', -> @user.set price_range: '-1:1000000000000' @state.completedSteps().should.be.empty it 'handles some combination of completed steps', -> @user.set collector_level: 2 @state.completedSteps().should.eql ['collect'] it 'memoizes the value so that it is unaffected by user state modifications', -> @state.completedSteps().should.be.empty @user.set collector_level: 2 @state.completedSteps().should.be.empty describe '#steps', -> it 'reflects the actual state of the steps the casual user needs to complete on initialization', -> @state.set current_level: 1 @state.steps().should.eql @state.get('__steps__')['new_1'] it 'reflects the actual state of the steps the collector user needs to complete on initialization', -> @state.set current_level: 2 @state.steps().should.eql @state.get('__steps__')['new_2'] it 'reflects the actual state of the steps the collector user who has a semi-complete profile needs to complete on initialization', -> @state.__completedSteps__ = null @state.set current_level: 2 @user.set collector_level: 2 @state.steps().should.eql _.without(@state.get('__steps__')['new_2'], 'collect') describe '#currentStepIndex', -> it 'returns the appropriate index', -> @state.currentStepIndex().should.equal 0 @state.next() @state.currentStepIndex().should.equal 1 describe '#currentStepLabel', -> it 'humanizes and capitalizes the step name', -> @state.set current_step: 'price_range' @state.currentStepLabel().should.equal 'Price Range' @state.set current_step: 'artists' @state.currentStepLabel().should.equal 'Artists' describe '#stepDisplay', -> it 'displays a human readable step count', -> @state.stepDisplay().should.equal "Step 1 of #{@state.steps().length}" @state.next() @state.stepDisplay().should.equal "Step 2 of #{@state.steps().length}" describe '#almostDone', -> it 'lets you know if you are on the last step', -> @state.almostDone().should.not.be.ok() last_step = _.last @state.steps() @state.set current_step: last_step @state.almostDone().should.be.ok() describe '#next', -> beforeEach -> @last_step = _.last @state.steps() @state.set current_step: @last_step it 'should not be able to step past the last step', -> @state.next() @state.get('current_step').should.equal @last_step it 'triggers done', (done) -> @state.on 'done', done @state.next() @state.off 'done' describe 'can be driven through all the state transitions depending on the user level', -> describe 'new users', -> it 'works for a user that is just looking and learning (level 1)', (done) -> state = new PersonalizeState user: @user, current_level: 1 state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'categories' state.next() state.get('current_step').should.equal 'favorites' state.next() state.get('current_step').should.equal 'artists' state.next() # Done it 'works for a user that is interested in starting to buy art (level 2)', (done) -> state = new PersonalizeState user: @user, current_level: 2 state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'price_range' state.next() state.get('current_step').should.equal 'categories' state.next() state.get('current_step').should.equal 'favorites' state.next() state.get('current_step').should.equal 'artists' state.next() # Done it 'works for a user that buys art (level 3)', (done) -> state = new PersonalizeState user: @user, current_level: 3 state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'price_range' state.next() state.get('current_step').should.equal 'bookmarks' state.next() state.get('current_step').should.equal 'artists' state.next() # Done describe 'existing users (reonboarding)', -> it 'works for a user that is just looking and learning (level 1)', (done) -> state = new PersonalizeState user: @user, current_level: 1, reonboarding: true state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'categories' state.next() state.get('current_step').should.equal 'favorites' state.next() state.get('current_step').should.equal 'artists' state.next() # Done it 'works for a user that is interested in starting to buy art (level 2)', (done) -> state = new PersonalizeState user: @user, current_level: 2, reonboarding: true state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'price_range' state.next() state.get('current_step').should.equal 'categories' state.next() state.get('current_step').should.equal 'favorites' state.next() state.get('current_step').should.equal 'artists' state.next() # Done it 'works for a user that buys art (level 3)', (done) -> state = new PersonalizeState user: @user, current_level: 3, reonboarding: true state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'price_range' state.next() state.get('current_step').should.equal 'bookmarks' state.next() state.get('current_step').should.equal 'artists' state.next() # Done
89495
_ = require 'underscore' CurrentUser = require '../../../../models/current_user' PersonalizeState = require '../../client/state' describe 'state', -> beforeEach -> @user = new CurrentUser @state = new PersonalizeState user: @user it 'has a default current_step', -> @state.get('current_step').should.equal 'collect' it 'has the appropriate set of steps for the appropriate level', -> @state.steps().should.eql @state.get('__steps__')[@state.stepKey()] describe '#stepKey', -> it 'returns the correct key', -> @state.set current_level: 2, reonboarding: true @state.stepKey().should.equal 'existing_<KEY>' @state.set current_level: 1, reonboarding: false @state.stepKey().should.equal 'new_<KEY>' @state.set current_level: 3 @state.unset 'reonboarding' @state.stepKey().should.equal '<KEY>' describe '#completedSteps', -> describe 'returns an array of steps that have already been completed', -> beforeEach -> # Kill memoization @state.__completedSteps__ = null it 'is empty by default', -> @state.completedSteps().should.be.empty it 'handles a user who has a collector_level set above the default', -> @user.set collector_level: 2 @state.completedSteps().should.eql ['collect'] it 'handles a user who has a price range already set', -> @user.set price_range: 'existy' @state.completedSteps().should.eql ['price_range'] it 'doesnt skip when the price range is the default returned by the server', -> @user.set price_range: '-1:1000000000000' @state.completedSteps().should.be.empty it 'handles some combination of completed steps', -> @user.set collector_level: 2 @state.completedSteps().should.eql ['collect'] it 'memoizes the value so that it is unaffected by user state modifications', -> @state.completedSteps().should.be.empty @user.set collector_level: 2 @state.completedSteps().should.be.empty describe '#steps', -> it 'reflects the actual state of the steps the casual user needs to complete on initialization', -> @state.set current_level: 1 @state.steps().should.eql @state.get('__steps__')['new_1'] it 'reflects the actual state of the steps the collector user needs to complete on initialization', -> @state.set current_level: 2 @state.steps().should.eql @state.get('__steps__')['new_2'] it 'reflects the actual state of the steps the collector user who has a semi-complete profile needs to complete on initialization', -> @state.__completedSteps__ = null @state.set current_level: 2 @user.set collector_level: 2 @state.steps().should.eql _.without(@state.get('__steps__')['new_2'], 'collect') describe '#currentStepIndex', -> it 'returns the appropriate index', -> @state.currentStepIndex().should.equal 0 @state.next() @state.currentStepIndex().should.equal 1 describe '#currentStepLabel', -> it 'humanizes and capitalizes the step name', -> @state.set current_step: 'price_range' @state.currentStepLabel().should.equal 'Price Range' @state.set current_step: 'artists' @state.currentStepLabel().should.equal 'Artists' describe '#stepDisplay', -> it 'displays a human readable step count', -> @state.stepDisplay().should.equal "Step 1 of #{@state.steps().length}" @state.next() @state.stepDisplay().should.equal "Step 2 of #{@state.steps().length}" describe '#almostDone', -> it 'lets you know if you are on the last step', -> @state.almostDone().should.not.be.ok() last_step = _.last @state.steps() @state.set current_step: last_step @state.almostDone().should.be.ok() describe '#next', -> beforeEach -> @last_step = _.last @state.steps() @state.set current_step: @last_step it 'should not be able to step past the last step', -> @state.next() @state.get('current_step').should.equal @last_step it 'triggers done', (done) -> @state.on 'done', done @state.next() @state.off 'done' describe 'can be driven through all the state transitions depending on the user level', -> describe 'new users', -> it 'works for a user that is just looking and learning (level 1)', (done) -> state = new PersonalizeState user: @user, current_level: 1 state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'categories' state.next() state.get('current_step').should.equal 'favorites' state.next() state.get('current_step').should.equal 'artists' state.next() # Done it 'works for a user that is interested in starting to buy art (level 2)', (done) -> state = new PersonalizeState user: @user, current_level: 2 state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'price_range' state.next() state.get('current_step').should.equal 'categories' state.next() state.get('current_step').should.equal 'favorites' state.next() state.get('current_step').should.equal 'artists' state.next() # Done it 'works for a user that buys art (level 3)', (done) -> state = new PersonalizeState user: @user, current_level: 3 state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'price_range' state.next() state.get('current_step').should.equal 'bookmarks' state.next() state.get('current_step').should.equal 'artists' state.next() # Done describe 'existing users (reonboarding)', -> it 'works for a user that is just looking and learning (level 1)', (done) -> state = new PersonalizeState user: @user, current_level: 1, reonboarding: true state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'categories' state.next() state.get('current_step').should.equal 'favorites' state.next() state.get('current_step').should.equal 'artists' state.next() # Done it 'works for a user that is interested in starting to buy art (level 2)', (done) -> state = new PersonalizeState user: @user, current_level: 2, reonboarding: true state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'price_range' state.next() state.get('current_step').should.equal 'categories' state.next() state.get('current_step').should.equal 'favorites' state.next() state.get('current_step').should.equal 'artists' state.next() # Done it 'works for a user that buys art (level 3)', (done) -> state = new PersonalizeState user: @user, current_level: 3, reonboarding: true state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'price_range' state.next() state.get('current_step').should.equal 'bookmarks' state.next() state.get('current_step').should.equal 'artists' state.next() # Done
true
_ = require 'underscore' CurrentUser = require '../../../../models/current_user' PersonalizeState = require '../../client/state' describe 'state', -> beforeEach -> @user = new CurrentUser @state = new PersonalizeState user: @user it 'has a default current_step', -> @state.get('current_step').should.equal 'collect' it 'has the appropriate set of steps for the appropriate level', -> @state.steps().should.eql @state.get('__steps__')[@state.stepKey()] describe '#stepKey', -> it 'returns the correct key', -> @state.set current_level: 2, reonboarding: true @state.stepKey().should.equal 'existing_PI:KEY:<KEY>END_PI' @state.set current_level: 1, reonboarding: false @state.stepKey().should.equal 'new_PI:KEY:<KEY>END_PI' @state.set current_level: 3 @state.unset 'reonboarding' @state.stepKey().should.equal 'PI:KEY:<KEY>END_PI' describe '#completedSteps', -> describe 'returns an array of steps that have already been completed', -> beforeEach -> # Kill memoization @state.__completedSteps__ = null it 'is empty by default', -> @state.completedSteps().should.be.empty it 'handles a user who has a collector_level set above the default', -> @user.set collector_level: 2 @state.completedSteps().should.eql ['collect'] it 'handles a user who has a price range already set', -> @user.set price_range: 'existy' @state.completedSteps().should.eql ['price_range'] it 'doesnt skip when the price range is the default returned by the server', -> @user.set price_range: '-1:1000000000000' @state.completedSteps().should.be.empty it 'handles some combination of completed steps', -> @user.set collector_level: 2 @state.completedSteps().should.eql ['collect'] it 'memoizes the value so that it is unaffected by user state modifications', -> @state.completedSteps().should.be.empty @user.set collector_level: 2 @state.completedSteps().should.be.empty describe '#steps', -> it 'reflects the actual state of the steps the casual user needs to complete on initialization', -> @state.set current_level: 1 @state.steps().should.eql @state.get('__steps__')['new_1'] it 'reflects the actual state of the steps the collector user needs to complete on initialization', -> @state.set current_level: 2 @state.steps().should.eql @state.get('__steps__')['new_2'] it 'reflects the actual state of the steps the collector user who has a semi-complete profile needs to complete on initialization', -> @state.__completedSteps__ = null @state.set current_level: 2 @user.set collector_level: 2 @state.steps().should.eql _.without(@state.get('__steps__')['new_2'], 'collect') describe '#currentStepIndex', -> it 'returns the appropriate index', -> @state.currentStepIndex().should.equal 0 @state.next() @state.currentStepIndex().should.equal 1 describe '#currentStepLabel', -> it 'humanizes and capitalizes the step name', -> @state.set current_step: 'price_range' @state.currentStepLabel().should.equal 'Price Range' @state.set current_step: 'artists' @state.currentStepLabel().should.equal 'Artists' describe '#stepDisplay', -> it 'displays a human readable step count', -> @state.stepDisplay().should.equal "Step 1 of #{@state.steps().length}" @state.next() @state.stepDisplay().should.equal "Step 2 of #{@state.steps().length}" describe '#almostDone', -> it 'lets you know if you are on the last step', -> @state.almostDone().should.not.be.ok() last_step = _.last @state.steps() @state.set current_step: last_step @state.almostDone().should.be.ok() describe '#next', -> beforeEach -> @last_step = _.last @state.steps() @state.set current_step: @last_step it 'should not be able to step past the last step', -> @state.next() @state.get('current_step').should.equal @last_step it 'triggers done', (done) -> @state.on 'done', done @state.next() @state.off 'done' describe 'can be driven through all the state transitions depending on the user level', -> describe 'new users', -> it 'works for a user that is just looking and learning (level 1)', (done) -> state = new PersonalizeState user: @user, current_level: 1 state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'categories' state.next() state.get('current_step').should.equal 'favorites' state.next() state.get('current_step').should.equal 'artists' state.next() # Done it 'works for a user that is interested in starting to buy art (level 2)', (done) -> state = new PersonalizeState user: @user, current_level: 2 state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'price_range' state.next() state.get('current_step').should.equal 'categories' state.next() state.get('current_step').should.equal 'favorites' state.next() state.get('current_step').should.equal 'artists' state.next() # Done it 'works for a user that buys art (level 3)', (done) -> state = new PersonalizeState user: @user, current_level: 3 state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'price_range' state.next() state.get('current_step').should.equal 'bookmarks' state.next() state.get('current_step').should.equal 'artists' state.next() # Done describe 'existing users (reonboarding)', -> it 'works for a user that is just looking and learning (level 1)', (done) -> state = new PersonalizeState user: @user, current_level: 1, reonboarding: true state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'categories' state.next() state.get('current_step').should.equal 'favorites' state.next() state.get('current_step').should.equal 'artists' state.next() # Done it 'works for a user that is interested in starting to buy art (level 2)', (done) -> state = new PersonalizeState user: @user, current_level: 2, reonboarding: true state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'price_range' state.next() state.get('current_step').should.equal 'categories' state.next() state.get('current_step').should.equal 'favorites' state.next() state.get('current_step').should.equal 'artists' state.next() # Done it 'works for a user that buys art (level 3)', (done) -> state = new PersonalizeState user: @user, current_level: 3, reonboarding: true state.on 'done', -> done() state.get('current_step').should.equal 'collect' state.next() state.get('current_step').should.equal 'price_range' state.next() state.get('current_step').should.equal 'bookmarks' state.next() state.get('current_step').should.equal 'artists' state.next() # Done
[ { "context": "efined\n @_autostart = undefined\n @password = undefined\n @serverDevice = undefined\n chrome.storage.", "end": 341, "score": 0.9715813994407654, "start": 332, "tag": "PASSWORD", "value": "undefined" }, { "context": "s, servers: @_servers, channels: @_channels, nick: @_nick }\n\n _createIRCStates: ->\n ircStates = []\n ", "end": 3788, "score": 0.9931517839431763, "start": 3782, "tag": "USERNAME", "value": "@_nick" }, { "context": "e.password\n if not @password\n @password = irc.util.randomName()\n @_log 'no password found, setting new pas", "end": 4711, "score": 0.8693658709526062, "start": 4692, "tag": "PASSWORD", "value": "irc.util.randomName" } ]
src/chat/storage.coffee
nornagon/ircv
20
exports = window.chat ?= {} ## # Manages storage. ## class Storage @STATE_ITEMS = ['nick', 'servers', 'channels'] @INITIAL_ITEMS = ['password', 'server_device', 'autostart'] constructor: -> @_log = getLogger this @_channels = [] @_servers = [] @_nick = undefined @_autostart = undefined @password = undefined @serverDevice = undefined chrome.storage.onChanged.addListener @_onChanged @pause() ## # Listen for storage changes. # If the password updated then change our own. If the password was cleared # then restore it. ## _onChanged: (changeMap, areaName) => if changeMap.password @_onPasswordChange changeMap.password if changeMap.server_device @_onServerDeviceChange changeMap.server_device _onPasswordChange: (passwordChange) -> @_log 'password changed from', passwordChange.oldValue, 'to', passwordChange.newValue return if passwordChange.newValue is @password if passwordChange.newValue @password = passwordChange.newValue @chat.setPassword @password else @_log 'password was cleared. Setting password back to', @password @_store 'password', @password _onServerDeviceChange: (serverChange) -> @_log 'device server changed from', serverChange.oldValue?.addr, serverChange.oldValue?.port, 'to', serverChange.newValue?.addr, serverChange.newValue?.port if serverChange.newValue @serverDevice = serverChange.newValue @_chat.remoteConnectionHandler.determineConnection @serverDevice else if @serverDevice @_store 'server_device', @serverDevice ## # Stops storing state items (channel, server, nick). # This is used when the client is resuming it's IRC state and doesn't want # to make redudant writes to storage. ## pause: -> @_paused = true resume: -> @_paused = false setAutostart: (opt_enabled) -> enabled = opt_enabled ? not @_autostart @_autostart = enabled @_store 'autostart', enabled return @_autostart nickChanged: (nick) -> return if @_nick is nick @_nick = nick @_store 'nick', nick channelJoined: (server, name, type='normal') -> return if @_isDuplicateChannel server, name channelObj = { server, name } channelObj.type = type unless type is 'normal' @_channels.push channelObj @_store 'channels', @_channels _isDuplicateChannel: (server, name) -> for chan in @_channels return true if chan.server is server and chan.name is name false serverJoined: (name, port) -> return if @_isDuplicateServer name, port @_servers.push { name, port } @_store 'servers', @_servers _isDuplicateServer: (name, port) -> for server, i in @_servers if server.name is name return true if server.port is port @_servers.splice i, 1 break return false parted: (server, channel) -> if channel? @_channelParted server, channel else @_serverParted server _channelParted: (server, name) -> for channel, i in @_channels if channel.server is server and channel.name is name @_channels.splice i, 1 break @_store 'channels', @_channels _serverParted: (name) -> for server, i in @_servers if server.name is name @_servers.splice i, 1 break @_store 'servers', @_servers _store: (key, value) -> return unless @shouldStore key @_log 'storing', key, '=>', value storageObj = {} storageObj[key] = value chrome.storage.sync.set storageObj shouldStore: (key) -> return not (@_paused and key in Storage.STATE_ITEMS) getState: (chat) -> @_chat = chat ircStates = @_createIRCStates() { ircStates, servers: @_servers, channels: @_channels, nick: @_nick } _createIRCStates: -> ircStates = [] for name, conn of @_chat.connections ircStates.push server: conn.name state: conn.irc.state channels: conn.irc.channels away: conn.irc.away nick: conn.irc.nick ircStates init: (chat) -> @_chat = chat chrome.storage.sync.get Storage.INITIAL_ITEMS, (state) => @_state = state @_restorePassword() @_loadServerDevice() @_autostart = state.autostart restoreSavedState: (chat, opt_callback) -> @_chat = chat chrome.storage.sync.get Storage.STATE_ITEMS, (savedState) => @loadState chat, savedState opt_callback?() loadState: (chat, state) -> @_state = state @_restoreNick() @_restoreServers() @_restoreChannels() @_restoreIRCStates() _restorePassword: -> @password = @_state.password if not @password @password = irc.util.randomName() @_log 'no password found, setting new password to', @password @_store 'password', @password else @_log 'password loaded from storage:', @password @_chat.setPassword @password @_chat.remoteConnectionHandler.determineConnection() _restoreServers: -> return unless servers = @_state.servers @_servers = servers for server in servers @_chat.connect server.name, server.port _restoreChannels: -> return unless channels = @_state.channels @_channels = channels for channel in channels return unless conn = @_chat.connections[channel.server] if channel.type is 'private' @_chat.createPrivateMessageWindow conn, channel.name else @_chat.join conn, channel.name _restoreNick: -> return unless (nick = @_state.nick) and typeof nick is 'string' @_nick = nick @_chat.setNick nick _restoreIRCStates: -> return unless ircStates = @_state.ircStates connectedServers = [] for ircState in ircStates conn = @_chat.connections[ircState.server] connectedServers.push ircState.server @_setIRCState conn, ircState if conn @_disconnectServersWithNoState connectedServers _disconnectServersWithNoState: (connectedServers) -> for name, conn of @_chat.connections conn.irc.state = 'disconnected' unless name in connectedServers ## # Loads servers, channels and nick from the given IRC state. # The state has the following format: # { nick: string, channels: Array.<{sevrer, name}>, # servers: Array.<{name, port}>, irc_state: object, # server_device: { port: number, addr: string}, password: string } # @param {Object} ircState An object that represents the current state of an IRC # client. ## _setIRCState: (conn, ircState) -> @_chat.onConnected conn if ircState.state is 'connected' conn.irc.state = ircState.state if ircState.state conn.irc.away = ircState.away if ircState.away conn.irc.channels = ircState.channels if ircState.channels conn.irc.nick = ircState.nick return unless ircState.channels for channelName, channelInfo of ircState.channels @_chat.onJoined conn, channelName nicks = (nick for norm, nick of channelInfo.names) @_chat.onNames { context: { server: conn.name, channel: channelName } }, nicks _loadServerDevice: -> @loadedServerDevice = true @serverDevice = @_state.server_device @_log 'no remote server found', @_state unless @serverDevice @_log 'loaded server device', @serverDevice if @serverDevice @_chat.remoteConnectionHandler.determineConnection() becomeServerDevice: (connectionInfo) -> @serverDevice = { addr: connectionInfo.addr, port: connectionInfo.port } @_store 'server_device', @serverDevice exports.Storage = Storage
133871
exports = window.chat ?= {} ## # Manages storage. ## class Storage @STATE_ITEMS = ['nick', 'servers', 'channels'] @INITIAL_ITEMS = ['password', 'server_device', 'autostart'] constructor: -> @_log = getLogger this @_channels = [] @_servers = [] @_nick = undefined @_autostart = undefined @password = <PASSWORD> @serverDevice = undefined chrome.storage.onChanged.addListener @_onChanged @pause() ## # Listen for storage changes. # If the password updated then change our own. If the password was cleared # then restore it. ## _onChanged: (changeMap, areaName) => if changeMap.password @_onPasswordChange changeMap.password if changeMap.server_device @_onServerDeviceChange changeMap.server_device _onPasswordChange: (passwordChange) -> @_log 'password changed from', passwordChange.oldValue, 'to', passwordChange.newValue return if passwordChange.newValue is @password if passwordChange.newValue @password = passwordChange.newValue @chat.setPassword @password else @_log 'password was cleared. Setting password back to', @password @_store 'password', @password _onServerDeviceChange: (serverChange) -> @_log 'device server changed from', serverChange.oldValue?.addr, serverChange.oldValue?.port, 'to', serverChange.newValue?.addr, serverChange.newValue?.port if serverChange.newValue @serverDevice = serverChange.newValue @_chat.remoteConnectionHandler.determineConnection @serverDevice else if @serverDevice @_store 'server_device', @serverDevice ## # Stops storing state items (channel, server, nick). # This is used when the client is resuming it's IRC state and doesn't want # to make redudant writes to storage. ## pause: -> @_paused = true resume: -> @_paused = false setAutostart: (opt_enabled) -> enabled = opt_enabled ? not @_autostart @_autostart = enabled @_store 'autostart', enabled return @_autostart nickChanged: (nick) -> return if @_nick is nick @_nick = nick @_store 'nick', nick channelJoined: (server, name, type='normal') -> return if @_isDuplicateChannel server, name channelObj = { server, name } channelObj.type = type unless type is 'normal' @_channels.push channelObj @_store 'channels', @_channels _isDuplicateChannel: (server, name) -> for chan in @_channels return true if chan.server is server and chan.name is name false serverJoined: (name, port) -> return if @_isDuplicateServer name, port @_servers.push { name, port } @_store 'servers', @_servers _isDuplicateServer: (name, port) -> for server, i in @_servers if server.name is name return true if server.port is port @_servers.splice i, 1 break return false parted: (server, channel) -> if channel? @_channelParted server, channel else @_serverParted server _channelParted: (server, name) -> for channel, i in @_channels if channel.server is server and channel.name is name @_channels.splice i, 1 break @_store 'channels', @_channels _serverParted: (name) -> for server, i in @_servers if server.name is name @_servers.splice i, 1 break @_store 'servers', @_servers _store: (key, value) -> return unless @shouldStore key @_log 'storing', key, '=>', value storageObj = {} storageObj[key] = value chrome.storage.sync.set storageObj shouldStore: (key) -> return not (@_paused and key in Storage.STATE_ITEMS) getState: (chat) -> @_chat = chat ircStates = @_createIRCStates() { ircStates, servers: @_servers, channels: @_channels, nick: @_nick } _createIRCStates: -> ircStates = [] for name, conn of @_chat.connections ircStates.push server: conn.name state: conn.irc.state channels: conn.irc.channels away: conn.irc.away nick: conn.irc.nick ircStates init: (chat) -> @_chat = chat chrome.storage.sync.get Storage.INITIAL_ITEMS, (state) => @_state = state @_restorePassword() @_loadServerDevice() @_autostart = state.autostart restoreSavedState: (chat, opt_callback) -> @_chat = chat chrome.storage.sync.get Storage.STATE_ITEMS, (savedState) => @loadState chat, savedState opt_callback?() loadState: (chat, state) -> @_state = state @_restoreNick() @_restoreServers() @_restoreChannels() @_restoreIRCStates() _restorePassword: -> @password = @_state.password if not @password @password = <PASSWORD>() @_log 'no password found, setting new password to', @password @_store 'password', @password else @_log 'password loaded from storage:', @password @_chat.setPassword @password @_chat.remoteConnectionHandler.determineConnection() _restoreServers: -> return unless servers = @_state.servers @_servers = servers for server in servers @_chat.connect server.name, server.port _restoreChannels: -> return unless channels = @_state.channels @_channels = channels for channel in channels return unless conn = @_chat.connections[channel.server] if channel.type is 'private' @_chat.createPrivateMessageWindow conn, channel.name else @_chat.join conn, channel.name _restoreNick: -> return unless (nick = @_state.nick) and typeof nick is 'string' @_nick = nick @_chat.setNick nick _restoreIRCStates: -> return unless ircStates = @_state.ircStates connectedServers = [] for ircState in ircStates conn = @_chat.connections[ircState.server] connectedServers.push ircState.server @_setIRCState conn, ircState if conn @_disconnectServersWithNoState connectedServers _disconnectServersWithNoState: (connectedServers) -> for name, conn of @_chat.connections conn.irc.state = 'disconnected' unless name in connectedServers ## # Loads servers, channels and nick from the given IRC state. # The state has the following format: # { nick: string, channels: Array.<{sevrer, name}>, # servers: Array.<{name, port}>, irc_state: object, # server_device: { port: number, addr: string}, password: string } # @param {Object} ircState An object that represents the current state of an IRC # client. ## _setIRCState: (conn, ircState) -> @_chat.onConnected conn if ircState.state is 'connected' conn.irc.state = ircState.state if ircState.state conn.irc.away = ircState.away if ircState.away conn.irc.channels = ircState.channels if ircState.channels conn.irc.nick = ircState.nick return unless ircState.channels for channelName, channelInfo of ircState.channels @_chat.onJoined conn, channelName nicks = (nick for norm, nick of channelInfo.names) @_chat.onNames { context: { server: conn.name, channel: channelName } }, nicks _loadServerDevice: -> @loadedServerDevice = true @serverDevice = @_state.server_device @_log 'no remote server found', @_state unless @serverDevice @_log 'loaded server device', @serverDevice if @serverDevice @_chat.remoteConnectionHandler.determineConnection() becomeServerDevice: (connectionInfo) -> @serverDevice = { addr: connectionInfo.addr, port: connectionInfo.port } @_store 'server_device', @serverDevice exports.Storage = Storage
true
exports = window.chat ?= {} ## # Manages storage. ## class Storage @STATE_ITEMS = ['nick', 'servers', 'channels'] @INITIAL_ITEMS = ['password', 'server_device', 'autostart'] constructor: -> @_log = getLogger this @_channels = [] @_servers = [] @_nick = undefined @_autostart = undefined @password = PI:PASSWORD:<PASSWORD>END_PI @serverDevice = undefined chrome.storage.onChanged.addListener @_onChanged @pause() ## # Listen for storage changes. # If the password updated then change our own. If the password was cleared # then restore it. ## _onChanged: (changeMap, areaName) => if changeMap.password @_onPasswordChange changeMap.password if changeMap.server_device @_onServerDeviceChange changeMap.server_device _onPasswordChange: (passwordChange) -> @_log 'password changed from', passwordChange.oldValue, 'to', passwordChange.newValue return if passwordChange.newValue is @password if passwordChange.newValue @password = passwordChange.newValue @chat.setPassword @password else @_log 'password was cleared. Setting password back to', @password @_store 'password', @password _onServerDeviceChange: (serverChange) -> @_log 'device server changed from', serverChange.oldValue?.addr, serverChange.oldValue?.port, 'to', serverChange.newValue?.addr, serverChange.newValue?.port if serverChange.newValue @serverDevice = serverChange.newValue @_chat.remoteConnectionHandler.determineConnection @serverDevice else if @serverDevice @_store 'server_device', @serverDevice ## # Stops storing state items (channel, server, nick). # This is used when the client is resuming it's IRC state and doesn't want # to make redudant writes to storage. ## pause: -> @_paused = true resume: -> @_paused = false setAutostart: (opt_enabled) -> enabled = opt_enabled ? not @_autostart @_autostart = enabled @_store 'autostart', enabled return @_autostart nickChanged: (nick) -> return if @_nick is nick @_nick = nick @_store 'nick', nick channelJoined: (server, name, type='normal') -> return if @_isDuplicateChannel server, name channelObj = { server, name } channelObj.type = type unless type is 'normal' @_channels.push channelObj @_store 'channels', @_channels _isDuplicateChannel: (server, name) -> for chan in @_channels return true if chan.server is server and chan.name is name false serverJoined: (name, port) -> return if @_isDuplicateServer name, port @_servers.push { name, port } @_store 'servers', @_servers _isDuplicateServer: (name, port) -> for server, i in @_servers if server.name is name return true if server.port is port @_servers.splice i, 1 break return false parted: (server, channel) -> if channel? @_channelParted server, channel else @_serverParted server _channelParted: (server, name) -> for channel, i in @_channels if channel.server is server and channel.name is name @_channels.splice i, 1 break @_store 'channels', @_channels _serverParted: (name) -> for server, i in @_servers if server.name is name @_servers.splice i, 1 break @_store 'servers', @_servers _store: (key, value) -> return unless @shouldStore key @_log 'storing', key, '=>', value storageObj = {} storageObj[key] = value chrome.storage.sync.set storageObj shouldStore: (key) -> return not (@_paused and key in Storage.STATE_ITEMS) getState: (chat) -> @_chat = chat ircStates = @_createIRCStates() { ircStates, servers: @_servers, channels: @_channels, nick: @_nick } _createIRCStates: -> ircStates = [] for name, conn of @_chat.connections ircStates.push server: conn.name state: conn.irc.state channels: conn.irc.channels away: conn.irc.away nick: conn.irc.nick ircStates init: (chat) -> @_chat = chat chrome.storage.sync.get Storage.INITIAL_ITEMS, (state) => @_state = state @_restorePassword() @_loadServerDevice() @_autostart = state.autostart restoreSavedState: (chat, opt_callback) -> @_chat = chat chrome.storage.sync.get Storage.STATE_ITEMS, (savedState) => @loadState chat, savedState opt_callback?() loadState: (chat, state) -> @_state = state @_restoreNick() @_restoreServers() @_restoreChannels() @_restoreIRCStates() _restorePassword: -> @password = @_state.password if not @password @password = PI:PASSWORD:<PASSWORD>END_PI() @_log 'no password found, setting new password to', @password @_store 'password', @password else @_log 'password loaded from storage:', @password @_chat.setPassword @password @_chat.remoteConnectionHandler.determineConnection() _restoreServers: -> return unless servers = @_state.servers @_servers = servers for server in servers @_chat.connect server.name, server.port _restoreChannels: -> return unless channels = @_state.channels @_channels = channels for channel in channels return unless conn = @_chat.connections[channel.server] if channel.type is 'private' @_chat.createPrivateMessageWindow conn, channel.name else @_chat.join conn, channel.name _restoreNick: -> return unless (nick = @_state.nick) and typeof nick is 'string' @_nick = nick @_chat.setNick nick _restoreIRCStates: -> return unless ircStates = @_state.ircStates connectedServers = [] for ircState in ircStates conn = @_chat.connections[ircState.server] connectedServers.push ircState.server @_setIRCState conn, ircState if conn @_disconnectServersWithNoState connectedServers _disconnectServersWithNoState: (connectedServers) -> for name, conn of @_chat.connections conn.irc.state = 'disconnected' unless name in connectedServers ## # Loads servers, channels and nick from the given IRC state. # The state has the following format: # { nick: string, channels: Array.<{sevrer, name}>, # servers: Array.<{name, port}>, irc_state: object, # server_device: { port: number, addr: string}, password: string } # @param {Object} ircState An object that represents the current state of an IRC # client. ## _setIRCState: (conn, ircState) -> @_chat.onConnected conn if ircState.state is 'connected' conn.irc.state = ircState.state if ircState.state conn.irc.away = ircState.away if ircState.away conn.irc.channels = ircState.channels if ircState.channels conn.irc.nick = ircState.nick return unless ircState.channels for channelName, channelInfo of ircState.channels @_chat.onJoined conn, channelName nicks = (nick for norm, nick of channelInfo.names) @_chat.onNames { context: { server: conn.name, channel: channelName } }, nicks _loadServerDevice: -> @loadedServerDevice = true @serverDevice = @_state.server_device @_log 'no remote server found', @_state unless @serverDevice @_log 'loaded server device', @serverDevice if @serverDevice @_chat.remoteConnectionHandler.determineConnection() becomeServerDevice: (connectionInfo) -> @serverDevice = { addr: connectionInfo.addr, port: connectionInfo.port } @_store 'server_device', @serverDevice exports.Storage = Storage
[ { "context": "ot caught in too much rain on the way back.”\n\n**\n\nGabe sat on a cold concrete bench at a cold, round, co", "end": 2499, "score": 0.96146559715271, "start": 2495, "tag": "NAME", "value": "Gabe" }, { "context": "ast the sky is doing what they’re all thinking.”\n\nGabe looked up the nearly deserted road and noticed tw", "end": 3372, "score": 0.8202597498893738, "start": 3368, "tag": "NAME", "value": "Gabe" }, { "context": "e mist and entering the Kmart parking lot. Amused, Gabe wondered whether the pair might tie their horses ", "end": 3616, "score": 0.7744344472885132, "start": 3612, "tag": "NAME", "value": "Gabe" }, { "context": "er horse. She nimbly saddled up again, and she and Jib then began perusing the aisles of the Kmart and", "end": 4164, "score": 0.7976972460746765, "start": 4163, "tag": "NAME", "value": "J" }, { "context": "me over here RIGHT NOW and received no response.\n\nPoli caught up with Jib and together they loaded dry ", "end": 5452, "score": 0.6562012434005737, "start": 5449, "tag": "NAME", "value": "Pol" }, { "context": "NOW and received no response.\n\nPoli caught up with Jib and together they loaded dry beans and rice int", "end": 5470, "score": 0.7858109474182129, "start": 5469, "tag": "NAME", "value": "J" }, { "context": "e to get those for Elo. I bet they’ll be perfect!” Poli shouted to Jib, and she urged her horse forward.", "end": 5810, "score": 0.7283002734184265, "start": 5807, "tag": "NAME", "value": "Pol" }, { "context": "or Elo. I bet they’ll be perfect!” Poli shouted to Jib, and she urged her horse forward. Jib rode afte", "end": 5824, "score": 0.582439124584198, "start": 5823, "tag": "NAME", "value": "J" }, { "context": "ety of cookies, snack cakes, and other treats, and Poli and Jib were, for the first time, ill at ease in", "end": 6057, "score": 0.7094526886940002, "start": 6054, "tag": "NAME", "value": "Pol" }, { "context": " she smiled shyly, handing up a box.\n\n“Thank you,” Jib smiled back. He tore into the box and passed a ha", "end": 6247, "score": 0.784315824508667, "start": 6244, "tag": "NAME", "value": "Jib" }, { "context": "ou help us load our cart with every box there is?” Poli asked.\n\n“Not every box. I want to have three for", "end": 6537, "score": 0.5059499144554138, "start": 6534, "tag": "NAME", "value": "Pol" }, { "context": " vanilla, and Jib and Poli rode to the checkout.\n\nPoli pulled a small wooden box from her canvas messeng", "end": 7173, "score": 0.9924248456954956, "start": 7169, "tag": "NAME", "value": "Poli" }, { "context": "han enough payment for these goods in our cart.”\n\nPoli and Jib rode out of the store, cart still in tow,", "end": 7445, "score": 0.9885722398757935, "start": 7441, "tag": "NAME", "value": "Poli" }, { "context": "gh payment for these goods in our cart.”\n\nPoli and Jib rode out of the store, cart still in tow, as Gabe", "end": 7453, "score": 0.9939182996749878, "start": 7450, "tag": "NAME", "value": "Jib" }, { "context": "d Jib rode out of the store, cart still in tow, as Gabe came back in. The two riders disappeared into the", "end": 7503, "score": 0.9889717102050781, "start": 7499, "tag": "NAME", "value": "Gabe" }, { "context": "red into the night.\n\nThe employees surrounded him. Gabe said nothing. He strolled through the store, surv", "end": 7596, "score": 0.9919022917747498, "start": 7592, "tag": "NAME", "value": "Gabe" }, { "context": "sles 6, 7, 10, and 12. Better get a shovel.”\n\n**\n\nElo drifted to sleep that night, completely content, ", "end": 7849, "score": 0.9877679347991943, "start": 7846, "tag": "NAME", "value": "Elo" }, { "context": "blue light bathed them both.\n\n“What is your name?” Elo asked.\n\n“Theodosia,” the girl answered. The girl ", "end": 8151, "score": 0.9882445335388184, "start": 8148, "tag": "NAME", "value": "Elo" }, { "context": "hed them both.\n\n“What is your name?” Elo asked.\n\n“Theodosia,” the girl answered. The girl flew up to meet Elo", "end": 8170, "score": 0.970725417137146, "start": 8161, "tag": "NAME", "value": "Theodosia" }, { "context": "osia,” the girl answered. The girl flew up to meet Elo and they soared effortlessly through the ceiling ", "end": 8220, "score": 0.9480379819869995, "start": 8217, "tag": "NAME", "value": "Elo" }, { "context": "onths later, in the middle of another rainy night, Elo gave birth to a baby girl. The child was dusted w", "end": 8355, "score": 0.9304301738739014, "start": 8352, "tag": "NAME", "value": "Elo" }, { "context": " bluest eyes she had ever seen. She named the girl Theodosia.\n\n\"\"\"\n", "end": 8516, "score": 0.9520795345306396, "start": 8507, "tag": "NAME", "value": "Theodosia" } ]
stories/blue-light-special.coffee
STRd6/zine
12
module.exports = """ Blue Light Special “You know, I really want some cookies.” Elo said. She sat on a cushion on top of a tarp spread on the ground in front of their small campfire and whittled a piece of wood, periodically tossing the shavings into the fire. The warm glow bathed her deft fingers, tired face, and honey-colored hair with a soft light, and faintly illuminated the oak trees around them in the pressing darkness. “We can break camp tomorrow, move on, and see what we can find on the way,” Jib replied, as he munched some popcorn and scratched his dark beard. He scooted his log seat closer to the fire and buttoned his shearling jacket to keep out the fine mist rolling in among the trees. “I don’t want to break camp,” Elo protested. “I like it here. We should stay a while. I just want to have some cookies.” She looked around their camp: at Jib on his stump; at Poli beside her on the tarp, seated on her own cushion; at their reliable and well-used tent; at the horses draped with their blankets; at the clean dishes drying fireside. This was a good place. She rubbed her ever-growing abdomen. The tiny person ensconced within dragged a heel over her insides in response. “Okay, we won’t break camp, then. We can just go to town tomorrow. We need some other supplies anyway.” Jib raised his lanky body to pass the popcorn to Poli, who took the enameled bowl and placed it between her and Elo. Poli offered the popcorn to Elo. “Here, have some popcorn. That will help take your mind off the craving.” Elo knitted her brows. “No, it won’t. It’s not the same and you know it.” “Yeah, okay. I know. It’s not. But it’s what we have,” Poli smiled gently, hoping to diffuse the situation. “Why can’t you just go get some now? We didn’t camp that far from town, and it’s not that late,” Elo pleaded. “Because it’s going to rain soon, and because I’m tired, and because we decide things together, not based on whim,” Jib retorted grumpily. “Pleeeeeease! I really, really want them. I’m tired too and my back hurts from hauling this baby around and I just want to have some cookies. Is that too much to ask?” Elo burst into tears. “Elo, please don’t cry.” Poli’s red curls bounced as she snapped her head up to glare at Jib. She enfolded Elo in a hug, and Elo sobbed harder on the petite woman’s shoulder. “Poli, come on,” Jib sighed. “Get Elo settled in the tent and you and I will go tonight. Let’s get moving so we’re not caught in too much rain on the way back.” ** Gabe sat on a cold concrete bench at a cold, round, concrete table, eating cold pizza under a murky and unforgiving sky in which clouds entirely obscured the stars, and in which mist threatened to give way to outright rain. He reflected miserably that of all the ways to eat pizza, this was probably the second-worst. The worst would be back in the break room with the other Kmart employees, where they would have excited yet hushed conversations that did not include him, the night manager. The table he was sitting at had recently had a fiberglass umbrella to provide meager protection against the elements. Last week, however, seven drunk teenagers had removed it to use as a boat in a very large puddle at the back of the parking lot and it had not been seen since. The sky began to spit at him, and he thought, “At least the sky is doing what they’re all thinking.” Gabe looked up the nearly deserted road and noticed two large figures with an odd gait. They resolved into a tall, bearded man and a petite, redheaded woman, each on horseback, emerging from the mist and entering the Kmart parking lot. Amused, Gabe wondered whether the pair might tie their horses up to the bike racks, or find a parking space near a lamp post and hitch them there, or tether them to a tree. The man and woman did none of these things. They simply rode the horses through the automatic doors and into the Kmart. Gabe took a moment to process this. He started to get up, looked at his phone, noticed ten minutes remained of his break, and sat back down. ** Poli dismounted inside the doors and hitched up a shopping cart to her horse. She nimbly saddled up again, and she and Jib then began perusing the aisles of the Kmart and checking the items off their list. “Sir? Miss? Can I help you?” an employee demanded tersely, body language suggesting the only help would be toward an exit. “Yes, thank you. We are looking for cookies such as would satisfy a pregnancy craving,” Jib replied. He placed some batteries in their cart. “Cookies? Aisle 12A,” the employee responded automatically, then shook her head. “The horses. You can’t have them in here. You’ll have to take them outside.” The employee was joined by two others, all of them looking simultaneously stern and bewildered. They reached the aisle’s endcap. “Ooh, look, nut mixes are on sale,” Poli grinned. “Go ahead and get a few,” Jib called to her as he rode ahead to select some prenatal vitamins and toothpaste. “Miss, please. The two of you need to take the horses outside,” the employee wheedled. As if to respond, Poli’s horse lifted its tail and dropped a steaming load near the employee’s boot. The employee leapt back, dismayed. “Oh, no, I’m afraid that won’t be possible. These are our service animals,” Poli chirped sweetly. The employees huddled together. “Where’s Gabe?” they worried. They barked into walkie-talkies to Gabe to come over here RIGHT NOW and received no response. Poli caught up with Jib and together they loaded dry beans and rice into the cart. Suddenly, a voice spoke, as if from the heavens, and a flashing blue light punctuated the announcement: “Attention, Kmart shoppers! Blue light special on Aisle 12A. Tedwich Sandwich Cookies, buy two, get one free!” “We have to get those for Elo. I bet they’ll be perfect!” Poli shouted to Jib, and she urged her horse forward. Jib rode after her, followed by the three ineffectual employees, and an ever-growing crowd of onlookers. Aisle 12A displayed an alarming variety of cookies, snack cakes, and other treats, and Poli and Jib were, for the first time, ill at ease in the Kmart. A small girl with braids and cutoff jeans approached them. “Here you go,” she smiled shyly, handing up a box. “Thank you,” Jib smiled back. He tore into the box and passed a handful of the Tedwich cookies to Poli. They sampled the miniature bear-shaped cinnamon cookies sandwiching a vanilla cream filling. They were, indeed, exactly what Elo would love. “Can you help us load our cart with every box there is?” Poli asked. “Not every box. I want to have three for myself,” the girl quickly replied. “Done.” With all but three boxes of Tedwich cookies in their cart, the only thing left was to find some ice cream to go with them. This expedition caused no small amount of chaos in the freezer case aisle when a small, yappy dog in a handbag spooked the horses, which in turn sent the crowd scattering in all directions. Fortunately, it also resulted in Jib’s horse being perfectly positioned in front of a case containing pint after pint of ice cream. They selected one of chocolate and one of vanilla, and Jib and Poli rode to the checkout. Poli pulled a small wooden box from her canvas messenger bag and handed it down to the cashier. “This is a very rare and ancient turtle, carved from an unknown precious stone to bring the bearer untold riches. It is more than enough payment for these goods in our cart.” Poli and Jib rode out of the store, cart still in tow, as Gabe came back in. The two riders disappeared into the night. The employees surrounded him. Gabe said nothing. He strolled through the store, surveying the relative lack of damage, the confused shoppers, and the piles of manure, and he grinned as he reached for his walkie-talkie. “Cleanup on Aisles 6, 7, 10, and 12. Better get a shovel.” ** Elo drifted to sleep that night, completely content, filled with cookies and ice cream. She dreamed of a girl with braids and cutoff jeans, holding boxes and boxes of Tedwich cookies stacked higher than she was tall. She flew above the girl as a deep blue light bathed them both. “What is your name?” Elo asked. “Theodosia,” the girl answered. The girl flew up to meet Elo and they soared effortlessly through the ceiling and out into the mist. Three months later, in the middle of another rainy night, Elo gave birth to a baby girl. The child was dusted with cinnamon freckles and looked up at Elo with the bluest eyes she had ever seen. She named the girl Theodosia. """
208742
module.exports = """ Blue Light Special “You know, I really want some cookies.” Elo said. She sat on a cushion on top of a tarp spread on the ground in front of their small campfire and whittled a piece of wood, periodically tossing the shavings into the fire. The warm glow bathed her deft fingers, tired face, and honey-colored hair with a soft light, and faintly illuminated the oak trees around them in the pressing darkness. “We can break camp tomorrow, move on, and see what we can find on the way,” Jib replied, as he munched some popcorn and scratched his dark beard. He scooted his log seat closer to the fire and buttoned his shearling jacket to keep out the fine mist rolling in among the trees. “I don’t want to break camp,” Elo protested. “I like it here. We should stay a while. I just want to have some cookies.” She looked around their camp: at Jib on his stump; at Poli beside her on the tarp, seated on her own cushion; at their reliable and well-used tent; at the horses draped with their blankets; at the clean dishes drying fireside. This was a good place. She rubbed her ever-growing abdomen. The tiny person ensconced within dragged a heel over her insides in response. “Okay, we won’t break camp, then. We can just go to town tomorrow. We need some other supplies anyway.” Jib raised his lanky body to pass the popcorn to Poli, who took the enameled bowl and placed it between her and Elo. Poli offered the popcorn to Elo. “Here, have some popcorn. That will help take your mind off the craving.” Elo knitted her brows. “No, it won’t. It’s not the same and you know it.” “Yeah, okay. I know. It’s not. But it’s what we have,” Poli smiled gently, hoping to diffuse the situation. “Why can’t you just go get some now? We didn’t camp that far from town, and it’s not that late,” Elo pleaded. “Because it’s going to rain soon, and because I’m tired, and because we decide things together, not based on whim,” Jib retorted grumpily. “Pleeeeeease! I really, really want them. I’m tired too and my back hurts from hauling this baby around and I just want to have some cookies. Is that too much to ask?” Elo burst into tears. “Elo, please don’t cry.” Poli’s red curls bounced as she snapped her head up to glare at Jib. She enfolded Elo in a hug, and Elo sobbed harder on the petite woman’s shoulder. “Poli, come on,” Jib sighed. “Get Elo settled in the tent and you and I will go tonight. Let’s get moving so we’re not caught in too much rain on the way back.” ** <NAME> sat on a cold concrete bench at a cold, round, concrete table, eating cold pizza under a murky and unforgiving sky in which clouds entirely obscured the stars, and in which mist threatened to give way to outright rain. He reflected miserably that of all the ways to eat pizza, this was probably the second-worst. The worst would be back in the break room with the other Kmart employees, where they would have excited yet hushed conversations that did not include him, the night manager. The table he was sitting at had recently had a fiberglass umbrella to provide meager protection against the elements. Last week, however, seven drunk teenagers had removed it to use as a boat in a very large puddle at the back of the parking lot and it had not been seen since. The sky began to spit at him, and he thought, “At least the sky is doing what they’re all thinking.” <NAME> looked up the nearly deserted road and noticed two large figures with an odd gait. They resolved into a tall, bearded man and a petite, redheaded woman, each on horseback, emerging from the mist and entering the Kmart parking lot. Amused, <NAME> wondered whether the pair might tie their horses up to the bike racks, or find a parking space near a lamp post and hitch them there, or tether them to a tree. The man and woman did none of these things. They simply rode the horses through the automatic doors and into the Kmart. Gabe took a moment to process this. He started to get up, looked at his phone, noticed ten minutes remained of his break, and sat back down. ** Poli dismounted inside the doors and hitched up a shopping cart to her horse. She nimbly saddled up again, and she and <NAME>ib then began perusing the aisles of the Kmart and checking the items off their list. “Sir? Miss? Can I help you?” an employee demanded tersely, body language suggesting the only help would be toward an exit. “Yes, thank you. We are looking for cookies such as would satisfy a pregnancy craving,” Jib replied. He placed some batteries in their cart. “Cookies? Aisle 12A,” the employee responded automatically, then shook her head. “The horses. You can’t have them in here. You’ll have to take them outside.” The employee was joined by two others, all of them looking simultaneously stern and bewildered. They reached the aisle’s endcap. “Ooh, look, nut mixes are on sale,” Poli grinned. “Go ahead and get a few,” Jib called to her as he rode ahead to select some prenatal vitamins and toothpaste. “Miss, please. The two of you need to take the horses outside,” the employee wheedled. As if to respond, Poli’s horse lifted its tail and dropped a steaming load near the employee’s boot. The employee leapt back, dismayed. “Oh, no, I’m afraid that won’t be possible. These are our service animals,” Poli chirped sweetly. The employees huddled together. “Where’s Gabe?” they worried. They barked into walkie-talkies to Gabe to come over here RIGHT NOW and received no response. <NAME>i caught up with <NAME>ib and together they loaded dry beans and rice into the cart. Suddenly, a voice spoke, as if from the heavens, and a flashing blue light punctuated the announcement: “Attention, Kmart shoppers! Blue light special on Aisle 12A. Tedwich Sandwich Cookies, buy two, get one free!” “We have to get those for Elo. I bet they’ll be perfect!” <NAME>i shouted to <NAME>ib, and she urged her horse forward. Jib rode after her, followed by the three ineffectual employees, and an ever-growing crowd of onlookers. Aisle 12A displayed an alarming variety of cookies, snack cakes, and other treats, and <NAME>i and Jib were, for the first time, ill at ease in the Kmart. A small girl with braids and cutoff jeans approached them. “Here you go,” she smiled shyly, handing up a box. “Thank you,” <NAME> smiled back. He tore into the box and passed a handful of the Tedwich cookies to Poli. They sampled the miniature bear-shaped cinnamon cookies sandwiching a vanilla cream filling. They were, indeed, exactly what Elo would love. “Can you help us load our cart with every box there is?” <NAME>i asked. “Not every box. I want to have three for myself,” the girl quickly replied. “Done.” With all but three boxes of Tedwich cookies in their cart, the only thing left was to find some ice cream to go with them. This expedition caused no small amount of chaos in the freezer case aisle when a small, yappy dog in a handbag spooked the horses, which in turn sent the crowd scattering in all directions. Fortunately, it also resulted in Jib’s horse being perfectly positioned in front of a case containing pint after pint of ice cream. They selected one of chocolate and one of vanilla, and Jib and Poli rode to the checkout. <NAME> pulled a small wooden box from her canvas messenger bag and handed it down to the cashier. “This is a very rare and ancient turtle, carved from an unknown precious stone to bring the bearer untold riches. It is more than enough payment for these goods in our cart.” <NAME> and <NAME> rode out of the store, cart still in tow, as <NAME> came back in. The two riders disappeared into the night. The employees surrounded him. <NAME> said nothing. He strolled through the store, surveying the relative lack of damage, the confused shoppers, and the piles of manure, and he grinned as he reached for his walkie-talkie. “Cleanup on Aisles 6, 7, 10, and 12. Better get a shovel.” ** <NAME> drifted to sleep that night, completely content, filled with cookies and ice cream. She dreamed of a girl with braids and cutoff jeans, holding boxes and boxes of Tedwich cookies stacked higher than she was tall. She flew above the girl as a deep blue light bathed them both. “What is your name?” <NAME> asked. “<NAME>,” the girl answered. The girl flew up to meet <NAME> and they soared effortlessly through the ceiling and out into the mist. Three months later, in the middle of another rainy night, <NAME> gave birth to a baby girl. The child was dusted with cinnamon freckles and looked up at Elo with the bluest eyes she had ever seen. She named the girl <NAME>. """
true
module.exports = """ Blue Light Special “You know, I really want some cookies.” Elo said. She sat on a cushion on top of a tarp spread on the ground in front of their small campfire and whittled a piece of wood, periodically tossing the shavings into the fire. The warm glow bathed her deft fingers, tired face, and honey-colored hair with a soft light, and faintly illuminated the oak trees around them in the pressing darkness. “We can break camp tomorrow, move on, and see what we can find on the way,” Jib replied, as he munched some popcorn and scratched his dark beard. He scooted his log seat closer to the fire and buttoned his shearling jacket to keep out the fine mist rolling in among the trees. “I don’t want to break camp,” Elo protested. “I like it here. We should stay a while. I just want to have some cookies.” She looked around their camp: at Jib on his stump; at Poli beside her on the tarp, seated on her own cushion; at their reliable and well-used tent; at the horses draped with their blankets; at the clean dishes drying fireside. This was a good place. She rubbed her ever-growing abdomen. The tiny person ensconced within dragged a heel over her insides in response. “Okay, we won’t break camp, then. We can just go to town tomorrow. We need some other supplies anyway.” Jib raised his lanky body to pass the popcorn to Poli, who took the enameled bowl and placed it between her and Elo. Poli offered the popcorn to Elo. “Here, have some popcorn. That will help take your mind off the craving.” Elo knitted her brows. “No, it won’t. It’s not the same and you know it.” “Yeah, okay. I know. It’s not. But it’s what we have,” Poli smiled gently, hoping to diffuse the situation. “Why can’t you just go get some now? We didn’t camp that far from town, and it’s not that late,” Elo pleaded. “Because it’s going to rain soon, and because I’m tired, and because we decide things together, not based on whim,” Jib retorted grumpily. “Pleeeeeease! I really, really want them. I’m tired too and my back hurts from hauling this baby around and I just want to have some cookies. Is that too much to ask?” Elo burst into tears. “Elo, please don’t cry.” Poli’s red curls bounced as she snapped her head up to glare at Jib. She enfolded Elo in a hug, and Elo sobbed harder on the petite woman’s shoulder. “Poli, come on,” Jib sighed. “Get Elo settled in the tent and you and I will go tonight. Let’s get moving so we’re not caught in too much rain on the way back.” ** PI:NAME:<NAME>END_PI sat on a cold concrete bench at a cold, round, concrete table, eating cold pizza under a murky and unforgiving sky in which clouds entirely obscured the stars, and in which mist threatened to give way to outright rain. He reflected miserably that of all the ways to eat pizza, this was probably the second-worst. The worst would be back in the break room with the other Kmart employees, where they would have excited yet hushed conversations that did not include him, the night manager. The table he was sitting at had recently had a fiberglass umbrella to provide meager protection against the elements. Last week, however, seven drunk teenagers had removed it to use as a boat in a very large puddle at the back of the parking lot and it had not been seen since. The sky began to spit at him, and he thought, “At least the sky is doing what they’re all thinking.” PI:NAME:<NAME>END_PI looked up the nearly deserted road and noticed two large figures with an odd gait. They resolved into a tall, bearded man and a petite, redheaded woman, each on horseback, emerging from the mist and entering the Kmart parking lot. Amused, PI:NAME:<NAME>END_PI wondered whether the pair might tie their horses up to the bike racks, or find a parking space near a lamp post and hitch them there, or tether them to a tree. The man and woman did none of these things. They simply rode the horses through the automatic doors and into the Kmart. Gabe took a moment to process this. He started to get up, looked at his phone, noticed ten minutes remained of his break, and sat back down. ** Poli dismounted inside the doors and hitched up a shopping cart to her horse. She nimbly saddled up again, and she and PI:NAME:<NAME>END_PIib then began perusing the aisles of the Kmart and checking the items off their list. “Sir? Miss? Can I help you?” an employee demanded tersely, body language suggesting the only help would be toward an exit. “Yes, thank you. We are looking for cookies such as would satisfy a pregnancy craving,” Jib replied. He placed some batteries in their cart. “Cookies? Aisle 12A,” the employee responded automatically, then shook her head. “The horses. You can’t have them in here. You’ll have to take them outside.” The employee was joined by two others, all of them looking simultaneously stern and bewildered. They reached the aisle’s endcap. “Ooh, look, nut mixes are on sale,” Poli grinned. “Go ahead and get a few,” Jib called to her as he rode ahead to select some prenatal vitamins and toothpaste. “Miss, please. The two of you need to take the horses outside,” the employee wheedled. As if to respond, Poli’s horse lifted its tail and dropped a steaming load near the employee’s boot. The employee leapt back, dismayed. “Oh, no, I’m afraid that won’t be possible. These are our service animals,” Poli chirped sweetly. The employees huddled together. “Where’s Gabe?” they worried. They barked into walkie-talkies to Gabe to come over here RIGHT NOW and received no response. PI:NAME:<NAME>END_PIi caught up with PI:NAME:<NAME>END_PIib and together they loaded dry beans and rice into the cart. Suddenly, a voice spoke, as if from the heavens, and a flashing blue light punctuated the announcement: “Attention, Kmart shoppers! Blue light special on Aisle 12A. Tedwich Sandwich Cookies, buy two, get one free!” “We have to get those for Elo. I bet they’ll be perfect!” PI:NAME:<NAME>END_PIi shouted to PI:NAME:<NAME>END_PIib, and she urged her horse forward. Jib rode after her, followed by the three ineffectual employees, and an ever-growing crowd of onlookers. Aisle 12A displayed an alarming variety of cookies, snack cakes, and other treats, and PI:NAME:<NAME>END_PIi and Jib were, for the first time, ill at ease in the Kmart. A small girl with braids and cutoff jeans approached them. “Here you go,” she smiled shyly, handing up a box. “Thank you,” PI:NAME:<NAME>END_PI smiled back. He tore into the box and passed a handful of the Tedwich cookies to Poli. They sampled the miniature bear-shaped cinnamon cookies sandwiching a vanilla cream filling. They were, indeed, exactly what Elo would love. “Can you help us load our cart with every box there is?” PI:NAME:<NAME>END_PIi asked. “Not every box. I want to have three for myself,” the girl quickly replied. “Done.” With all but three boxes of Tedwich cookies in their cart, the only thing left was to find some ice cream to go with them. This expedition caused no small amount of chaos in the freezer case aisle when a small, yappy dog in a handbag spooked the horses, which in turn sent the crowd scattering in all directions. Fortunately, it also resulted in Jib’s horse being perfectly positioned in front of a case containing pint after pint of ice cream. They selected one of chocolate and one of vanilla, and Jib and Poli rode to the checkout. PI:NAME:<NAME>END_PI pulled a small wooden box from her canvas messenger bag and handed it down to the cashier. “This is a very rare and ancient turtle, carved from an unknown precious stone to bring the bearer untold riches. It is more than enough payment for these goods in our cart.” PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI rode out of the store, cart still in tow, as PI:NAME:<NAME>END_PI came back in. The two riders disappeared into the night. The employees surrounded him. PI:NAME:<NAME>END_PI said nothing. He strolled through the store, surveying the relative lack of damage, the confused shoppers, and the piles of manure, and he grinned as he reached for his walkie-talkie. “Cleanup on Aisles 6, 7, 10, and 12. Better get a shovel.” ** PI:NAME:<NAME>END_PI drifted to sleep that night, completely content, filled with cookies and ice cream. She dreamed of a girl with braids and cutoff jeans, holding boxes and boxes of Tedwich cookies stacked higher than she was tall. She flew above the girl as a deep blue light bathed them both. “What is your name?” PI:NAME:<NAME>END_PI asked. “PI:NAME:<NAME>END_PI,” the girl answered. The girl flew up to meet PI:NAME:<NAME>END_PI and they soared effortlessly through the ceiling and out into the mist. Three months later, in the middle of another rainy night, PI:NAME:<NAME>END_PI gave birth to a baby girl. The child was dusted with cinnamon freckles and looked up at Elo with the bluest eyes she had ever seen. She named the girl PI:NAME:<NAME>END_PI. """
[ { "context": "word:\n label: 'Password'\n description:", "end": 106195, "score": 0.8320892453193665, "start": 106187, "tag": "PASSWORD", "value": "Password" }, { "context": " description: 'Password to authenticate with Splunk'\n ", "end": 106255, "score": 0.5214424729347229, "start": 106247, "tag": "PASSWORD", "value": "Password" } ]
cyclotron-site/app/scripts/common/services/services.commonConfigService.coffee
smartcommunitylab/cyclotron
1
### # Copyright (c) 2013-2015 the original author or authors. # # Licensed under the MIT License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.opensource.org/licenses/mit-license.php # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific # language governing permissions and limitations under the License. ### # Common Config File - all default or shared configs cyclotronServices.factory 'commonConfigService', -> linkedWidgetOptions = (dashboard) -> linkedWidgets = {} _.each dashboard.pages, (page, pageIndex) -> _.each page.widgets, (widget, widgetIndex) -> return if widget.widget == 'linkedWidget' widgetName = _.titleCase(widget.widget) if widget.name?.length > 0 or widget.title?.length > 0 widgetName += ': ' + (widget.name || widget.title) linkedWidgets['Page ' + (pageIndex + 1) + ': ' + widgetName] = { value: pageIndex + ',' + widgetIndex } linkedWidgets datasourceOptions = (dashboard) -> dataSources = {} _.each dashboard.dataSources, (dataSource) -> dataSources[dataSource.name] = { value: dataSource.name } dataSources exports = { version: '1.48.0' logging: enableDebug: false authentication: enable: false loginMessage: 'Please login using your LDAP username and password.' analytics: enable: false newUser: enableMessage: true welcomeMessage: 'It looks like you\'re new here! Take a look at the <a href="/help"><i class="fa fa-question-circle" /> Help</a> page.' iconClass: 'fa-info' autoDecayDuration: 1 # Dashboard settings dashboard: properties: name: label: 'Name' description: 'Dashboard Name. This is required and cannot be changed after the Dashboard is created.' placeholder: 'Dashboard Name' type: 'string' required: true order: 0 displayName: label: 'Display Name' description: 'Display Name; this is displayed in the browser title bar or the Header Widget.' placeholder: 'Display Name' type: 'string' required: false inlineJs: true defaultHidden: true order: 1 description: label: 'Description' description: 'A short summary of the Dashboard\'s purpose or capabilities.' placeholder: 'A short summary of the Dashboard\'s purpose or capabilities.' type: 'string' required: false order: 2 theme: label: 'Theme' description: 'The default Page Theme for the Dashboard. If this property is set, the value will be applied to any Pages that have not specified a Theme. If it is not set, the default value of "Dark" will be used.' type: 'string' default: 'dark' required: false options: charcoal: label: 'Charcoal' value: 'charcoal' dashboardBackgroundColor: '#1E2328' dark: label: 'Dark' value: 'dark' dashboardBackgroundColor: '#2f2f2f' darkmetro: label: 'Dark Metro' value: 'darkmetro' dashboardBackgroundColor: '#2f2f2f' gto: label: 'GTO' value: 'gto' dashboardBackgroundColor: 'white' light: label: 'Light' value: 'light' dashboardBackgroundColor: 'white' lightborderless: label: 'Light (borderless)' value: 'lightborderless' dashboardBackgroundColor: 'white' dark2: label: 'Very Dark' value: 'dark2' dashboardBackgroundColor: 'black' order: 5 themeVariant: label: 'Theme Variant' description: 'The default Theme Variant for the Dashboard; each Theme may or may not implement each variant. If this property is set, the value will be applies to any Pages that have not specified a Theme Variant. If it is not set, the default variant will be used.' type: 'string' default: 'default' required: false defaultHidden: true options: default: value: 'default' transparent: value: 'transparent' 'transparent-unpadded': value: 'transparent-unpadded' order: 6 style: label: 'Style' description: 'The default Page Style for the Dashboard. If this property is set, the value will be applied to any Pages that have not specified a Style. If it is not set, the default value of "Normal" will be used.' type: 'string' default: 'normal' required: false options: normal: value: 'normal' fullscreen: value: 'fullscreen' defaultHidden: true order: 7 autoRotate: label: 'Auto-Rotate' description: 'If set to true, Cyclotron will automatically rotate between pages of the Dashboard based on the duration property for each Page. Set this value false to require manual rotation.' type: 'boolean' default: false required: false defaultHidden: true order: 10 duration: label: 'Auto-Rotate Duration (seconds)' description: 'If autoRotate is enabled, this controls the default interval to rotate to the next page. This value can be overridded at a page level.' type: 'integer' placeholder: 'Seconds per page' default: 60 required: false defaultHidden: true order: 11 preload: label: 'Pre-Load Time (seconds)' description: 'The amount of time, in seconds, before rotating to preload the next page. If set, this value will apply to all pages in the Dashboard. If autoRotate is false, this value is ignored.' placeholder: 'Seconds' type: 'integer' default: 0.050 required: false defaultHidden: true order: 12 allowFullscreen: label: 'Allow Fullscreen' description: 'If true, each Widget on a Page can be maximized to fill the entire Dashboard. This setting can be overridden by each Page/Widget.' type: 'boolean' default: true required: false defaultHidden: true allowExport: label: 'Allow Export' description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This setting can be overridden by each Page/Widget.' type: 'boolean' default: true required: false defaultHidden: true openLinksInNewWindow: label: 'Open Links in New Window' description: 'If true, all links will open in a new browser window; this is the default.' type: 'boolean' required: false default: true defaultHidden: true showWidgetErrors: label: 'Show Error Messages on Widgets' description: 'If true, allows error messages to be displayed on Widgets. This setting can be overridden by each Page/Widget.' type: 'boolean' required: false default: true defaultHidden: true showDashboardControls: label: 'Show Dashboard Controls' description: 'If false, hides the default Dashboard controls (rotation, export, etc)' type: 'boolean' required: false default: true defaultHidden: true sidebar: label: 'Sidebar' description: '' type: 'propertyset' default: {} defaultHidden: true properties: showDashboardSidebar: label: 'Show Dashboard Sidebar' description: 'If false, hides the default Dashboard Sidebar.' type: 'boolean' required: false default: false order: 10 showDashboardTitle: label: 'Include Dashboard Title' description: 'Enables a section of the sidebar for the Dashboard title.' type: 'boolean' required: false default: true defaultHidden: true order: 11 showToolbar: label: 'Include Toolbar' description: 'Enables a toolbar in the sidebar.' type: 'boolean' required: false default: true defaultHidden: true order: 12 showHideWidgets: label: 'Include Show/Hide Widgets' description: 'Enables a section of the sidebar for overriding the visibility of Widgets.' type: 'boolean' required: false default: false defaultHidden: true order: 13 sidebarContent: label: 'Custom Sidebar Sections' singleLabel: 'Section' description: 'One or more sections of content to display in the Sidebar.' type: 'propertyset[]' default: [] order: 15 properties: heading: label: 'Heading' description: 'Heading for the Sidebar section.' type: 'string' inlineJs: true order: 1 html: label: 'HTML Content' description: 'HTML Content to display.' placeholder: 'Value' type: 'editor' editorMode: 'html' inlineJs: true order: 2 pages: label: 'Pages' description: 'The list of Page definitions which compose the Dashboard.' type: 'pages' default: [] required: true properties: name: label: 'Name' description: 'Name of this page; used in the browser title and URL.' placeholder: 'Page Name' type: 'string' required: false order: 0 layout: label: 'Layout' description: 'Contains properties for configuring the Page layout and dimensions.' type: 'propertyset' default: {} required: false properties: gridColumns: label: 'Grid Columns' description: 'Specifies the total number of horizonal grid squares available in the grid. The grid squares will be scaled to fit the browser window. If omitted, the number of columns will be calculated dynamically.' type: 'integer' required: false order: 0 gridRows: label: 'Grid Rows' description: 'Specifies the total number of vertical grid squares available in the grid. The grid squares will be scaled vertically to fit the browser window. If omitted, the grid squares will be literally square, e.g. the height and width will be the same. When omitted, the widgets may not fill the entire browser window, or they may scroll vertically. Use this property to make widgets scale vertically to fit the dashboard.' type: 'integer' required: false order: 1 gridWidthAdjustment: label: 'Grid Page Width Adjustment' description: 'Specifies an adjustment (in pixels) to the width of the page when calculating the grid layout. If the value is positive, the page width will have the adjustment added to it (making each column wider), whereas if it is negative, the page width will be reduced (making each column skinnier).' type: 'integer' default: 0 required: false defaultHidden: true order: 2 gridHeightAdjustment: label: 'Grid Page Height Adjustment' description: 'Specifies an adjustment (in pixels) to the height of the page when calculating the grid layout. If the value is positive, the page height will have the adjustment added to it (making each row taller), whereas if it is negative, the page height will be reduced (making each row shorter). This is commonly used with a fixed-height Header widget.' type: 'integer' default: 0 required: false order: 3 gutter: label: 'Gutter' description: 'Controls the space (in pixels) between widgets positioned in the grid. The default value is 10.' type: 'integer' default: 10 required: false defaultHidden: true order: 5 borderWidth: label: 'Border Width' description: 'Specifies the pixel width of the border around each widget. Can be set to 0 to remove the border. If omitted, the theme default will be used.' type: 'integer' default: null required: false defaultHidden: true order: 6 margin: label: 'Margin' description: 'Controls the empty margin width (in pixels) around the outer edge of the Dashboard. Can be set to 0 to remove the margin.' type: 'integer' default: 10 required: false defaultHidden: true order: 7 scrolling: label: 'Scrolling Enabled' description: 'Enables vertical scrolling of the page to display content longer than the current browser size.' type: 'boolean' default: true required: false defaultHidden: true order: 8 order: 2 widgets: label: 'Widgets' description: 'An array of one or more Widgets to display on the page' type: 'propertyset[]' subState: 'edit.widget' headingfn: 'getWidgetName' default: [] required: true properties: widget: label: 'Type' description: 'The type of Widget to be rendered.' type: 'string' required: true name: label: 'Name' description: 'Internal Widget name, displayed in the Dashboard Editor.' placeholder: 'Name' type: 'string' required: false defaultHidden: true inlineJs: false order: 1 title: label: 'Title' description: 'Specifies the title of the widget. Most widgets will display the title at the top of the widget. If omitted, nothing will be displayed and the widget contents will occupy the entire widget boundaries.' placeholder: 'Widget Title' type: 'string' required: false inlineJs: true order: 2 gridHeight: label: 'Grid Rows' description: 'Specifies the number of vertical grid squares for this widget to occupy. Instead of an absolute height, this sets the relative size based on grid units.' placeholder: 'Number of Rows' type: 'integer' default: '1' required: false order: 100 gridWidth: label: 'Grid Columns' description: 'Specifies the number of horizontal grid squares for this widget to occupy. Instead of an absolute width, this sets the relative size based on grid units.' placeholder: 'Number of Columns' type: 'integer' default: '1' required: false order: 101 height: label: 'Height' description: 'If set, specifies the absolute display height of the widget. Any valid CSS value can be used (e.g. "200px", "40%", etc).' placeholder: 'Height' type: 'string' required: false defaultHidden: true order: 102 width: label: 'Width' description: 'If set, specifies the absolute display width of the widget. Any valid CSS value can be used (e.g. "200px", "40%", etc).' placeholder: 'Width' type: 'string' required: false defaultHidden: true order: 103 autoHeight: label: 'Auto-Height (Fit to Contents)' description: 'If true, disables both the gridHeight and height properties, and allows the Widget to be vertically sized to fit its contents.' type: 'boolean' required: false defaultHidden: true order: 104 helpText: label: 'Help Text' description: 'Provides an optional help text for the Widget, available via a help icon in the corner of the Widget.' type: 'string' required: false inlineJs: true defaultHidden: true order: 109 theme: label: 'Theme' description: 'If set, overrides the Page theme and allows a widget to have a different theme from the rest of the Page and Widgets.' type: 'string' inherit: true required: false defaultHidden: true order: 110 themeVariant: label: 'Theme Variant' description: 'If set, overrides the Page theme variant and allows a widget to have a different theme variant from the rest of the Page and Widgets.' type: 'string' inherit: true required: false defaultHidden: true order: 111 noData: label: 'No Data Message' description: 'If set, displays this message in the Widget when no data is loaded from the Data Source. If not set, no message will be displayed' type: 'string' inlineJs: true required: false defaultHidden: true order: 120 noscroll: label: 'No Scroll' description: 'If set to true, the widget will not have scrollbars and any overflow will be hidden. The effect of this setting varies per widget.' type: 'boolean' default: false required: false defaultHidden: true order: 121 allowFullscreen: label: 'Allow Fullscreen' description: 'If true, the Widget can be maximized to fill the entire Dashboard; if false, the ability to view in fullscreen is disabled. This property overrides the Page setting.' type: 'boolean' inherit: true required: false defaultHidden: true order: 122 allowExport: label: 'Allow Export' description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This property overrides the Page setting.' type: 'boolean' inherit: true required: false defaultHidden: true order: 123 showWidgetErrors: label: 'Show Error Messages on Widgets' description: 'If true, allows error messages to be displayed on Widgets. This property overrides the Page setting.' type: 'boolean' required: false inherit: true defaultHidden: true order: 124 hidden: label: 'Hidden' description: 'If true, the Widget will not be displayed in the Dashboard and will not occupy space in the Layout rendering. The Widget will still be initialized, however.' type: 'boolean' default: false required: false defaultHidden: true order: 125 genericEvents: label: 'Generic Events' singleLabel: 'param-event' description: 'Array of parameters (defined beforehand in the Parameters section of the dashboard) and events that can trigger their change within widgets. Note that adding a Name to the widget is mandatory for this property to work.' type: 'propertyset[]' inlineJs: true defaultHidden: true default: [] properties: paramName: label: 'Parameter Name' type: 'string' required: true order: 1 event: label: 'Event' type: 'string' required: true options: clickOnWidget: value: 'clickOnWidget' order: 2 order: 126 parameterSubscription: label: 'Subscription To Parameters' singleLabel: 'param' description: 'Specifies a list of parameters the widget subscribes to, i.e., that the widget uses and that can cause its reload upon change. See section Parameters for more details.' type: 'string[]' inlineJs: true defaultHidden: true default: [] order: 127 container: label: 'Container' description: 'Name of the Container Widget that should contain this widget' type: 'string' inlineJs: true defaultHidden: true order: 128 order: 3 duration: label: 'Auto-Rotate Duration (seconds)' description: 'The number of seconds to remain on this page before rotating to the next page. If autoRotate is set to false, this value is ignored.' placeholder: 'Seconds per page' inherit: true type: 'integer' required: false defaultHidden: true order: 4 frequency: label: 'Frequency' description: 'If greater than one, this page will only be shown on every N cycles through the dashboard. Defaults to 1, meaning the Page will be shown on every cycle.' default: 1 type: 'integer' required: false defaultHidden: true order: 5 theme: label: 'Theme' description: 'The theme for the Page. If not set, the Dashboard setting or default value will apply.' type: 'string' inherit: true required: false defaultHidden: true order: 6 themeVariant: label: 'Theme Variant' description: 'The theme variant for the Page. If not set, the Dashboard setting or default value will apply.' type: 'string' inherit: true required: false defaultHidden: true order: 7 style: label: 'Style' description: 'The style for the Page. If not set, the Dashboard setting or default value will apply.' type: 'string' inherit: true required: false defaultHidden: true order: 8 allowFullscreen: label: 'Allow Fullscreen' description: 'If true, each Widget on the page can be maximized to fill the entire Dashboard. This setting can be overridden by each Widget.' type: 'boolean' inherit: true required: false defaultHidden: true order: 10 allowExport: label: 'Allow Export' description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This setting can be overridden by each Widget.' type: 'boolean' inherit: true required: false defaultHidden: true order: 11 showWidgetErrors: label: 'Show Error Messages on Widgets' description: 'If true, allows error messages to be displayed on Widgets. This setting can be overridden by each Widget.' type: 'boolean' required: false inherit: true defaultHidden: true order: 12; dataSources: label: 'Data Sources' description: 'A list of Data Sources which connect to external services and pull in data for the Dashboard.' type: 'datasources' default: [] required: false properties: name: label: 'Name' description: 'The Data Source Name is used to reference the Data Source from a widget' placeholder: 'Data Source Name' type: 'string' required: true order: 1 type: label: 'Type' description: 'Specifies the implementation type of the Data Source' type: 'string' required: true order: 0 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted' type: 'hash' inlineJsKey: true inlineJsValue: true required: false defaultHidden: true order: 101 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' defaultHidden: true order: 102 preload: label: 'Preload' description: 'By default, each Data Source is loaded only when it is used, e.g. when a Widget consuming it is rendered. Setting this true causes Cyclotron to load the Data Source when the Dashboard is initialized.' type: 'boolean' inlineJs: false required: false default: false defaultHidden: true order: 103 deferred: label: 'Deferred' description: 'Prevents execution of the data source until execute() is manually called on the Data Source. This should only be used when using custom JavaScript to execute this Data Source, otherwise the Data Source will never run.' type: 'boolean' inlineJs: false required: false default: false defaultHidden: true order: 103 errorHandler: label: 'Error Handler' description: 'Specifies an optional JavaScript function that is called if an errors occurs. It can return a different or modified error message. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 104 parameterSubscription: label: 'Subscription To Parameters' singleLabel: 'param' description: 'Specifies a list of parameters the data source subscribes to, i.e., that can cause the re-execution of the data source upon change. See section Parameters for more details.' type: 'string[]' inlineJs: true defaultHidden: true default: [] order: 105 options: cloudwatch: value: 'cloudwatch' label: 'CloudWatch' message: 'Amazon CloudWatch monitors operational and performance metrics for your AWS cloud resources and applications. Refer to the <a href="http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/Welcome.html" target="_blank">API Documentation</a> for information on configuring the available options.' icon: 'fa-cloud-download' properties: url: label: 'URL' description: 'Specifies the Amazon CloudWatch Endpoint for the desired region, e.g. "monitoring.us-west-2.amazonaws.com".' placeholder: 'CloudWatch Endpoint' type: 'url' inlineJs: true inlineEncryption: true required: true order: 10 awsCredentials: label: 'AWS Credentials' description: 'AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.' type: 'propertyset' required: true order: 12 properties: accessKeyId: label: 'Access Key Id' description: 'AWS access key id' type: 'string' placeholder: 'Access Key Id' inlineJs: true inlineEncryption: true order: 1 secretAccessKey: label: 'Secret Access Key' description: 'AWS sercet access key' type: 'string' placeholder: 'Secret Access Key' inlineJs: true inlineEncryption: true order: 2 parameters: label: 'CloudWatch Parameters' description: 'Set of parameters for the CloudWatch API.' type: 'propertyset' required: true order: 13 properties: Action: label: 'Action' description: 'Specifies one of the CloudWatch actions.' type: 'string' default: 'auto' inlineJs: true options: ListMetrics: value: 'ListMetrics' GetMetricStatistics: value: 'GetMetricStatistics' required: true order: 1 Namespace: label: 'Namespace' description: 'The namespace to filter against.' type: 'string' inlineJs: true required: false order: 2 MeasureName: label: 'Metric Name' description: 'The name of the metric to filter against.' type: 'string' inlineJs: true required: false order: 3 Dimensions: label: 'Dimensions' description: 'Optional; a list of Dimension key/values to filter against.' type: 'hash' required: false inlineJsValue: true inlineEncryption: true order: 4 Statistics: label: 'Statistics' description: 'Specifies one or more Statistics to return.' type: 'string[]' inlineJs: true options: SampleCount: value: 'SampleCount' Average: value: 'Average' Sum: value: 'Sum' Minimum: value: 'Minimum' Maximum: value: 'Maximum' required: true order: 5 Period: label: 'Period' description: 'The granularity, in seconds, of the returned datapoints. A Period can be as short as one minute (60 seconds) or as long as one day (86,400 seconds), and must be a multiple of 60.' type: 'integer' default: 60 required: false placeholder: 'Number of Seconds' order: 6 StartTime: label: 'Start Time' description: 'The date/time of the first datapoint to return. The time stamp must be in ISO 8601 UTC format (e.g., 2014-09-03T23:00:00Z).' type: 'string' inlineJs: true required: false order: 8 EndTime: label: 'End Time' description: 'The date/time of the last datapoint to return. The time stamp must be in ISO 8601 UTC format (e.g., 2014-09-03T23:00:00Z).' type: 'string' inlineJs: true required: false order: 9 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 15 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 16 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 17 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 11 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 18 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 cyclotronData: value: 'cyclotronData' label: 'CyclotronData' icon: 'fa-cloud-download' message: 'Cyclotron has built-in support for a limited amount of data storage using uniquely-named buckets. Refer to to the Documentation for more details.' properties: key: label: 'Bucket Key' description: 'Specifies the unique key to a Cyclotron Data bucket.' placeholder: 'Bucket Key' type: 'string' inlineJs: true required: true order: 10 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 14 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 15 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 16 url: label: 'Cyclotron Server' description: 'Specifies which Cyclotron server to request data from. If omitted, the default sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 11 elasticsearch: value: 'elasticsearch' label: 'Elasticsearch' icon: 'fa-cloud-download' properties: url: label: 'URL' description: 'Specifies the Elasticsearch endpoint.' placeholder: 'Elasticsearch URL' type: 'url' inlineJs: true inlineEncryption: true required: true order: 10 index: label: 'Index' description: 'Specifies the name of the Elasticsearch index to query.' type: 'string' inlineJs: true inlineEncryption: true required: true order: 12 method: label: 'API Name' description: 'Indicates which Elasticsearch API method to use; defaults to "_search".' type: 'string' inlineJs: true inlineEncryption: true defaultHidden: true default: '_search' required: false order: 13 request: label: 'Elasticsearch Request' description: 'Specifies the Elasticsearch JSON request.' placeholder: 'JSON' type: 'editor' editorMode: 'json' inlineJs: true inlineEncryption: true required: true order: 14 responseAdapter: label: 'Response Adapter' description: 'Determines how the Elasticsearch response will be converted to Cyclotron\'s data format. Defaults to "auto".' type: 'string' default: 'auto' inlineJs: true options: 'Auto': value: 'auto' 'Hits': value: 'hits' 'Aggregations': value: 'aggregations' 'Raw': value: 'raw' required: false order: 15 awsCredentials: label: 'AWS Credentials' description: 'Optional AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 16 properties: accessKeyId: label: 'Access Key Id' description: 'AWS access key id' type: 'string' placeholder: 'Access Key Id' inlineJs: true inlineEncryption: true order: 1 secretAccessKey: label: 'Secret Access Key' description: 'AWS sercet access key' type: 'string' placeholder: 'Secret Access Key' inlineJs: true inlineEncryption: true order: 2 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 20 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 21 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 22 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 23 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 24 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 graphite: value: 'graphite' label: 'Graphite' icon: 'fa-cloud-download' message: 'The Graphite Data Source connects to any <a href="http://graphite.readthedocs.org/" target="_blank">Graphite<a> server to load time-series metrics via the Render api. For more details on usage, refer to the Graphite <a href="http://graphite.readthedocs.org/en/latest/render_api.html" target="_blank">documentation</a>.' properties: url: label: 'URL' description: 'The Graphite server' placeholder: 'Graphite Server URL or IP' type: 'url' inlineJs: true inlineEncryption: true required: true order: 10 targets: label: 'Targets' description: 'One or more Graphite metrics, optionally with metrics.' type: 'string[]' inlineJs: true inlineEncryption: true required: true order: 11 from: label: 'From' description: 'Specifies the absolute or relative beginning of the time period to retrieve. If omitted, it defaults to 24 hours ago (per Graphite).' placeholder: 'Start Time' type: 'string' inlineJs: true inlineEncryption: true required: false order: 12 until: label: 'Until' description: 'Specifies the absolute or relative end of the time period to retrieve. If omitted, it defaults now (per Graphite).' placeholder: 'End Time' type: 'string' inlineJs: true inlineEncryption: true required: false order: 13 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 14 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 15 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Graphite result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 16 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 11 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 17 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 influxdb: value: 'influxdb' label: 'InfluxDB' icon: 'fa-cloud-download' message: '<a href="https://www.influxdata.com/time-series-platform/influxdb/" target="_blank">InfluxDB</a> is an open source time series database built from the ground up to handle high write and query loads.' properties: url: label: 'URL' description: 'The InfluxDB server' placeholder: 'InfluxDB Server URL or IP' type: 'url' inlineJs: true required: true order: 10 database: label: 'Database' description: 'Specifies the target InfluxDB database for the query.' placeholder: 'Database' type: 'string' required: true inlineJs: true inlineEncryption: true required: false order: 11 query: label: 'Query' description: 'An InfluxQL query.' type: 'string' inlineJs: true inlineEncryption: true required: true order: 11 precision: label: 'Precision' description: 'Overrides the default timestamp precision.' type: 'string' default: 'ms' inlineJs: true options: h: value: 'h' m: value: 'm' s: value: 's' ms: value: 'ms' u: value: 'u' ns: value: 'ns' order: 11 username: label: 'Username' description: 'Optional; username for authentication, if enabled.' type: 'string' inlineJs: true inlineEncryption: true order: 15 password: label: 'Password' description: 'Optional; password for authentication, if enabled.' type: 'string' inputType: 'password' inlineJs: true inlineEncryption: true order: 16 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 21 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 22 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Graphite result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 23 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 11 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 24 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 javascript: value: 'javascript' label: 'JavaScript' icon: 'fa-cloud-download' message: 'The JavaScript Data Source allows custom JavaScript to be used to load or generate a Data Source.' properties: processor: label: 'Processor' description: 'Specifies a JavaScript function used to provide data for the Data Source, either by directly returning a data set, or resolving a promise asynchronously. The function is called with an optional promise which can be used for this purpose.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: true order: 10 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 11 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 12 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the JavaScript result dataset before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 13 json: value: 'json' label: 'JSON' icon: 'fa-cloud-download' properties: url: label: 'URL' description: 'Specifies the JSON Web Service URL.' placeholder: 'Web Service URL' type: 'url' inlineJs: true inlineEncryption: true required: true order: 10 queryParameters: label: 'Query Parameters' description: 'Optional query parameters which are added to the URL. If there are already query parameters in the URL, these will be appended. The keys and values are both URL-encoded.' type: 'hash' required: false inlineJsKey: true inlineJsValue: true inlineEncryption: true defaultHidden: true order: 12 options: label: 'Options' description: 'Optional request parameters that are passed to the library making the request.' type: 'hash' required: false inlineJsValue: true inlineEncryption: true defaultHidden: true order: 13 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 14 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 15 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 16 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 11 awsCredentials: label: 'AWS Credentials' description: 'Optional AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 17 properties: accessKeyId: label: 'Access Key Id' description: 'AWS access key id' type: 'string' placeholder: 'Access Key Id' inlineJs: true inlineEncryption: true order: 1 secretAccessKey: label: 'Secret Access Key' description: 'AWS sercet access key' type: 'string' placeholder: 'Secret Access Key' inlineJs: true inlineEncryption: true order: 2 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 18 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 ###scopes: label: 'Scopes' description: 'Optional list of scopes (comma- or space-separated, according to what the authorization server accepts) that will be passed to the authorization server' type: 'string' placeholder: 'Scopes' inlineJs: true inlineEncryption: true order: 4 ### mock: value: 'mock' label: 'Mock' icon: 'fa-cloud-download' message: 'The Mock Data Source generates sample data for testing a dashboard.' properties: format: label: 'Format' description: 'Selects the format of the mock data from these possible values: ["object", "pie", "ducati"]. Defaults to "object".' type: 'string' required: false default: 'object' options: object: value: 'object' pie: value: 'pie' large: value: 'large' ducati: value: 'ducati' order: 10 refresh: label: 'Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 11 odata: value: 'odata' label: 'OData' icon: 'fa-cloud-download' properties: url: label: 'URL' description: 'Specifies the OData Service URL.' placeholder: 'Service URL' type: 'url' inlineJs: true inlineEncryption: true required: true order: 10 responseAdapter: label: 'Response Adapter' description: 'Determines how the response will be converted to Cyclotron\'s data format. Defaults to "raw", i.e. the result is returned as is. Use "Entity Set" to read a list of objects. Use "Single Entity" to read a single object. Use "Primitive Property" to have a single value.' type: 'string' default: 'raw' inlineJs: true options: 'Primitive Property': value: 'primitive_prop' 'Single Entity': value: 'single_entity' 'Entity Set': value: 'entity_set' 'Raw': value: 'raw' required: false order: 11 queryParameters: label: 'Query Parameters' description: 'Optional query parameters which are added to the URL. If there are already query parameters in the URL, these will be appended. The keys and values are both URL-encoded.' type: 'hash' required: false inlineJsKey: true inlineJsValue: true inlineEncryption: true defaultHidden: true order: 12 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 13 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not a JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 14 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not a JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 15 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 16 options: label: 'Options' description: 'Optional request parameters that are passed to the library making the request.' type: 'hash' required: false inlineJsValue: true inlineEncryption: true defaultHidden: true order: 17 awsCredentials: label: 'AWS Credentials' description: 'Optional AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 18 properties: accessKeyId: label: 'Access Key Id' description: 'AWS access key id' type: 'string' placeholder: 'Access Key Id' inlineJs: true inlineEncryption: true order: 1 secretAccessKey: label: 'Secret Access Key' description: 'AWS sercet access key' type: 'string' placeholder: 'Secret Access Key' inlineJs: true inlineEncryption: true order: 2 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 19 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 splunk: value: 'splunk' label: 'Splunk' icon: 'fa-cloud-download' properties: query: label: 'Query' description: 'Splunk query' placeholder: 'Splunk query' type: 'textarea' required: true order: 10 earliest: label: 'Earliest Time' description: 'Sets the earliest (inclusive), respectively, time bounds for the search. The time string can be either a UTC time (with fractional seconds), a relative time specifier (to now) or a formatted time string.' placeholder: 'Earliest Time' type: 'string' inlineJs: true inlineEncryption: true required: false order: 11 latest: label: 'Latest Time' description: 'Sets the latest (exclusive), respectively, time bounds for the search. The time string can be either a UTC time (with fractional seconds), a relative time specifier (to now) or a formatted time string.' placeholder: 'Latest Time' type: 'string' inlineJs: true inlineEncryption: true required: false order: 12 username: label: 'Username' description: 'Username to authenticate with Splunk' type: 'string' required: true inlineJs: true inlineEncryption: true order: 13 password: label: 'Password' description: 'Password to authenticate with Splunk' type: 'string' inputType: 'password' required: true inlineJs: true inlineEncryption: true order: 14 host: label: 'Host' description: 'Splunk API host name' placeholder: 'Splunk API host name' type: 'string' inputType: 'string' required: false defaultHidden: false order: 15 url: label: 'URL' description: 'The Splunk API Search URL' placeholder: 'Splunk API Search URL' type: 'url' inlineJs: true inlineEncryption: true default: 'https://#{host}:8089/services/search/jobs/export' defaultHidden: true required: false order: 16 refresh: label: 'Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 17 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 18 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Splunk result dataset before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 19 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. This is required to use encrypted strings within the Data Source properties. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 20 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 21 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 parameters: label: 'Parameters' description: 'A list of Parameters that can be used to configure the Dashboard.' type: 'propertyset[]' default: [] required: false properties: name: label: 'Name' description: 'The name used to set or reference this Parameter.' type: 'string' required: true placeholder: 'Parameter Name' order: 0 defaultValue: label: 'Default Value' description: 'The value used if the Parameter is not set when opening the Dashboard.' type: 'string' placeholder: 'Default Value' required: false inlineJs: true order: 1 showInUrl: label: 'Show in URL' description: 'Determines whether or not the Parameter is displayed in the query string of the Dashboard URL.' type: 'boolean' default: true required: false order: 2 editInHeader: label: 'Editable in Header' description: 'If true, the Parameter will be displayed and configurable in the Parameter section of the Header Widget (if used).' type: 'boolean' default: false required: false order: 3 persistent: label: 'Persistent' description: 'If true, the value of this Parameter will be persisted in the user\'s browser across multiple sessions.' type: 'boolean' default: false required: false order: 4 changeEvent: label: 'Change Event' description: 'This event occurs when the Parameter value is modified. It does not fire when the Dashboard is being initialized. Expects a JavaScript function in the form function(parameterName, newValue, oldValue).' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 10 editing: label: 'Editing' description: 'Configuration for how this Parameter can be edited in the Dashboard.' type: 'propertyset' required: false default: {} defaultHidden: true order: 15 properties: displayName: label: 'Display Name' description: 'The display name used for this Parameter.' type: 'string' required: false placeholder: 'Display Name' order: 1 editorType: label: 'Editor Type' description: 'Determines the type of editor used to configured this Parameter (e.g. in the Header Widget).' type: 'string' required: false default: 'textbox' order: 2 options: textbox: value: 'textbox' dropdown: value: 'dropdown' autocomplete: value: 'autocomplete' links: value: 'links' checkbox: value: 'checkbox' radiobuttons: value: 'radiobuttons' datetime: value: 'datetime' date: value: 'date' time: value: 'time' dataSource: label: 'Data Source' description: 'Optionally specifies a Data Source providing dropdown options for this Parameter.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions order: 4 datetimeFormat: label: 'Date/Time Format' description: 'The Moment.js-compatible date/time format string used to read/write datetimes to this Parameter. Only used if the editor type is "datetime", "date", or "time". Defaults to an ISO 8601 format.' type: 'string' required: false placeholder: 'Format' defaultHidden: true order: 5 minCharNumber: label: 'Minimal Number of Characters' description: 'Minimal number of characters typed before autocomplete activates. Must be greather than or equal to 0. Defaults to 1.' type: 'integer' required: false default: 1 defaultHidden: true order: 6 allowNonMatching: label: 'Allow Non-Matching Values' description: 'If true, values that do not match any value in the list can be entered in the autocomplete input field. If false, only values in the list are allowed.' type: 'boolean' default: true required: false defaultHidden: true order: 7 allowEmpty: label: 'Allow Empty Input field' description: 'If true, the autocomplete input field can be empty. If false, the field is automatically populated with the currently highlighted value of the list when it is not focused.' type: 'boolean' default: true required: false defaultHidden: true order: 7 broadcastUpdate: label: 'Broadcast Parameter update' description: 'Notify the dashboard that the value has changed' type: 'boolean' default: true required: false defaultHidden: true order: 8 sample: name: '' defaultValue: '' scripts: label: 'Scripts' description: 'Defines a list of inline JavaScript or external JavaScript URIs that are loaded when the Dashboard initializes.' type: 'propertyset[]' default: [] required: false properties: name: label: 'Name' description: 'Display name of the script' type: 'string' placeholder: 'Name' required: false order: 0 path: label: 'Path' description: 'URL to a JavaScript file, to be loaded along with the Dashboard' type: 'url' placeholder: 'JavaScript file URL' required: false order: 1 text: label: 'JavaScript Text' description: 'Inline JavaScript to be run when the Dashboard is loaded' type: 'editor' editorMode: 'javascript' placeholder: 'Inline JavaScript' required: false order: 2 singleLoad: label: 'Single-Load' description: 'If true, this Script will only be loaded once when the Dashboard is loaded. Otherwise, it will be rerun every time the Dashboard internally refreshes. Scripts loaded from a path are always treated as single-load, and this property is ignored.' type: 'boolean' required: false default: false order: 3 sample: text: '' styles: label: 'Styles' description: 'Defines a list of inline CSS or external CSS URIs that are loaded when the Dashboard initializes.' type: 'propertyset[]' default: [] required: false properties: name: label: 'Name' description: 'Display name of the style' type: 'string' placeholder: 'Name' required: false order: 0 path: label: 'Path' description: 'URL to a CSS file, to be loaded along with the Dashboard' type: 'url' placeholder: 'CSS file URL' required: false order: 0 text: label: 'CSS Text' description: 'Inline CSS to be run when the Dashboard is loaded' type: 'editor' editorMode: 'css' placeholder: 'Inline CSS' required: false order: 1 sample: text: '' controls: # Controls how long to display the controls before hiding. duration: 1000 # Controls how close the mouse must be before the controls appear hitPaddingX: 60 hitPaddingY: 50 sample: name: '' sidebar: showDashboardSidebar: true pages: [] # Dashboard Sidebar dashboardSidebar: footer: logos: [{ title: 'Cyclotron' src: '/img/favicon32.png' href: '/' }] # List of help pages help: [ { name: 'About' path: '/partials/help/about.html' tags: ['about', 'terminology', 'features'] children: [ { name: 'Quick Start' path: '/partials/help/quickstart.html' tags: ['help', 'creating', 'tags', 'theme', 'revisions', 'preview', 'data sources', 'pages', 'layout', 'widgets'] } { name: 'JSON' path: '/partials/help/json.html' tags: ['json'] } { name: 'Examples' path: '/partials/help/examples.html' tags: ['examples', 'cyclotron-examples'] } { name: 'Browser Compatibility' path: '/partials/help/browserCompat.html' tags: ['browser', 'compatibility', 'firefox', 'chrome', 'internet explorer', 'ie', 'safari', 'browsercheck'] } { name: 'Permissions' path: '/partials/help/permissions.html' tags: ['permissions', 'edit permission', 'view permission', 'editors', 'viewers', 'restricted', 'login', 'rest', 'api'] } { name: 'Analytics' path: '/partials/help/analytics.html' tags: ['analytics', 'pageviews', 'visits', 'metrics'] } { name: 'Encrypted Strings' path: '/partials/help/encryptedStrings.html' tags: ['encryption', 'encrypted', '!{', 'decrypt', 'encrypt'] } { name: 'JavaScript API' path: '/partials/help/javascriptApi.html' tags: ['javascript', 'api', 'scripting'] } { name: 'CyclotronData' path: '/partials/help/cyclotrondata.html' tags: ['cyclotrondata', 'data', 'storage', 'bucket', 'api'] } { name: '3rd Party Libraries' path: '/partials/help/3rdparty.html' tags: ['libraries', 'jquery', 'moment', 'lodash', 'angular', 'numeral', 'localforage', 'uri', 'bootstrap', 'c3.js', 'd3.js', 'font awesome', 'highcharts', 'masonry', 'metricsgraphics', 'select2', 'spin.js'] } { name: 'Hotkeys' path: '/partials/help/hotkeys.html' tags: ['hotkeys', 'keys', 'shortcuts'] } { name: 'API' path: '/partials/help/api.html' tags: ['api', 'rest', 'service'] } ] } { name: 'Dashboards' path: '/partials/help/dashboards.html' tags: ['dashboards', 'pages', 'dataSources', 'scripts', 'parameters'] children: [ { name: 'Pages' path: '/partials/help/pages.html' tags: ['pages', 'widgets'] } { name: 'Layout' path: '/partials/help/layout.html' tags: ['layout', 'grid', 'mobile', 'scrolling', 'position', 'absolute'] } { name: 'Parameters' path: '/partials/help/parameters.html' tags: ['parameters'] } { name: 'Scripts' path: '/partials/help/scripts.html' tags: ['scripts', 'javascript'] } { name: 'Styles' path: '/partials/help/styles.html' tags: ['styles', 'css'] } ] } { name: 'Data Sources' path: '/partials/help/dataSources.html' tags: ['data sources', 'dataSources', 'tabular', 'post-processor', 'post processor', 'pre-processor', 'pre processor'] } { name: 'Widgets' path: '/partials/help/widgets.html' tags: ['widgets'] } ] # Formats supported for Dashboard Export exportFormats: [{ label: 'PDF', value: 'pdf' }] # Page settings page: sample: frequency: 1 layout: gridColumns: 2 gridRows: 2 widgets: [] # Widget settings widgets: annotationChart: name: 'annotationChart' label: 'Annotation Chart' icon: 'fa-bar-chart-o' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for this Widget.' placeholder: 'Data Source name' type: 'string' required: true options: datasourceOptions order: 10 xAxis: label: 'X-Axis' description: 'Configuration of the X-axis.' type: 'propertyset' required: true properties: column: label: 'Column Name' description: 'Name of the column in the Data Source used for the x-axis.' placeholder: 'Column Name' inlineJs: true type: 'string' order: 1 format: label: 'Format' description: 'Specifies which format the incoming datetime data is in.' type: 'string' options: date: value: 'date' epoch: value: 'epoch' epochmillis: value: 'epochmillis' string: value: 'string' order: 2 formatString: label: 'Format String' description: 'Used with the String format to specify how the string should be parsed.' type: 'string' order: 3 order: 11 series: label: 'Series' singleLabel: 'series' description: 'One or more series to display in the annotation chart.' type: 'propertyset[]' required: true default: [] order: 12 properties: column: label: 'Column Name' description: 'Name of the column in the Data Source to use as the y-axis value for this series.' placeholder: 'Column Name' inlineJs: true type: 'string' order: 1 label: label: 'Label' description: 'Display label for the series; if omitted, the column name will be used.' placeholder: 'Label' inlineJs: true type: 'string' order: 2 annotationTitleColumn: label: 'Annotation Title Column Name' description: 'Name of the column in the Data Source to use as the title of annotations corresponding to each point.' placeholder: 'Column Name' inlineJs: true type: 'string' order: 3 annotationTextColumn: label: 'Annotation Text Column Name' description: 'Name of the column in the Data Source to use as the text of annotations corresponding to each point.' placeholder: 'Column Name' inlineJs: true type: 'string' order: 4 secondaryAxis: label: 'Secondary Axis' description: 'If true, places the series on a second axis on the left of the chart.' inlineJs: true type: 'boolean' order: 5 options: label: 'Options' description: 'Additional options for the Google Annotation chart. Any supported option is allowed here.' type: 'propertyset' required: false inlineJs: true properties: allValuesSuffix: label: 'All Values Suffix' description: 'A suffix to be added to all values in the legend and tick labels in the vertical axes.' placeholder: 'Suffix' type: 'string' inlineJs: true defaultHidden: true annotationsWidth: label: 'Annotations Width' description: 'The width (in percent) of the annotations area, out of the entire chart area. Must be a number in the range 5-80.' type: 'integer' inlineJs: true defaultHidden: true displayAnnotations: label: 'Display Annotations' description: 'Controls whether annotations are displayed along with the chart.' type: 'boolean' inlineJs: true default: true defaultHidden: true displayAnnotationsFilter: label: 'Display Annotations Filter' description: 'If set to true, the chart will display a filter control to filter annotations.' type: 'boolean' inlineJs: true default: false defaultHidden: true displayDateBarSeparator: label: 'Display Date Bar Separator' description: 'If set to true, the chart will display a small bar separator ( | ) between the series values and the date in the legend.' type: 'boolean' inlineJs: true default: false defaultHidden: true displayLegendDots: label: 'Display Legend Dots' description: 'If set to true, the chart will display dots next to the values in the legend text.' type: 'boolean' inlineJs: true defaultHidden: true displayLegendValues: label: 'Display Legend Values' description: 'If set to true, the chart will display the highlighted values in the legend.' type: 'boolean' inlineJs: true defaultHidden: true displayRangeSelector: label: 'Display Range Selector' description: 'If set to true, the chart will display the zoom range selection area (the area at the bottom of the chart).' type: 'boolean' inlineJs: true defaultHidden: true displayZoomButtons: label: 'Display Zoom Buttons' description: 'If set to true, the chart will display the zoom buttons ("1d 5d 1m" etc).' type: 'boolean' inlineJs: true defaultHidden: true fill: label: 'Fill' description: 'A number from 0—100 (inclusive) specifying the alpha of the fill below each line in the line graph. 100 means 100% opaque, and 0 means no fill at all. The fill color is the same color as the line above it.' type: 'integer' inlineJs: true defaultHidden: true focusTarget: label: 'Focus Target' description: 'Determines whether mouse hover focuses on individual points, or is shared by all series. Defaults to category, unless Annotation editing is enabled, which forces "datum".' type: 'string' inlineJs: true defaultHidden: true default: 'category' options: datum: value: 'datum' category: value: 'category' legendPosition: label: 'Legend Position' description: 'Determines whether the legend is put on the same row as the zoom buttons, or a new row.' type: 'string' inlineJs: true defaultHidden: true options: sameRow: value: 'sameRow' newRow: value: 'newRow' max: label: 'Maximum' description: 'The maximum value to show on the Y-axis. If the maximum data point is less than this value, this setting will be ignored.' type: 'number' inlineJs: true defaultHidden: true min: label: 'Minimum' description: 'The minimum value to show on the Y-axis. If the minimum data point is less than this value, this setting will be ignored.' type: 'number' inlineJs: true defaultHidden: true scaleFormat: label: 'Scale Format' description: 'Number format to be used for the axis tick labels. Format reference: https://developers.google.com/chart/interactive/docs/customizing_axes#number-formats.' placeholder: 'Format' type: 'string' inlineJs: true defaultHidden: true scaleType: label: 'Scale Type' description: 'Sets the maximum and minimum values shown on the Y-axis. Reference: https://developers.google.com/chart/interactive/docs/gallery/annotationchart.' type: 'string' inlineJs: true defaultHidden: true options: maximized: value: 'maximized' fixed: value: 'fixed' allmaximized: value: 'allmaximized' allfixed: value: 'allfixed' thickness: label: 'Thickness' description: 'A number from 0—10 (inclusive) specifying the thickness of the lines, where 0 is the thinnest.' placeholder: 'Thickness' type: 'integer' inlineJs: true defaultHidden: true zoomStartTime: label: 'Zoom Start Time' description: 'Sets the initial start datetime of the selected zoom range. Should be provided as a JavaScript Date.' placeholder: 'Date Time' type: 'datetime' inlineJs: true defaultHidden: true zoomEndTime: label: 'Zoom End Time' description: 'Sets the initial end datetime of the selected zoom range. Should be provided as a JavaScript Date.' placeholder: 'Date Time' type: 'datetime' inlineJs: true defaultHidden: true order: 13 annotationEditing: label: 'Built-In Annotation Editing' description: 'Optional, but if enabled, allows users to create new annotations for points on the chart. Annotations are stored automatically within Cyclotron.' type: 'boolean' required: false default: false order: 13 annotationKey: label: 'Built-In Annotation Key' description: 'Provides a CyclotronData bucket key to be used for built-in annotation editing. This property is automatically initialized with a random UUID.' type: 'string' inlineJs: true required: false defaultHidden: true order: 14 events: label: 'Events' description: 'Optional event handlers for various events.' type: 'propertyset' required: false defaultHidden: true order: 15 properties: rangechange: label: 'Range Change Event' description: 'This event occurs when the user changes the range slider. The new endpoints are available as e.start and e.end.' type: 'editor' editorMode: 'javascript' required: false order: 1 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 20 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' order: 20 # Common options options: displayAnnotations: true # Undocumented "chart" options chart: focusTarget: 'category' sample: -> # Generate new Annotation Chart Widget { annotationKey: uuid.v4() } # Theme-specific options themes: dark: options: dbackgroundColor: '#222222' darkmetro: options: dbackgroundColor: '#202020' ### chart: name: 'chart' label: 'Chart' icon: 'fa-bar-chart-o' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for this Widget.' placeholder: 'Data Source name' type: 'string' required: true options: datasourceOptions order: 10 drilldownDataSource: label: 'Drilldown Data Source' description: 'The name of the Data Source providing drilldown data for this Widget.' placeholder: 'Data Source name' type: 'string' required: false defaultHidden: true options: datasourceOptions order: 11 highchart: label: 'Highchart Definition' description: 'Contains all the options for the chart, in the format expected by Highcharts. Any valid Highcharts properties can be set under this property and will be applied to the chart.' type: 'json' inlineJs: true required: true order: 12 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 13 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' order: 14 addShiftPoints: label: 'Add/Shift Points' description: 'If true, identifies new points on each data reload and appends them to the right side of the chart, shifting points off of the left side. This is ideal for rolling time-series charts with a fixed number of points. The default is false, which forces a complete redraw of all points.' type: 'boolean' default: false required: false order: 15 sample: highchart: series: [{ x: '' y: '' } ] xAxis: [{ type: 'linear' } ] yAxis: [{ title: text: 'Values' } ] themes: light: chart: style: fontFamily: '"Open Sans", sans-serif' drilldown: activeAxisLabelStyle: color: '#333' textDecoration: 'none' plotOptions: series: shadow: false marker: enabled: false states: hover: enabled: true bar: borderWidth: 0 column: borderWidth: 0 pie: borderWidth: 0 title: style: font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 labels: style: fontSize: '11px' title: style: fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null lineWidth: 0 tickWidth: 0 labels: style: fontSize: '11px' title: style: fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 symbolWidth: 40 gto: chart: style: fontFamily: '"Open Sans", sans-serif' plotOptions: series: shadow: false marker: enabled: false states: hover: enabled: true bar: borderWidth: 0 column: borderWidth: 0 pie: borderWidth: 0 title: style: font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 labels: style: fontSize: '11px' title: style: fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null lineWidth: 0 tickWidth: 0 labels: style: fontSize: '11px' title: style: fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 symbolWidth: 40 dark: colors: [ '#007D9D' #Blue '#82B93A' #Green '#E3AAD5' #Pink '#EBDC46' #Yellow '#AC5B41' #Red '#D1D1D0' #Offwhite '#B07288' #Purple ] chart: backgroundColor: null #'#333333' borderWidth: 0 borderRadius: 0 plotBackgroundColor: null plotShadow: false plotBorderWidth: 0 style: fontFamily: '"Open Sans", sans-serif' color: '#FFF' drilldown: activeAxisLabelStyle: color: '#999' textDecoration: 'none' activeDataLabelStyle: color: '#999' textDecoration: 'none' title: style: color: '#FFF' font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: color: '#FFF' font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 lineColor: '#999' tickColor: '#999' labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null gridLineColor: 'rgba(255, 255, 255, .1)' minorGridLineColor: 'rgba(255,255,255,0.07)' lineWidth: 0 tickWidth: 0 labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 itemStyle: color: '#CCC' itemHoverStyle: color: '#FFF' itemHiddenStyle: color: '#333' symbolWidth: 40 labels: style: color: '#CCC' tooltip: backgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, 'rgba(96, 96, 96, .8)'] [1, 'rgba(16, 16, 16, .8)'] ] borderWidth: 0 style: color: '#FFF' plotOptions: series: dataLabels: style: color: '#999' textShadow: false shadow: true marker: enabled: false states: hover: enabled: true bar: borderWidth: 0 column: borderWidth: 0 line: dataLabels: color: '#CCC' marker: lineColor: '#333' pie: borderWidth: 0 dataLabels: color: '#999' fontSize: '14px' spline: marker: lineColor: '#333' scatter: marker: lineColor: '#333' candlestick: lineColor: 'white' toolbar: itemStyle: color: '#CCC' navigation: buttonOptions: symbolStroke: '#DDDDDD' hoverSymbolStroke: '#FFFFFF' theme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#606060'] [0.6, '#333333'] ] stroke: '#000000' # scroll charts rangeSelector: buttonTheme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] stroke: '#000000' style: color: '#CCC' fontWeight: 'bold' states: hover: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#BBB'] [0.6, '#888'] ] stroke: '#000000' style: color: 'white' select: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.1, '#000'] [0.3, '#333'] ] stroke: '#000000' style: color: 'yellow' inputStyle: backgroundColor: '#333' color: 'silver' labelStyle: color: 'silver' navigator: handles: backgroundColor: '#666' borderColor: '#AAA' outlineColor: '#CCC' maskFill: 'rgba(16, 16, 16, 0.5)' series: color: '#7798BF' lineColor: '#A6C7ED' scrollbar: barBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] barBorderColor: '#CCC' buttonArrowColor: '#CCC' buttonBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] buttonBorderColor: '#CCC' rifleColor: '#FFF' trackBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, '#000'] [1, '#333'] ] trackBorderColor: '#666' dark2: colors: [ '#2095F0' #Blue '#FF9A13' #Orange '#FFFF13' #Yellow '#A61DF1' #Purple '#28F712' #Green '#FE131E' #Red '#D1D1D0' #Offwhite ] chart: backgroundColor: null #'#333333' borderWidth: 0 borderRadius: 0 plotBackgroundColor: null plotShadow: false plotBorderWidth: 0 style: fontFamily: '"Open Sans", sans-serif' color: '#FFF' drilldown: activeAxisLabelStyle: color: '#999' textDecoration: 'none' activeDataLabelStyle: color: '#999' textDecoration: 'none' title: style: color: '#FFF' font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: color: '#FFF' font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 lineColor: '#999' tickColor: '#999' labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null gridLineColor: 'rgba(255, 255, 255, .1)' minorGridLineColor: 'rgba(255,255,255,0.07)' lineWidth: 0 tickWidth: 0 labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 itemStyle: color: '#CCC' itemHoverStyle: color: '#FFF' itemHiddenStyle: color: '#333' symbolWidth: 40 labels: style: color: '#CCC' tooltip: backgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, 'rgba(96, 96, 96, .8)'] [1, 'rgba(16, 16, 16, .8)'] ] borderWidth: 0 style: color: '#FFF' plotOptions: series: shadow: true marker: enabled: false states: hover: enabled: true dataLabels: style: color: '#999' textShadow: false bar: borderWidth: 0 column: borderWidth: 0 line: dataLabels: color: '#CCC' marker: lineColor: '#333' pie: borderWidth: 0 dataLabels: color: '#999' fontSize: '14px' spline: marker: lineColor: '#333' scatter: marker: lineColor: '#333' candlestick: lineColor: 'white' toolbar: itemStyle: color: '#CCC' navigation: buttonOptions: symbolStroke: '#DDDDDD' hoverSymbolStroke: '#FFFFFF' theme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#606060'] [0.6, '#333333'] ] stroke: '#000000' # scroll charts rangeSelector: buttonTheme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] stroke: '#000000' style: color: '#CCC' fontWeight: 'bold' states: hover: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#BBB'] [0.6, '#888'] ] stroke: '#000000' style: color: 'white' select: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.1, '#000'] [0.3, '#333'] ] stroke: '#000000' style: color: 'yellow' inputStyle: backgroundColor: '#333' color: 'silver' labelStyle: color: 'silver' navigator: handles: backgroundColor: '#666' borderColor: '#AAA' outlineColor: '#CCC' maskFill: 'rgba(16, 16, 16, 0.5)' series: color: '#7798BF' lineColor: '#A6C7ED' scrollbar: barBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] barBorderColor: '#CCC' buttonArrowColor: '#CCC' buttonBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] buttonBorderColor: '#CCC' rifleColor: '#FFF' trackBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, '#000'] [1, '#333'] ] trackBorderColor: '#666' darkmetro: colors: [ '#007D9D' #Blue '#82B93A' #Green '#E3AAD5' #Pink '#EBDC46' #Yellow '#AC5B41' #Red '#D1D1D0' #Offwhite '#B07288' #Purple ] chart: backgroundColor: null #'#333333' borderWidth: 0 borderRadius: 0 plotBackgroundColor: null plotShadow: false plotBorderWidth: 0 style: fontFamily: '"Open Sans", sans-serif' color: '#FFF' drilldown: activeAxisLabelStyle: color: '#999' textDecoration: 'none' activeDataLabelStyle: color: '#999' textDecoration: 'none' title: style: color: '#FFF' font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: color: '#FFF' font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 lineColor: '#999' tickColor: '#999' labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null gridLineColor: 'rgba(255, 255, 255, .1)' minorGridLineColor: 'rgba(255,255,255,0.07)' lineWidth: 0 tickWidth: 0 labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 itemStyle: color: '#CCC' itemHoverStyle: color: '#FFF' itemHiddenStyle: color: '#333' symbolWidth: 40 labels: style: color: '#CCC' tooltip: backgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, 'rgba(96, 96, 96, .8)'] [1, 'rgba(16, 16, 16, .8)'] ] borderWidth: 0 style: color: '#FFF' plotOptions: series: dataLabels: style: color: '#999' textShadow: false shadow: true marker: enabled: false states: hover: enabled: true bar: borderWidth: 0 column: borderWidth: 0 line: dataLabels: color: '#CCC' marker: lineColor: '#333' pie: borderWidth: 0 dataLabels: color: '#999' fontSize: '14px' spline: marker: lineColor: '#333' scatter: marker: lineColor: '#333' candlestick: lineColor: 'white' toolbar: itemStyle: color: '#CCC' navigation: buttonOptions: symbolStroke: '#DDDDDD' hoverSymbolStroke: '#FFFFFF' theme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#606060'] [0.6, '#333333'] ] stroke: '#000000' # scroll charts rangeSelector: buttonTheme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] stroke: '#000000' style: color: '#CCC' fontWeight: 'bold' states: hover: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#BBB'] [0.6, '#888'] ] stroke: '#000000' style: color: 'white' select: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.1, '#000'] [0.3, '#333'] ] stroke: '#000000' style: color: 'yellow' inputStyle: backgroundColor: '#333' color: 'silver' labelStyle: color: 'silver' navigator: handles: backgroundColor: '#666' borderColor: '#AAA' outlineColor: '#CCC' maskFill: 'rgba(16, 16, 16, 0.5)' series: color: '#7798BF' lineColor: '#A6C7ED' scrollbar: barBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] barBorderColor: '#CCC' buttonArrowColor: '#CCC' buttonBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] buttonBorderColor: '#CCC' rifleColor: '#FFF' trackBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, '#000'] [1, '#333'] ] trackBorderColor: '#666' charcoal: colors: [ '#007D9D' #Blue '#82B93A' #Green '#E3AAD5' #Pink '#EBDC46' #Yellow '#AC5B41' #Red '#D1D1D0' #Offwhite '#B07288' #Purple ] chart: backgroundColor: null #'#333333' borderWidth: 0 borderRadius: 0 plotBackgroundColor: null plotShadow: false plotBorderWidth: 0 style: fontFamily: '"Open Sans", sans-serif' color: '#FFF' drilldown: activeAxisLabelStyle: color: '#999' textDecoration: 'none' activeDataLabelStyle: color: '#999' textDecoration: 'none' title: style: color: '#FFF' font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: color: '#FFF' font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 lineColor: '#999' tickColor: '#999' labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null gridLineColor: 'rgba(255, 255, 255, .1)' minorGridLineColor: 'rgba(255,255,255,0.07)' lineWidth: 0 tickWidth: 0 labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 itemStyle: color: '#CCC' itemHoverStyle: color: '#FFF' itemHiddenStyle: color: '#333' symbolWidth: 40 labels: style: color: '#CCC' tooltip: backgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, 'rgba(96, 96, 96, .8)'] [1, 'rgba(16, 16, 16, .8)'] ] borderWidth: 0 style: color: '#FFF' plotOptions: series: dataLabels: style: color: '#999' textShadow: false shadow: false marker: enabled: false states: hover: enabled: true bar: borderWidth: 0 column: borderWidth: 0 line: dataLabels: color: '#CCC' marker: lineColor: '#333' pie: borderWidth: 0 dataLabels: color: '#999' fontSize: '14px' spline: marker: lineColor: '#333' scatter: marker: lineColor: '#333' candlestick: lineColor: 'white' toolbar: itemStyle: color: '#CCC' navigation: buttonOptions: symbolStroke: '#DDDDDD' hoverSymbolStroke: '#FFFFFF' theme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#606060'] [0.6, '#333333'] ] stroke: '#000000' # scroll charts rangeSelector: buttonTheme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] stroke: '#000000' style: color: '#CCC' fontWeight: 'bold' states: hover: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#BBB'] [0.6, '#888'] ] stroke: '#000000' style: color: 'white' select: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.1, '#000'] [0.3, '#333'] ] stroke: '#000000' style: color: 'yellow' inputStyle: backgroundColor: '#333' color: 'silver' labelStyle: color: 'silver' navigator: handles: backgroundColor: '#666' borderColor: '#AAA' outlineColor: '#CCC' maskFill: 'rgba(16, 16, 16, 0.5)' series: color: '#7798BF' lineColor: '#A6C7ED' scrollbar: barBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] barBorderColor: '#CCC' buttonArrowColor: '#CCC' buttonBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] buttonBorderColor: '#CCC' rifleColor: '#FFF' trackBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, '#000'] [1, '#333'] ] trackBorderColor: '#666' ### gchart: name: 'gchart' label: 'Google Charts' icon: 'fa-rocket' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing table-like data for this Widget.' placeholder: 'Data Source name' type: 'string' required: true options: datasourceOptions order: 10 chartType: label: 'Chart Type' description: 'Type of the chart.' type: 'string' required: true options: AnnotatedTimeLine: value: 'AnnotatedTimeLine' AreaChart: value: 'AreaChart' BarChart: value: 'BarChart' BubbleChart: value: 'BubbleChart' CandlestickChart: value: 'CandlestickChart' ColumnChart: value: 'ColumnChart' ComboChart: value: 'ComboChart' Gauge: value: 'Gauge' GeoChart: value: 'GeoChart' IntensityMap: value: 'IntensityMap' Map: value: 'Map' Histogram: value: 'Histogram' LineChart: value: 'LineChart' OrgChart: value: 'OrgChart' PieChart: value: 'PieChart' ScatterChart: value: 'ScatterChart' SteppedAreaChart: value: 'SteppedAreaChart' Table: value: 'Table' Timeline: value: 'Timeline' TreeMap: value: 'TreeMap' order: 11 options: label: 'Options' description: 'JSON object with configuration options for the chart.' type: 'editor' editorMode: 'javascript' required: false order: 12 columns: label: 'Columns' singleLabel: 'column' description: 'Array of columns of the table-like dataset. If not provided, the column labels will be inferred from the keys of the first dataset object. Note that this property must be used if some columns contain dates, times or datetimes or if the column role should differ from "data" (e.g. for annotations; see https://developers.google.com/chart/interactive/docs/roles).' type: 'propertyset[]' inlineJs: true required: false properties: name: label: 'Name' description: 'Indicates the name of the data source field to use for this column.' type: 'string' inlineJs: true required: true order: 1 type: label: 'Type' description: 'Type of the column values. If omitted, "string" will be assigned.' type: 'string' options: string: value: 'string' number: value: 'number' boolean: value: 'boolean' date: value: 'date' datetime: value: 'datetime' timeofday: value: 'timeofday' order: 2 role: label: 'Role' description: 'Optional role of the column. If omitted, "data" will be assigned. Note that columns with role "annotation" must immediately follow the series column that should be annotated, and columns with role "annotationText" must follow the annotated column.' type: 'string' options: annotation: value: 'annotation' annotationText: value: 'annotationText' order: 3 order: 13 formatters: label: 'Formatters' singleLabel: 'formatter' description: 'Optional JavaScript functions that will be applied to all the values of the specified datasource columns.' type: 'propertyset[]' properties: columnName: label: 'Column Name' description: 'Indicates the name of the datasource column' type: 'string' inlineJs: true order: 1 formatter: label: 'Formatter' description: 'The function must take a single value as argument and return the new value.' type: 'editor' editorMode: 'javascript' required: false order: 2 order: 14 clock: name: 'clock' label: 'Clock' icon: 'fa-clock-o' properties: format: label: 'Format' description: 'Enter time format of your choice. "http://momentjs.com/docs/#/displaying/format/" can help in choosing time formats' type: 'string' default: 'dddd, MMMM Do YYYY, h:mm:ss a' required: false order: 10 timezone: label: 'Time Zone' description: 'Enter time zone of your choice. "http://momentjs.com/timezone/" can help in choosing time zone' required: false type: 'string' order: 11 deckgl: name: 'deckgl' label: 'Deck.gl' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for the layers.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions order: 10 ###mapboxApiAccessToken: label: 'Mapbox Token' description: '' type: 'string' required: false order: 11 mapStyle: label: 'Map Style' description: '' type: 'string' required: false order: 12### viewState: label: 'View State' description: 'viewState property' type: 'propertyset' properties: longitude: label: 'Longitude' description: '' type: 'string' required: true order: 1 latitude: label: 'Latitude' description: '' type: 'string' required: true order: 2 zoom: label: 'Zoom' description: 'Default is 0' type: 'integer' required: false default: 0 order: 3 bearing: label: 'Bearing' description: '' type: 'integer' required: false defaultHidden: true order: 4 pitch: label: 'Pitch' description: '' type: 'integer' required: false defaultHidden: true order: 5 order: 13 additionalDeckProps: label: 'Additional Deck Properties' description: 'Additional supported Deck properties. See https://deck.gl/#/documentation/deckgl-api-reference/deck' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 14 layers: label: 'Layers' singleLabel: 'layer' description: '' type: 'propertyset[]' properties: type: label: 'Type' description: 'The type of layer that will be added to the deck.' type: 'string' required: true options: ArcLayer: value: 'ArcLayer' BitmapLayer: value: 'BitmapLayer' ColumnLayer: value: 'ColumnLayer' GeoJsonLayer: value: 'GeoJsonLayer' GridCellLayer: value: 'GridCellLayer' IconLayer: value: 'IconLayer' LineLayer: value: 'LineLayer' PathLayer: value: 'PathLayer' PointCloudLayer: value: 'PointCloudLayer' PolygonLayer: value: 'PolygonLayer' ScatterplotLayer: value: 'ScatterplotLayer' SolidPolygonLayer: value: 'SolidPolygonLayer' TextLayer: value: 'TextLayer' order: 1 configProperties: label: 'Configuration Properties' description: 'See https://deck.gl/#/documentation/deckgl-api-reference/layers/overview for supported properties. Note that they may vary depending on the layer type.' type: 'editor' editorMode: 'javascript' required: false order: 2 useDataSource: label: 'Use Data Source' description: 'Use the Data Source to provide data for this layer. The data will be used for the first layer found with this property set to true.' type: 'boolean' required: false default: false order: 3 order: 14 header: name: 'header' label: 'Header' icon: 'fa-header' properties: headerTitle: label: 'Header Title' description: 'Contains properties for displaying a title in the header.' type: 'propertyset' order: 10 properties: showTitle: label: 'Show Title' description: 'Determines whether a title will be shown. If the Widget has a Title, it will be shown, otherwise it defaults to the Dashboard\'s Display Name or Name.' type: 'boolean' default: true required: false inlineJs: true order: 1 showPageName: label: 'Show Page Name' description: 'Determines whether the current page name will be shown as part of the title.' type: 'boolean' default: true required: false inlineJs: true order: 2 pageNameSeparator: label: 'Page Name Separator' description: 'Configures a string to use to separate the Dashboard name from the Page name. Defaults to a space.' type: 'string' required: false default: '' inlineJs: true defaultHidden: true order: 3 titleSize: label: 'Title Size' description: 'Sets the font size for the header title (if displayed). Any valid CSS height is allowed.' type: 'string' required: false inlineJs: true order: 5 logoUrl: label: 'Logo URL' description: 'Contains a URL to a dashboard logo to display before the title. Data URLs can be used.' type: 'string' required: false inlineJs: true order: 10 logoSize: label: 'Logo Size' description: 'Sets the height for the header logo (if displayed). The logo will be scaled without changing the aspect ratio. Any valid CSS height is allowed.' type: 'string' required: false inlineJs: true order: 11 link: label: 'Link' description: 'If set, makes the Logo and Title a link to this URL.' type: 'string' required: false inlineJs: true order: 20 parameters: label: 'Parameters' description: 'Contains properties for displaying Dashboard Parameters in the header.' type: 'propertyset' order: 20 properties: showParameters: label: 'Show Parameters' description: 'Determines whether Parameters will be shown.' type: 'boolean' default: false required: false inlineJs: true order: 1 showUpdateButton: label: 'Show Update Button' description: 'If true, an "Update" button will be displayed after the Parameters. The updateEvent property must be used to apply an action to the button click event, else nothing will happen.' type: 'boolean' default: false required: false order: 2 updateButtonLabel: label: 'Update Button Label' description: 'Customizes the label for the Update button, if shown.' type: 'string' default: 'Update' defaultHidden: true required: false order: 2 updateEvent: label: 'Update Button Click Event' description: 'This event occurs when the Update button is clicked, if shown.' type: 'editor' editorMode: 'javascript' required: false order: 10 parametersIncluded: label: 'Included Parameters' description: 'Optionally specifies an array of Parameter names, limiting the Header to only displaying the specified Parameters. This does not override the editInHeader property of each Parameter, which needs to be set true to appear in the Header.' type: 'string[]' required: false defaultHidden: true order: 11 customHtml: label: 'HTML Content' description: 'Provides additional HTML content to be displayed in the header. This can be used to customize the header display.' type: 'editor' editorMode: 'html' required: false inlineJs: true order: 30 html: name: 'html' label: 'HTML' icon: 'fa-html5' properties: dataSource: label: 'Data Source' description: 'Optional; the name of the Data Source providing data for this Widget. If set, the `html` property will be used as a repeater and rendered once for each row.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions order: 10 html: label: 'HTML' description: 'Contains HTML markup to be displayed. If dataSource is set, this HTML will be repeated for each row in the result.' type: 'editor' editorMode: 'html' required: false default: '' order: 11 preHtml: label: 'Pre-HTML' description: 'Optional, contains HTML markup which is displayed before the main body of HTML.' type: 'editor' editorMode: 'html' required: false default: '' order: 12 postHtml: label: 'Post-HTML' description: 'Optional, contains HTML markup which is displayed after the main body of HTML.' type: 'editor' editorMode: 'html' required: false default: '' order: 13 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 14 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' placeholder: 'Column name' type: 'string[]' inlineJs: true required: false order: 15 iframe: name: 'iframe' label: 'iFrame' icon: 'fa-desktop' properties: url: label: 'Url' description: 'Specifies the URL to be loaded within the Widget.' type: 'string' placeholder: 'Url' required: true default: 'http://www.expedia.com' order: 10 refresh: label: 'Refresh' description: 'Optional number of seconds; enables reloading the iframe contents periodically every N seconds.' placeholder: 'Seconds' type: 'integer' required: false order: 11 image: name: 'image' label: 'Image' icon: 'fa-image-o' properties: images: label: 'Images' singleLabel: 'Image' description: 'One or more Images to display in this widget.' type: 'propertyset[]' required: true default: [] order: 10 properties: url: label: 'URL' description: 'URL to the image to be displayed.' placeholder: 'Url' inlineJs: true required: true type: 'string' order: 1 link: label: 'Link' description: 'Optional, specifies a URL that will be opened if the image is clicked on.' placeholder: 'URL' type: 'url' inlineJs: true required: false order: 13 tooltip: label: 'Tooltip' description: 'Sets the tooltip of the image.' placeholder: 'Tooltip' type: 'string' inlineJs: true required: false defaultHidden: true order: 2 backgroundSize: label: 'Background-Size' description: 'Specifies the CSS property background-size, which determines how the image is fit into the Widget.' type: 'string' inlineJs: true required: false defaultHidden: true options: auto: value: 'auto' contain: value: 'contain' cover: value: 'cover' '100%': value: '100%' order: 3 backgroundPosition: label: 'Background Position' description: 'Specifies the CSS property background-position, which determines where the image is positioned in the Widget.' type: 'string' inlineJs: true required: false default: 'center' defaultHidden: true options: center: value: 'center' top: value: 'top' bottom: value: 'bottom' left: value: 'left' right: value: 'right' order: 4 backgroundColor: label: 'Background Color' description: 'Optionally specifies the CSS property background-color, which is drawn behind this image. It may appear if the image does not cover the Widget, or if the image is not opaque.' type: 'string' inlineJs: true required: false defaultHidden: true order: 5 backgroundRepeat: label: 'Background Repeat' description: 'Optionally specifies the CSS property background-repeat, which determiens if or how the image is repeated within the Widget.' type: 'string' inlineJs: true required: false default: 'no-repeat' defaultHidden: true options: 'no-repeat': value: 'no-repeat' 'repeat': value: 'repeat' 'repeat-x': value: 'repeat-x' 'repeat-y': value: 'repeat-y' 'space': value: 'space' 'round': value: 'round' order: 6 filters: label: 'Filters' description: 'Optionally applies one or more CSS filters to the image. If provided, it should be a string containing one or more filters, separated by spaces.' type: 'string' inlineJs: true required: false defaultHidden: true order: 7 duration: label: 'Auto-Rotate Duration' description: 'Optional number of seconds; enables rotating among a set of images periodically.' placeholder: 'Seconds' type: 'integer' default: 0 required: false order: 11 javascript: name: 'javascript' label: 'JavaScript' icon: 'fa-cogs' properties: dataSource: label: 'Data Source' description: 'Optional; the name of the Data Source providing data for this Widget. If set, the data source will be called and the result will be passed to the JavaScript function.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions order: 10 functionName: label: 'Function Name' description: 'JavaScript function name used to create a controller instance. Supports namespaces/drilldown using periods, e.g. Cyclotron.functions.scatterPlot' placeholder: 'Function Name' type: 'string' required: true order: 11 refresh: label: 'Refresh' description: 'Optional; enables re-invoking the javascript object periodically every N seconds.' placeholder: 'Seconds' type: 'integer' required: false order: 12 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 13 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' placeholder: 'Column name' type: 'string[]' inlineJs: true required: false order: 14 linkedWidget: name: 'linkedWidget' label: 'Linked Widget' icon: 'fa-link' properties: linkedWidget: label: 'Linked Widget' description: 'Selects another Widget in this Dashboard to link.' type: 'string' required: true options: linkedWidgetOptions order: 10 number: name: 'number' label: 'Number' icon: 'fa-cog' properties: dataSource: label: 'Data Source' description: 'Optional, but required to use data expressions e.g. "#{columnName}". The name of the Data Source providing data for this Widget.' placeholder: 'Data Source Name' type: 'string' required: false options: datasourceOptions order: 10 numbers: label: 'Numbers' singleLabel: 'number' description: 'One or more Numbers to display in this widget.' type: 'propertyset[]' required: true default: [] order: 11 properties: number: label: 'Number' description: 'Number value or expression.' placeholder: 'Value' inlineJs: true required: false type: 'string' order: 1 prefix: label: 'Prefix' description: 'Optional; specifies a prefix to append to the number.' placeholder: 'Prefix' type: 'string' inlineJs: true order: 2 suffix: label: 'Suffix' description: 'Optional; specifies a suffix to append to the number.' placeholder: 'Suffix' type: 'string' inlineJs: true order: 3 color: label: 'Color' description: 'Sets the color of the number.' placeholder: 'Color' type: 'string' inlineJs: true required: false defaultHidden: true order: 4 tooltip: label: 'Tooltip' description: 'Sets the tooltip of the number.' placeholder: 'Tooltip' type: 'string' inlineJs: true required: false defaultHidden: true order: 5 icon: label: 'Icon' description: 'Optional Font Awesome icon class to be displayed with the number.' placeholder: 'Icon Class' inlineJs: true type: 'string' defaultHidden: true order: 6 iconColor: label: 'Icon Color' description: 'Optionally specifies a color for the icon if the icon property is also set. The value can be a named color (e.g. "red"), a hex color (e.g. "#AA0088") or a data source column/inline javascript (e.g. "#{statusColor}").' type: 'string' inlineJs: true defaultHidden: true order: 7 iconTooltip: label: 'IconTooltip' description: 'Sets the tooltip of the icon.' placeholder: 'Icon Tooltip' type: 'string' inlineJs: true required: false defaultHidden: true order: 8 onClick: label: 'Click Event' description: 'This event occurs when the user clicks on the number. If this property is set with a JavaScript function, the function will be called as an event handler.' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 9 orientation: label: 'Orientation' description: 'Controls the direction in which the numbers are arranged.' type: 'string' required: false default: 'vertical' options: vertical: value: 'vertical' horizontal: value: 'horizontal' order: 12 autoSize: label: 'Auto-Size Numbers' description: 'If true, up to 4 numbers will be automatically sized-to-fit in the Widget. If false, or if there are more than four numbers, all numbers will be listed sequentially.' type: 'boolean' required: false default: true order: 13 link: label: 'Link' description: 'Optional, specifies a URL that will be displayed at the bottom of the widget as a link.' placeholder: 'URL' type: 'url' required: false order: 14 filters: label: 'Filters' description: "Optional, but if provided, specifies name-value pairs used to filter the data source's result set. This has no effect if the dataSource property is not set.\nOnly the first row of the data source is used to get data, so this property can be used to narrow down on the correct row" type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 15 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.\nOnly the first row of the data source is used to get data, so this property can be used to sort the data and ensure the correct row comes first.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' order: 16 openLayersMap: name: 'openLayersMap' label: 'OpenLayers Map' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for the overlays.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions order: 10 center: label: 'Center' description: 'X and Y coordinates to center the map on' type: 'propertyset' required: true properties: x: label: 'X' type: 'string' required: true order: 1 y: label: 'Y' type: 'string' required: true order: 2 order: 11 zoom: label: 'Zoom' description: 'Zoom level (0 is zoomed out)' type: 'integer' required: true order: 12 layers: label: 'Layers' singleLabel: 'layer' description: 'An array of layers that will be added to the map. Default is a single OpenStreetMap (OSM) layer.' type: 'propertyset[]' inlineJs: true properties: type: label: 'Type' description: 'The type of layer that will be added to the map. Specifying a source is mandatory except for VectorTile layers. Heatmap layer also requires Weight to be specified. If no type nor source are specified, Tile and OSM are used.' type: 'string' required: false default: 'Tile' options: image: value: 'Image' tile: value: 'Tile' heatmap: value: 'Heatmap' vector: value: 'Vector' vectortile: value: 'VectorTile' order: 1 source: label: 'Source' description: 'Source for the layer. Please refer to the help page if you do not know which one you need. Note that depending on the layer type (Image, Tile, Heatmap or VectorTile) only a subset of these sources is accepted.' type: 'propertyset' properties: name: label: 'Name' type: 'string' required: false default: 'OSM' options: BingMaps: value: 'BingMaps' CartoDB: value: 'CartoDB' Cluster: value: 'Cluster' ImageArcGISRest: value: 'ImageArcGISRest' ImageCanvas: value: 'ImageCanvas' ImageMapGuide: value: 'ImageMapGuide' ImageStatic: value: 'ImageStatic' ImageWMS: value: 'ImageWMS' OSM: value: 'OSM' Raster: value: 'Raster' Stamen: value: 'Stamen' TileArcGISRest: value: 'TileArcGISRest' TileDebug: value: 'TileDebug' TileJSON: value: 'TileJSON' TileUTFGrid: value: 'TileUTFGrid' TileWMS: value: 'TileWMS' Vector: value: 'Vector' VectorTile: value: 'VectorTile' WMTS: value: 'WMTS' XYZ: value: 'XYZ' Zoomify: value: 'Zoomify' order: 1 configuration: label: 'Configuration' description: 'Configuration object. Please refer to the widget help page to know how to configure each source.' type: 'editor' editorMode: 'javascript' required: false order: 2 order: 2 weight: label: 'Weight (for heatmap)' description: '' type: 'string' required: false order: 3 styleFunction: label: 'Style function' description: 'Style function (for vector layers, see https://openlayers.org/en/v4.6.5/apidoc/ol.html#.StyleFunction). You can specify a style function to be applied when selecting a feature by defining it as "Cyclotron.featureSelectStyleFunction" in the Scripts section, otherwise the default select style will be applied.' type: 'editor' editorMode: 'javascript' required: false order: 4 order: 13 overlayGroups: label: 'Overlay Groups' singleLabel: 'group' description: 'Groups of overlays that will be added to the map, i.e., elements that will be displayed over the map and attached to a given position. Each group of overlays can have one overlay selected at a time.' type: 'propertyset[]' inlineJs: true properties: name: label: 'Name' type: 'string' required: true order: 1 initiallySelected: label: 'Overlay Initially Selected' description: 'Name of the overlay that will be assigned the CSS class on selection when the page is loaded. If not provided, all overlays will have the regular CSS class until one is clicked. Note that to use this field you must provide names for the overlays.' type: 'string' required: false order: 2 overlays: label: 'Overlays' singleLabel: 'overlay' description: '' type: 'propertyset[]' inlineJs: true required: true properties: name: label: 'Name' description: 'Unique identifier for the overlay' type: 'string' required: false order: 1 cssClass: label: 'CSS Class' description: 'CSS class name (defined beforehand in the Styles section of the dashboard) for the overlay' type: 'string' required: true order: 2 cssClassSelected: label: 'CSS Class On Selection' description: 'Optional CSS class name (defined beforehand in the Styles section of the dashboard) for the selected overlay' type: 'string' required: false order: 3 position: label: 'Position' description: 'X and Y coordinates of the location where the overlay will be attached' type: 'propertyset' properties: x: label: 'X' type: 'string' required: false order: 1 y: label: 'Y' type: 'string' required: false order: 2 order: 4 positioning: label: 'Positioning' description: 'Where the overlay is placed with respect to Position. Default is top-left.' type: 'string' required: false default: 'top-left' options: bottomLeft: value: 'bottom-left' bottomCenter: value: 'bottom-center' bottomRight: value: 'bottom-right' centerLeft: value: 'center-left' centerCenter: value: 'center-center' centerRight: value: 'center-right' topLeft: value: 'top-left' topCenter: value: 'top-center' topRight: value: 'top-right' order: 5 template: label: 'Template' description: 'HTML template for overlay content.' type: 'editor' editorMode: 'html' required: false default: '' order: 6 order: 3 order: 15 controls: label: 'Controls' singleLabel: 'control' description: 'An array of controls that will be added to the map.' type: 'propertyset[]' inlineJs: true defaultHidden: true default: [] properties: control: label: 'Control' type: 'string' required: false options: Attribution: value: 'Attribution' MousePosition: value: 'MousePosition' OverviewMap: value: 'OverviewMap' ScaleLine: value: 'ScaleLine' Zoom: value: 'Zoom' ZoomSlider: value: 'ZoomSlider' ZoomToExtent: value: 'ZoomToExtent' order: 1 order: 16 dataSourceMapping: label: 'DataSource Mapping' description: 'Overlay properties must be mapped to datasource fields. The datasource is required to have at least fields for CSS class and the list of overlays.' type: 'propertyset' defaultHidden: true properties: identifierField: label: 'Identifier Field' description: 'Datasource field with a unique identifier for the overlay group. If it is not specified and the datasource provides more that one object (i.e. overlay group), each group will be assigned a random ID.' type: 'string' required: false order: 1 initiallySelectedField: label: 'Overlay Initially Selected Field' description: 'Optional datasource field with the ID of the overlay that will be assigned the CSS class on selection when the page is loaded. If not provided, all overlays will have the regular CSS class until one is clicked.' type: 'string' required: false defaultHidden: true order: 2 overlayListField: label: 'Overlay List Field' description: 'Datasource field containing the list of overlays for the group' type: 'string' required: true order: 3 cssClassField: label: 'CSS Class Field' description: 'Datasource field with the style for each overlay in the group as name of a CSS class defined in the Styles section of the editor.' type: 'string' required: true order: 4 cssClassOnSelectionField: label: 'CSS Class On Selection Field' description: 'Optional datasource field with the CSS class for each overlay after it has been clicked. It must be the name of a CSS class defined in the Styles section of the editor.' type: 'string' required: false defaultHidden: true order: 5 overlayIdField: label: 'Overlay Identifier Field' description: 'Datasource field with a unique identifier for each overlay in the group list. If it is missing, a random ID will be generated.' type: 'string' required: false order: 6 positionField: label: 'Position Field' description: 'Datasource field with an array of coordinates (i.e. [x_coord, y_coord]) for each overlay in the group list. Alternatively, single fields for X and Y can be specified.' type: 'string' required: false order: 7 xField: label: 'X Coordinate Field' description: 'Datasource field with X coordinate for each overlay in the group list.' type: 'string' required: false defaultHidden: true order: 8 yField: label: 'Y Coordinate Field' description: 'Datasource field with Y coordinate for each overlay in the group list.' type: 'string' required: false defaultHidden: true order: 9 positioningField: label: 'Positioning Field' description: 'Datasource field with the positioning (e.g. "center-center") of each overlay.' type: 'string' required: false defaultHidden: true order: 10 templateField: label: 'Template Field' description: 'Datasource field with the HTML template for the content of each overlay.' type: 'string' required: false defaultHidden: true order: 11 order: 14 specificEvents: label: 'Specific Events' singleLabel: 'param-event' description: 'Array of parameters (defined beforehand in the Parameters section of the dashboard) and widget events that can trigger their change.' type: 'propertyset[]' inlineJs: true defaultHidden: true default: [] properties: paramName: label: 'Parameter Name' type: 'string' required: true order: 1 event: label: 'Event' type: 'string' required: true options: clickOnOverlay: value: 'clickOnOverlay' clickOnWMSLayer: value: 'clickOnWMSLayer' selectVectorFeature: value: 'selectVectorFeature' order: 2 section: label: 'Section' description: 'Name of the overlay group that triggers the event, for the event "clickOnOverlay". Name of the WMS layer that triggers the event (e.g. "topp:states"), for the event "clickOnWMSLayer". For other events, you can leave this option empty. For the event "selectVectorFeature", you can set the index (zero-based) of the layer the features should be selected from, so that features of the specified layer will be stored in the parameter, otherwise features of any layer will be stored in the same parameter. Some widgets (e.g. slider) have one section only, i.e. the whole widget triggers the event, while others may have some sections that trigger the same kind of event (e.g. in OpenLayers maps, any overlay group can trigger clickOnOverlay event).' type: 'string' required: false order: 3 order: 17 projection: label: 'Projection' description: 'Projection. Default is EPSG:3857 (Spherical Mercator).' type: 'string' required: false default: 'EPSG:3857' options: 'EPSG:3857': value: 'EPSG:3857' 'EPSG:4326': value: 'EPSG:4326' order: 18 qrcode: name: 'qrcode' label: 'QRcode' icon: 'fa-cogs' properties: text: label: 'Text' description: 'Text content of the generated QR code.' placeholder: 'QR Code Contents' type: 'string' required: false order: 10 maxSize: label: 'Max Size' description: 'Maximum height/width of the QR code.' type: 'integer' required: false order: 11 useUrl: label: 'Use URL' description: 'Overrides the text property and generates a QR code with the current Dashboard\'s URL.' type: 'boolean' default: false required: false order: 12 dataSource: label: 'Data Source' description: 'Optional; specifies the name of a Dashboard data source. If set, the data source will be called and the result will be available for the QR code generation.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions defaultHidden: true order: 13 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false defaultHidden: true order: 14 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' placeholder: 'Column name' type: 'string[]' inlineJs: true required: false defaultHidden: true order: 15 colorDark: label: 'Dark Color' description: 'CSS color name or hex color code, used to draw the dark portions of the QR code.' placeholder: 'CSS color or hex color code' type: 'string' default: '#000000' required: false defaultHidden: true order: 16 colorLight: label: 'Light Color' description: 'CSS color name or hex color code, used to draw the dark portions of the QR code.' placeholder: 'CSS color or hex color code' type: 'string' default: '#ffffff' required: false defaultHidden: true order: 17 sample: text: 'hello' slider: name: 'slider' label: 'Slider' icon: 'fa-bar-chart-o' properties: minValue: label: 'Minimum date-time' description: 'Starting value of the slider' type: 'string' placeholder: 'YYYY-MM-DD HH:mm' required: true order: 10 maxValue: label: 'Maximum date-time' description: 'Ending value of the slider' type: 'string' placeholder: 'YYYY-MM-DD HH:mm' required: true order: 11 momentFormat: label: 'Date-time Format' description: 'Any valid moment() format. Default is YYYY-MM-DD HH:mm.' type: 'string' default: 'YYYY-MM-DD HH:mm' required: false order: 12 step: label: 'Step' description: 'Number of time units (e.g. days) between slider values (default is 1)' type: 'integer' required: false default: 1 order: 13 direction: label: 'Direction' description: 'Left-to-right or right-to-left. Default is left-to-right.' type: 'string' required: false defaultHidden: true default: 'ltr' options: ltr: value: 'ltr' rtl: value: 'rtl' order: 14 orientation: label: 'Orientation' description: 'Horizontal or vertical. Default is horizontal.' type: 'string' required: false defaultHidden: true default: 'horizontal' options: horizontal: value: 'horizontal' vertical: value: 'vertical' order: 15 player: label: 'Player' description: 'Play/pause button for automatic sliding' type: 'propertyset' properties: showPlayer: label: 'Show Player' description: 'Show player. Default is false.' type: 'boolean' required: false default: false order: 1 interval: label: 'Interval' description: 'Seconds between each sliding. Default is 1.' type: 'integer' required: false default: 1 order: 2 startOnPageReady: label: 'Start On Page Ready' description: 'Start the player automatically when the page is loaded' type: 'boolean' required: false default: false order: 3 order: 16 timeUnit: label: 'Time Unit' description: 'Each slider value corresponds to a minute, hour, day or month. Default is days.' type: 'string' required: false defaultHidden: true default: 'days' options: minutes: value: 'minutes' hours: value: 'hours' days: value: 'days' months: value: 'months' order: 17 pips: label: 'Pips' description: 'Scale/points shown near the slider' type: 'propertyset' properties: mode: label: 'Mode' description: 'Determines where to place pips.' type: 'string' required: false default: 'steps' options: range: value: 'range' steps: value: 'steps' positions: value: 'positions' count: value: 'count' values: value: 'values' order: 1 values: label: 'Values' description: 'Additional options for Positions, Count and Values mode. For Count mode provide an integer. For Positions and Values mode provide comma-separated integers.' type: 'string' required: false order: 2 stepped: label: 'Stepped' description: 'Match pips with slider values (default is false)' required: false default: false type: 'boolean' order: 3 density: label: 'Density' description: 'Number of pips in one percent of the slider range (default is 1)' type: 'integer' required: false default: 1 order: 4 format: label: 'Format' description: 'Show pip values in the same format as slider format (default is true)' type: 'boolean' required: false default: true order: 5 order: 18 tooltips: label: 'Tooltips' description: 'Show tooltips (default is false)' type: 'boolean' required: false defaultHidden: true default: false order: 19 twoHandles: label: 'Show Two Handles' description: 'Show two handles instead of one (default is false). In this case automatic sliding cannot be used. The handles will be placed at the first and last steps unless you specify a different position with Initial Handle Position.' type: 'boolean' required: false defaultHidden: true default: false order: 20 handlePosition: label: 'Initial Handle Position' description: 'Initial position of the handle, as a date-time in the same format used for Minimum and Maximum date-time. If the slider has two handles, enter two comma-separated date-times. Inline JavaScript can also be used, e.g. "${Cyclotron.parameters.handlePos}". By default the handle(s) will be positioned at the first (and last) value.' type: 'string' required: false defaultHidden: true order: 21 specificEvents: label: 'Specific Events' singleLabel: 'param-event' description: 'Array of parameters (defined beforehand in the Parameters section of the dashboard) and widget events that can trigger their change.' type: 'propertyset[]' inlineJs: true defaultHidden: true default: [] properties: paramName: label: 'Parameter Name' type: 'string' required: true order: 1 event: label: 'Event' type: 'string' required: true options: dateTimeChange: value: 'dateTimeChange' order: 2 section: label: 'Section' description: 'Specify which handle generates this event. If the slider has only one handle, you can leave this option empty.' type: 'string' default: 'first' required: false options: firstHandle: value: 'first' secondHandle: value: 'second' order: 3 order: 22 stoplight: name: 'stoplight' label: 'Stoplight' icon: 'fa-cog' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for this Widget.' placeholder: 'Data Source Name' type: 'string' required: false options: datasourceOptions order: 10 rules: label: 'Rules' description: 'Contains rule expressions for the different states of the Stoplight. The rules will be evaluated from red to green, and only the first rule that returns true will be enabled' type: 'propertyset' required: true order: 11 properties: green: label: 'Green' description: 'The rule expression evaluated to determine if the green light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.' type: 'string' placeholder: 'Rule Expression' inlineJs: true order: 3 yellow: label: 'Yellow' description: 'The rule expression evaluated to determine if the yellow light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.' type: 'string' placeholder: 'Rule Expression' inlineJs: true order: 2 red: label: 'Red' description: 'The rule expression evaluated to determine if the red light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.' type: 'string' placeholder: 'Rule Expression' inlineJs: true order: 1 tooltip: label: 'Tooltip' description: 'Sets the tooltip of the stoplight.' placeholder: 'Tooltip' type: 'string' inlineJs: true required: false defaultHidden: true order: 12 filters: label: 'Filters' description: "Optional, but if provided, specifies name-value pairs used to filter the data source's result set. This has no effect if the dataSource property is not set.\nOnly the first row of the data source is used to get data, so this property can be used to narrow down on the correct row" type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 15 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.\nOnly the first row of the data source is used to get data, so this property can be used to sort the data and ensure the correct row comes first.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' order: 16 table: name: 'table' label: 'Table' icon: 'fa-table' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for this Widget.' placeholder: 'Data Source name' type: 'string' required: true options: datasourceOptions order: 10 columns: label: 'Columns' singleLabel: 'column' description: 'Specifies the columns to display in the table, and their properties. If omitted, the columns will be automatically determined, either using a list of fields provided by the data source, or by looking at the first row.' type: 'propertyset[]' inlineJs: true properties: name: label: 'Name' description: 'Indicates the name of the data source field to use for this column.' type: 'string' inlineJs: true order: 1 label: label: 'Label' description: 'If provided, sets the header text for the column. If omitted, the name will be used. "#value" can be used to reference the "name" property of the column.' type: 'string' inlineJs: true order: 2 text: label: 'Text' description: 'Overrides the text in the cell using this value as an expression.' type: 'string' inlineJs: true defaultHidden: true order: 3 tooltip: label: 'Tooltip' description: 'Optionally specifies a tooltip to display for each cell in the column.' type: 'string' inlineJs: true defaultHidden: true headerTooltip: label: 'Header Tooltip' description: 'Optionally specifies a tooltip to display for the column header. "#value" can be used to reference the "name" property of the column.' type: 'string' inlineJs: true defaultHidden: true onClick: label: 'Click Event' description: 'This event occurs when the user clicks on a cell in this column. If this property is set with a JavaScript function, the function will be called as an event handler.' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true link: label: 'Link' description: 'If provided, the cell text will be made into a link rather than plain text.' type: 'url' inlineJs: true defaultHidden: true openLinksInNewWindow: label: 'Open Links in New Window' description: 'If true, links will open in a new browser window; this is the default.' type: 'boolean' default: true defaultHidden: true numeralformat: label: 'Numeral Format' description: 'Optionally specifies a Numeral.js-compatible format string, used to reformat the column value for display.' type: 'string' inlineJs: true defaultHidden: true image: label: 'Image' description: 'Optionally specifies a URL to an image to display in the column. The URL can be parameterized using any column values.' type: 'url' inlineJs: true defaultHidden: true imageHeight: label: 'Image Height' description: 'Optionally sets the height for the images displayed using the image property. If omitted, each image will be displayed at "1em" (the same height as text in the cell). Any valid CSS value string can be used, e.g. "110%", "20px", etc.' type: 'string' inlineJs: true defaultHidden: true icon: label: 'Icon' description: 'Optionally specifies a Font Awesome icon class to be displayed in the cell.' type: 'string' inlineJs: true defaultHidden: true iconColor: label: 'Icon Color' description: 'Optionally specifies a color for the icon if the icon property is also set. The value can be a named color (e.g. "red"), a hex color (e.g. "#AA0088") or a data source column/inline javascript (e.g. "#{statusColor}").' type: 'string' inlineJs: true defaultHidden: true border: label: 'Border' description: 'Optionally draws a border on either or both sides of the column. If set, this value should be either "left", "right", or "left,right" to indicate on which sides of the column to draw the borders.' type: 'string' inlineJs: true defaultHidden: true group: label: 'Column Group' description: 'Optionally puts the column in a column group. The value must be a string, which will be displayed above all consecutive columns with the same group property. The column group row will not appear unless at least one column has a group specified.' type: 'string' inlineJs: true defaultHidden: true groupRows: label: 'Group Rows' description: 'Optionally combines identical, consecutive values within a column. If set to true, and depending on the sort, repeated values in a column will be combined into a single cell with its rowspan value set. If the rows are separated by a resort, the combined cells will be split apart again. This property can be applied to any column(s) in the table. The default value is false.' type: 'boolean' default: false defaultHidden: true columnSortFunction: label: 'Column Sort Function' description: 'When using wildcard or regex expression in the `name` field, this property optionally provides a sort function used to order the generated columns. This function takes an array of column names and can return a sorted (or modified) array. Example: "${function(columns){return _.sortBy(columns);}}".' type: 'string' inlineJs: true defaultHidden: true columnsIgnored: label: 'Columns Ignored' description: 'When using wildcard or regex expression in the `name` field, this can contain a list of one or more column names that should not be matched.' type: 'string[]' required: false inlineJs: false defaultHidden: true order: 10 sample: name: '' rules: label: 'Rules' singleLabel: 'rule' description: 'Specifies an array of rules that will be run on each row in the table. Style properties can be set for every matching rule, on either the entire row or a subset of columns.' type: 'propertyset[]' inlineJs: true properties: rule: label: 'Rule' description: 'The rule expression evaluated to determine if this rule applies to a row. It can contain column values using #{name} notation. It will be evaluated as javascript, and should return true or false.' type: 'string' required: true inlineJs: true order: 1 columns: label: 'Columns Affected' description: 'Optionally specifies an array of column names, limiting the rule\'s effect to only the cells specified, rather than the entire row.' type: 'string[]' required: false order: 2 columnsIgnored: label: 'Columns Ignored' description: 'Optionally specifies an array of column names that the rule does NOT apply to.' type: 'string[]' required: false order: 3 name: label: 'Name' description: 'Indicates the name of the data source field to use for this column.' type: 'string' inlineJs: true defaultHidden: true 'font-weight': label: 'Font-Weight (CSS)' description: 'CSS setting for `font-weight`' type: 'string' inlineJs: true defaultHidden: true color: label: 'Color (CSS)' description: 'CSS setting for `color`' type: 'string' inlineJs: true defaultHidden: true 'background-color': label: 'Background Color (CSS)' description: 'CSS setting for `background-color`' type: 'string' inlineJs: true defaultHidden: true order: 11 sample: rule: 'true' freezeHeaders: label: 'Freeze Headers' description: 'Enables frozen headers at the top of the widget when scrolling' type: 'boolean' default: false required: false order: 12 omitHeaders: label: 'Omit Headers' description: 'Disables the table header row' type: 'boolean' default: false required: false order: 13 enableSort: label: 'Enable Sort' description: 'Enable or disable user sort controls' type: 'boolean' default: true required: false order: 14 rowHeight: label: 'Minimum Row Height' description: 'Specifies the (minimum) height in pixels of all rows (including the header row). The actual height of a row may be greater than this value, depending on the contents. If this is not set, each row will automatically size to its contents.' type: 'integer' required: false order: 15 pagination: label: 'Pagination' description: 'Controls pagination of the Table.' type: 'propertyset' required: false defaultHidden: true order: 16 properties: enabled: label: 'Enable Pagination' description: 'Enables or disables pagination for this Table Widget.' type: 'boolean' default: false required: false order: 1 autoItemsPerPage: label: 'Auto Items Per Page' description: 'Enables automatic detection of the number of rows to display in order to fit in the widget dimensions. Requires rowHeight property to be configured to work accurately. To manually size, set false and configure itemsPerPage instead.' type: 'boolean' default: true required: false order: 2 itemsPerPage: label: 'Items Per Page' description: 'Controls how many row are displayed on each page. If autoItemsPerPage is true, this is ignored.' type: 'integer' required: false order: 3 belowPagerMessage: label: 'Below Pager Message' description: 'If set, displays a message below the pager at the bottom of the Widget. The following variables can be used: #{itemsPerPage}, #{totalItems}, #{currentPage}.' type: 'string' required: false order: 4 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 17 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' order: 18 sortFunction: label: 'Sort Function' description: 'Optional, specifies an alternative function to the default sort implementation.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 19 onSort: label: 'Sort Event' description: 'This event occurs when the user changes the sort order of a column. If this property is set with a JavaScript function, the function will be called as an event handler. Return false from the function to prevent the default sort implementation from being applied.' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 20 tableau: name: 'tableau' label: 'Tableau' icon: 'fa-cog' properties: params: label: 'Parameters' description: 'An object of key-value pairs that Tableau uses to render the report. These parameters are specific to Tableau and will be passed-through to the view.' type: 'hash' required: true editorMode: 'json' order: 10 treemap: name: 'treemap' label: 'Treemap' icon: 'fa-tree' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for this Widget.' placeholder: 'Data Source name' type: 'string' required: true options: datasourceOptions order: 10 labelProperty: label: 'Label Property' description: 'The name of the property to use as the label of each item.' type: 'string' inlineJs: true required: false default: 'name' defaultHidden: true order: 11 valueProperty: label: 'Value Property' description: 'The name of the property to use to calculate the size of each item.' type: 'string' inlineJs: true required: false default: 'value' defaultHidden: true order: 12 valueDescription: label: 'Value Description' description: 'A short description of the property used to calculate the size of each item. Used in tooltips.' type: 'string' inlineJs: true required: false defaultHidden: true order: 13 valueFormat: label: 'Value Format' description: 'Specifies a Numeral.js-compatible format string used to format the label of the size value.' type: 'string' default: ',.2f' required: false defaultHidden: true inlineJs: true options: default: value: '0,0.[0]' percent: value: '0,0%' integer: value: '0,0' currency: value: '$0,0' order: 14 colorProperty: label: 'Color Property' description: 'The name of the property to use to calculate the color of each item. If omitted, the TreeMap will not be colored.' type: 'string' inlineJs: true required: false default: 'color' order: 15 colorDescription: label: 'Color Description' description: 'A short description of the property used to calculate the color of each item. Used in tooltips.' type: 'string' inlineJs: true required: false defaultHidden: true order: 16 colorFormat: label: 'Color Format' description: 'Specifies a Numeral.js-compatible format string used to format the label of the color value.' type: 'string' default: ',.2f' required: false defaultHidden: true inlineJs: true options: default: value: '0,0.[0]' percent: value: '0,0%' integer: value: '0,0' currency: value: '$0,0' large: value: '0a' order: 17 colorStops: label: 'Color Stops' singleLabel: 'color' description: 'Specifies a list of color stops used to build a gradient.' type: 'propertyset[]' inlineJs: true properties: value: label: 'Value' description: 'The numerical value assigned to this color stop.' type: 'number' required: true inlineJs: true order: 1 color: label: 'Color' description: 'The color to display at this color stop. Hex codes or CSS colors are permitted.' type: 'string' required: false inlineJs: true order: 2 order: 18 showLegend: label: 'Show Legend' description: 'Enables or disables the color legend.' type: 'boolean' default: true required: false order: 19 legendHeight: label: 'Legend Height' description: 'Specifies the height of the legend in pixels.' type: 'number' default: 30 required: false defaultHidden: true order: 20 widgetContainer: name: 'widgetContainer' label: 'Widget Container' icon: 'fa-desktop' properties: layout: label: 'Layout' description: 'Contains properties for configuring the Container layout and dimensions.' type: 'propertyset' default: {} required: false properties: gridColumns: label: 'Grid Columns' description: 'Specifies the total number of horizonal grid squares available in the grid. The grid squares will be scaled to fit the container. If omitted, the number of columns will be calculated dynamically.' type: 'integer' required: false order: 0 gridRows: label: 'Grid Rows' description: 'Specifies the total number of vertical grid squares available in the grid. The grid squares will be scaled vertically to fit the container. If omitted, the grid squares will be literally square, e.g. the height and width will be the same. When omitted, the widgets may not fill the entire container, or they may scroll vertically. Use this property to make widgets scale vertically to fit the container.' type: 'integer' required: false order: 1 gridWidthAdjustment: label: 'Grid Container Width Adjustment' description: 'Specifies an adjustment (in pixels) to the width of the container when calculating the grid layout. If the value is positive, the container width will have the adjustment added to it (making each column wider), whereas if it is negative, the container width will be reduced (making each column skinnier).' type: 'integer' default: 0 required: false defaultHidden: true order: 2 gridHeightAdjustment: label: 'Grid Container Height Adjustment' description: 'Specifies an adjustment (in pixels) to the height of the container when calculating the grid layout. If the value is positive, the container height will have the adjustment added to it (making each row taller), whereas if it is negative, the container height will be reduced (making each row shorter).' type: 'integer' default: 0 required: false order: 3 gutter: label: 'Gutter' description: 'Controls the space (in pixels) between widgets positioned in the grid. The default value is 10.' type: 'integer' default: 10 required: false defaultHidden: true order: 5 borderWidth: label: 'Border Width' description: 'Specifies the pixel width of the border around each widget. Can be set to 0 to remove the border. If omitted, the theme default will be used.' type: 'integer' default: null required: false defaultHidden: true order: 6 margin: label: 'Margin' description: 'Controls the empty margin width (in pixels) around the outer edge of the container. Can be set to 0 to remove the margin.' type: 'integer' default: 10 required: false defaultHidden: true order: 7 scrolling: label: 'Scrolling Enabled' description: 'Enables vertical scrolling of the container to display content longer than the current size.' type: 'boolean' default: true required: false defaultHidden: true order: 8 order: 10 sample: layout: gridColumns: 2 gridRows: 2 youtube: name: 'youtube' label: 'YouTube' icon: 'fa-youtube' properties: videoId: label: 'Video / Playlist ID' description: 'A YouTube video ID or Playlist ID. Multiple video IDs can be separated by commas.' type: 'string' inlineJs: true placeholder: 'ID' required: true order: 10 autoplay: label: 'Auto-Play' description: 'If true, automatically plays the video when the Widget is loaded.' type: 'boolean' inlineJs: true default: true required: false order: 13 loop: label: 'Loop' description: 'If true, automatically loops the video when it completes.' type: 'boolean' inlineJs: true default: true required: false order: 14 enableKeyboard: label: 'Enable Keyboard' description: 'If true, enables keyboard controls which are disabled by default.' type: 'boolean' inlineJs: true default: false required: false defaultHidden: true order: 15 enableControls: label: 'Enable Controls' description: 'If true, enables on-screen video controls which are disabled by default.' type: 'boolean' inlineJs: true default: false required: false defaultHidden: true order: 16 showAnnotations: label: 'Show Annotations' description: 'If true, displays available annotations over the video.' type: 'boolean' inlineJs: true default: false required: false defaultHidden: true order: 17 showRelated: label: 'Show Related' description: 'If true, displays related videos at the end of this video.' type: 'boolean' inlineJs: true default: false required: false defaultHidden: true order: 18 } # Copy Theme options to inherited locations exports.dashboard.properties.pages.properties.theme.options = exports.dashboard.properties.theme.options exports.dashboard.properties.pages.properties.widgets.properties.theme.options = exports.dashboard.properties.theme.options exports.dashboard.properties.pages.properties.themeVariant.options = exports.dashboard.properties.themeVariant.options exports.dashboard.properties.pages.properties.widgets.properties.themeVariant.options = exports.dashboard.properties.themeVariant.options # Copy Style options to inherited locations exports.dashboard.properties.pages.properties.style.options = exports.dashboard.properties.style.options # Table Widget: Column properties duplicated in Rules: tableProperties = exports.widgets.table.properties _.defaults tableProperties.rules.properties, _.omit(tableProperties.columns.properties, 'label') # Copy some chart themes #exports.widgets.chart.themes.lightborderless = exports.widgets.chart.themes.light # Populate Help tags with properties helpDashboards = _.find(exports.help, { name: 'Dashboards' }) helpDashboards.tags = _.union helpDashboards.tags, _.map exports.dashboard.properties, (value, name) -> name helpDataSources = _.find(exports.help, { name: 'Data Sources' }) helpDataSources.tags = _.union helpDataSources.tags, _.map exports.dashboard.properties.dataSources.properties, (value, name) -> name helpWidgets = _.find(exports.help, { name: 'Widgets' }) helpWidgets.tags = _.union helpWidgets.tags, _.map exports.dashboard.properties.pages.properties.widgets.properties, (value, name) -> name propertyMapHelper = (value, name) -> v = _.cloneDeep value v.name = name v # Add Widget and Data Source help pages helpDataSources.children = _.map _.sortBy(exports.dashboard.properties.dataSources.options, 'name'), (dataSource) -> { name: dataSource.label || dataSource.value path: '/partials/help/datasources/' + dataSource.value + '.html' tags: _.map dataSource.properties, propertyMapHelper } helpWidgets.children = _.map _.sortBy(exports.widgets, 'name'), (widget) -> { name: widget.label || widget.name path: '/widgets/' + widget.name + '/help.html' tags: _.map widget.properties, propertyMapHelper } return exports
125022
### # Copyright (c) 2013-2015 the original author or authors. # # Licensed under the MIT License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.opensource.org/licenses/mit-license.php # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific # language governing permissions and limitations under the License. ### # Common Config File - all default or shared configs cyclotronServices.factory 'commonConfigService', -> linkedWidgetOptions = (dashboard) -> linkedWidgets = {} _.each dashboard.pages, (page, pageIndex) -> _.each page.widgets, (widget, widgetIndex) -> return if widget.widget == 'linkedWidget' widgetName = _.titleCase(widget.widget) if widget.name?.length > 0 or widget.title?.length > 0 widgetName += ': ' + (widget.name || widget.title) linkedWidgets['Page ' + (pageIndex + 1) + ': ' + widgetName] = { value: pageIndex + ',' + widgetIndex } linkedWidgets datasourceOptions = (dashboard) -> dataSources = {} _.each dashboard.dataSources, (dataSource) -> dataSources[dataSource.name] = { value: dataSource.name } dataSources exports = { version: '1.48.0' logging: enableDebug: false authentication: enable: false loginMessage: 'Please login using your LDAP username and password.' analytics: enable: false newUser: enableMessage: true welcomeMessage: 'It looks like you\'re new here! Take a look at the <a href="/help"><i class="fa fa-question-circle" /> Help</a> page.' iconClass: 'fa-info' autoDecayDuration: 1 # Dashboard settings dashboard: properties: name: label: 'Name' description: 'Dashboard Name. This is required and cannot be changed after the Dashboard is created.' placeholder: 'Dashboard Name' type: 'string' required: true order: 0 displayName: label: 'Display Name' description: 'Display Name; this is displayed in the browser title bar or the Header Widget.' placeholder: 'Display Name' type: 'string' required: false inlineJs: true defaultHidden: true order: 1 description: label: 'Description' description: 'A short summary of the Dashboard\'s purpose or capabilities.' placeholder: 'A short summary of the Dashboard\'s purpose or capabilities.' type: 'string' required: false order: 2 theme: label: 'Theme' description: 'The default Page Theme for the Dashboard. If this property is set, the value will be applied to any Pages that have not specified a Theme. If it is not set, the default value of "Dark" will be used.' type: 'string' default: 'dark' required: false options: charcoal: label: 'Charcoal' value: 'charcoal' dashboardBackgroundColor: '#1E2328' dark: label: 'Dark' value: 'dark' dashboardBackgroundColor: '#2f2f2f' darkmetro: label: 'Dark Metro' value: 'darkmetro' dashboardBackgroundColor: '#2f2f2f' gto: label: 'GTO' value: 'gto' dashboardBackgroundColor: 'white' light: label: 'Light' value: 'light' dashboardBackgroundColor: 'white' lightborderless: label: 'Light (borderless)' value: 'lightborderless' dashboardBackgroundColor: 'white' dark2: label: 'Very Dark' value: 'dark2' dashboardBackgroundColor: 'black' order: 5 themeVariant: label: 'Theme Variant' description: 'The default Theme Variant for the Dashboard; each Theme may or may not implement each variant. If this property is set, the value will be applies to any Pages that have not specified a Theme Variant. If it is not set, the default variant will be used.' type: 'string' default: 'default' required: false defaultHidden: true options: default: value: 'default' transparent: value: 'transparent' 'transparent-unpadded': value: 'transparent-unpadded' order: 6 style: label: 'Style' description: 'The default Page Style for the Dashboard. If this property is set, the value will be applied to any Pages that have not specified a Style. If it is not set, the default value of "Normal" will be used.' type: 'string' default: 'normal' required: false options: normal: value: 'normal' fullscreen: value: 'fullscreen' defaultHidden: true order: 7 autoRotate: label: 'Auto-Rotate' description: 'If set to true, Cyclotron will automatically rotate between pages of the Dashboard based on the duration property for each Page. Set this value false to require manual rotation.' type: 'boolean' default: false required: false defaultHidden: true order: 10 duration: label: 'Auto-Rotate Duration (seconds)' description: 'If autoRotate is enabled, this controls the default interval to rotate to the next page. This value can be overridded at a page level.' type: 'integer' placeholder: 'Seconds per page' default: 60 required: false defaultHidden: true order: 11 preload: label: 'Pre-Load Time (seconds)' description: 'The amount of time, in seconds, before rotating to preload the next page. If set, this value will apply to all pages in the Dashboard. If autoRotate is false, this value is ignored.' placeholder: 'Seconds' type: 'integer' default: 0.050 required: false defaultHidden: true order: 12 allowFullscreen: label: 'Allow Fullscreen' description: 'If true, each Widget on a Page can be maximized to fill the entire Dashboard. This setting can be overridden by each Page/Widget.' type: 'boolean' default: true required: false defaultHidden: true allowExport: label: 'Allow Export' description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This setting can be overridden by each Page/Widget.' type: 'boolean' default: true required: false defaultHidden: true openLinksInNewWindow: label: 'Open Links in New Window' description: 'If true, all links will open in a new browser window; this is the default.' type: 'boolean' required: false default: true defaultHidden: true showWidgetErrors: label: 'Show Error Messages on Widgets' description: 'If true, allows error messages to be displayed on Widgets. This setting can be overridden by each Page/Widget.' type: 'boolean' required: false default: true defaultHidden: true showDashboardControls: label: 'Show Dashboard Controls' description: 'If false, hides the default Dashboard controls (rotation, export, etc)' type: 'boolean' required: false default: true defaultHidden: true sidebar: label: 'Sidebar' description: '' type: 'propertyset' default: {} defaultHidden: true properties: showDashboardSidebar: label: 'Show Dashboard Sidebar' description: 'If false, hides the default Dashboard Sidebar.' type: 'boolean' required: false default: false order: 10 showDashboardTitle: label: 'Include Dashboard Title' description: 'Enables a section of the sidebar for the Dashboard title.' type: 'boolean' required: false default: true defaultHidden: true order: 11 showToolbar: label: 'Include Toolbar' description: 'Enables a toolbar in the sidebar.' type: 'boolean' required: false default: true defaultHidden: true order: 12 showHideWidgets: label: 'Include Show/Hide Widgets' description: 'Enables a section of the sidebar for overriding the visibility of Widgets.' type: 'boolean' required: false default: false defaultHidden: true order: 13 sidebarContent: label: 'Custom Sidebar Sections' singleLabel: 'Section' description: 'One or more sections of content to display in the Sidebar.' type: 'propertyset[]' default: [] order: 15 properties: heading: label: 'Heading' description: 'Heading for the Sidebar section.' type: 'string' inlineJs: true order: 1 html: label: 'HTML Content' description: 'HTML Content to display.' placeholder: 'Value' type: 'editor' editorMode: 'html' inlineJs: true order: 2 pages: label: 'Pages' description: 'The list of Page definitions which compose the Dashboard.' type: 'pages' default: [] required: true properties: name: label: 'Name' description: 'Name of this page; used in the browser title and URL.' placeholder: 'Page Name' type: 'string' required: false order: 0 layout: label: 'Layout' description: 'Contains properties for configuring the Page layout and dimensions.' type: 'propertyset' default: {} required: false properties: gridColumns: label: 'Grid Columns' description: 'Specifies the total number of horizonal grid squares available in the grid. The grid squares will be scaled to fit the browser window. If omitted, the number of columns will be calculated dynamically.' type: 'integer' required: false order: 0 gridRows: label: 'Grid Rows' description: 'Specifies the total number of vertical grid squares available in the grid. The grid squares will be scaled vertically to fit the browser window. If omitted, the grid squares will be literally square, e.g. the height and width will be the same. When omitted, the widgets may not fill the entire browser window, or they may scroll vertically. Use this property to make widgets scale vertically to fit the dashboard.' type: 'integer' required: false order: 1 gridWidthAdjustment: label: 'Grid Page Width Adjustment' description: 'Specifies an adjustment (in pixels) to the width of the page when calculating the grid layout. If the value is positive, the page width will have the adjustment added to it (making each column wider), whereas if it is negative, the page width will be reduced (making each column skinnier).' type: 'integer' default: 0 required: false defaultHidden: true order: 2 gridHeightAdjustment: label: 'Grid Page Height Adjustment' description: 'Specifies an adjustment (in pixels) to the height of the page when calculating the grid layout. If the value is positive, the page height will have the adjustment added to it (making each row taller), whereas if it is negative, the page height will be reduced (making each row shorter). This is commonly used with a fixed-height Header widget.' type: 'integer' default: 0 required: false order: 3 gutter: label: 'Gutter' description: 'Controls the space (in pixels) between widgets positioned in the grid. The default value is 10.' type: 'integer' default: 10 required: false defaultHidden: true order: 5 borderWidth: label: 'Border Width' description: 'Specifies the pixel width of the border around each widget. Can be set to 0 to remove the border. If omitted, the theme default will be used.' type: 'integer' default: null required: false defaultHidden: true order: 6 margin: label: 'Margin' description: 'Controls the empty margin width (in pixels) around the outer edge of the Dashboard. Can be set to 0 to remove the margin.' type: 'integer' default: 10 required: false defaultHidden: true order: 7 scrolling: label: 'Scrolling Enabled' description: 'Enables vertical scrolling of the page to display content longer than the current browser size.' type: 'boolean' default: true required: false defaultHidden: true order: 8 order: 2 widgets: label: 'Widgets' description: 'An array of one or more Widgets to display on the page' type: 'propertyset[]' subState: 'edit.widget' headingfn: 'getWidgetName' default: [] required: true properties: widget: label: 'Type' description: 'The type of Widget to be rendered.' type: 'string' required: true name: label: 'Name' description: 'Internal Widget name, displayed in the Dashboard Editor.' placeholder: 'Name' type: 'string' required: false defaultHidden: true inlineJs: false order: 1 title: label: 'Title' description: 'Specifies the title of the widget. Most widgets will display the title at the top of the widget. If omitted, nothing will be displayed and the widget contents will occupy the entire widget boundaries.' placeholder: 'Widget Title' type: 'string' required: false inlineJs: true order: 2 gridHeight: label: 'Grid Rows' description: 'Specifies the number of vertical grid squares for this widget to occupy. Instead of an absolute height, this sets the relative size based on grid units.' placeholder: 'Number of Rows' type: 'integer' default: '1' required: false order: 100 gridWidth: label: 'Grid Columns' description: 'Specifies the number of horizontal grid squares for this widget to occupy. Instead of an absolute width, this sets the relative size based on grid units.' placeholder: 'Number of Columns' type: 'integer' default: '1' required: false order: 101 height: label: 'Height' description: 'If set, specifies the absolute display height of the widget. Any valid CSS value can be used (e.g. "200px", "40%", etc).' placeholder: 'Height' type: 'string' required: false defaultHidden: true order: 102 width: label: 'Width' description: 'If set, specifies the absolute display width of the widget. Any valid CSS value can be used (e.g. "200px", "40%", etc).' placeholder: 'Width' type: 'string' required: false defaultHidden: true order: 103 autoHeight: label: 'Auto-Height (Fit to Contents)' description: 'If true, disables both the gridHeight and height properties, and allows the Widget to be vertically sized to fit its contents.' type: 'boolean' required: false defaultHidden: true order: 104 helpText: label: 'Help Text' description: 'Provides an optional help text for the Widget, available via a help icon in the corner of the Widget.' type: 'string' required: false inlineJs: true defaultHidden: true order: 109 theme: label: 'Theme' description: 'If set, overrides the Page theme and allows a widget to have a different theme from the rest of the Page and Widgets.' type: 'string' inherit: true required: false defaultHidden: true order: 110 themeVariant: label: 'Theme Variant' description: 'If set, overrides the Page theme variant and allows a widget to have a different theme variant from the rest of the Page and Widgets.' type: 'string' inherit: true required: false defaultHidden: true order: 111 noData: label: 'No Data Message' description: 'If set, displays this message in the Widget when no data is loaded from the Data Source. If not set, no message will be displayed' type: 'string' inlineJs: true required: false defaultHidden: true order: 120 noscroll: label: 'No Scroll' description: 'If set to true, the widget will not have scrollbars and any overflow will be hidden. The effect of this setting varies per widget.' type: 'boolean' default: false required: false defaultHidden: true order: 121 allowFullscreen: label: 'Allow Fullscreen' description: 'If true, the Widget can be maximized to fill the entire Dashboard; if false, the ability to view in fullscreen is disabled. This property overrides the Page setting.' type: 'boolean' inherit: true required: false defaultHidden: true order: 122 allowExport: label: 'Allow Export' description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This property overrides the Page setting.' type: 'boolean' inherit: true required: false defaultHidden: true order: 123 showWidgetErrors: label: 'Show Error Messages on Widgets' description: 'If true, allows error messages to be displayed on Widgets. This property overrides the Page setting.' type: 'boolean' required: false inherit: true defaultHidden: true order: 124 hidden: label: 'Hidden' description: 'If true, the Widget will not be displayed in the Dashboard and will not occupy space in the Layout rendering. The Widget will still be initialized, however.' type: 'boolean' default: false required: false defaultHidden: true order: 125 genericEvents: label: 'Generic Events' singleLabel: 'param-event' description: 'Array of parameters (defined beforehand in the Parameters section of the dashboard) and events that can trigger their change within widgets. Note that adding a Name to the widget is mandatory for this property to work.' type: 'propertyset[]' inlineJs: true defaultHidden: true default: [] properties: paramName: label: 'Parameter Name' type: 'string' required: true order: 1 event: label: 'Event' type: 'string' required: true options: clickOnWidget: value: 'clickOnWidget' order: 2 order: 126 parameterSubscription: label: 'Subscription To Parameters' singleLabel: 'param' description: 'Specifies a list of parameters the widget subscribes to, i.e., that the widget uses and that can cause its reload upon change. See section Parameters for more details.' type: 'string[]' inlineJs: true defaultHidden: true default: [] order: 127 container: label: 'Container' description: 'Name of the Container Widget that should contain this widget' type: 'string' inlineJs: true defaultHidden: true order: 128 order: 3 duration: label: 'Auto-Rotate Duration (seconds)' description: 'The number of seconds to remain on this page before rotating to the next page. If autoRotate is set to false, this value is ignored.' placeholder: 'Seconds per page' inherit: true type: 'integer' required: false defaultHidden: true order: 4 frequency: label: 'Frequency' description: 'If greater than one, this page will only be shown on every N cycles through the dashboard. Defaults to 1, meaning the Page will be shown on every cycle.' default: 1 type: 'integer' required: false defaultHidden: true order: 5 theme: label: 'Theme' description: 'The theme for the Page. If not set, the Dashboard setting or default value will apply.' type: 'string' inherit: true required: false defaultHidden: true order: 6 themeVariant: label: 'Theme Variant' description: 'The theme variant for the Page. If not set, the Dashboard setting or default value will apply.' type: 'string' inherit: true required: false defaultHidden: true order: 7 style: label: 'Style' description: 'The style for the Page. If not set, the Dashboard setting or default value will apply.' type: 'string' inherit: true required: false defaultHidden: true order: 8 allowFullscreen: label: 'Allow Fullscreen' description: 'If true, each Widget on the page can be maximized to fill the entire Dashboard. This setting can be overridden by each Widget.' type: 'boolean' inherit: true required: false defaultHidden: true order: 10 allowExport: label: 'Allow Export' description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This setting can be overridden by each Widget.' type: 'boolean' inherit: true required: false defaultHidden: true order: 11 showWidgetErrors: label: 'Show Error Messages on Widgets' description: 'If true, allows error messages to be displayed on Widgets. This setting can be overridden by each Widget.' type: 'boolean' required: false inherit: true defaultHidden: true order: 12; dataSources: label: 'Data Sources' description: 'A list of Data Sources which connect to external services and pull in data for the Dashboard.' type: 'datasources' default: [] required: false properties: name: label: 'Name' description: 'The Data Source Name is used to reference the Data Source from a widget' placeholder: 'Data Source Name' type: 'string' required: true order: 1 type: label: 'Type' description: 'Specifies the implementation type of the Data Source' type: 'string' required: true order: 0 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted' type: 'hash' inlineJsKey: true inlineJsValue: true required: false defaultHidden: true order: 101 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' defaultHidden: true order: 102 preload: label: 'Preload' description: 'By default, each Data Source is loaded only when it is used, e.g. when a Widget consuming it is rendered. Setting this true causes Cyclotron to load the Data Source when the Dashboard is initialized.' type: 'boolean' inlineJs: false required: false default: false defaultHidden: true order: 103 deferred: label: 'Deferred' description: 'Prevents execution of the data source until execute() is manually called on the Data Source. This should only be used when using custom JavaScript to execute this Data Source, otherwise the Data Source will never run.' type: 'boolean' inlineJs: false required: false default: false defaultHidden: true order: 103 errorHandler: label: 'Error Handler' description: 'Specifies an optional JavaScript function that is called if an errors occurs. It can return a different or modified error message. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 104 parameterSubscription: label: 'Subscription To Parameters' singleLabel: 'param' description: 'Specifies a list of parameters the data source subscribes to, i.e., that can cause the re-execution of the data source upon change. See section Parameters for more details.' type: 'string[]' inlineJs: true defaultHidden: true default: [] order: 105 options: cloudwatch: value: 'cloudwatch' label: 'CloudWatch' message: 'Amazon CloudWatch monitors operational and performance metrics for your AWS cloud resources and applications. Refer to the <a href="http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/Welcome.html" target="_blank">API Documentation</a> for information on configuring the available options.' icon: 'fa-cloud-download' properties: url: label: 'URL' description: 'Specifies the Amazon CloudWatch Endpoint for the desired region, e.g. "monitoring.us-west-2.amazonaws.com".' placeholder: 'CloudWatch Endpoint' type: 'url' inlineJs: true inlineEncryption: true required: true order: 10 awsCredentials: label: 'AWS Credentials' description: 'AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.' type: 'propertyset' required: true order: 12 properties: accessKeyId: label: 'Access Key Id' description: 'AWS access key id' type: 'string' placeholder: 'Access Key Id' inlineJs: true inlineEncryption: true order: 1 secretAccessKey: label: 'Secret Access Key' description: 'AWS sercet access key' type: 'string' placeholder: 'Secret Access Key' inlineJs: true inlineEncryption: true order: 2 parameters: label: 'CloudWatch Parameters' description: 'Set of parameters for the CloudWatch API.' type: 'propertyset' required: true order: 13 properties: Action: label: 'Action' description: 'Specifies one of the CloudWatch actions.' type: 'string' default: 'auto' inlineJs: true options: ListMetrics: value: 'ListMetrics' GetMetricStatistics: value: 'GetMetricStatistics' required: true order: 1 Namespace: label: 'Namespace' description: 'The namespace to filter against.' type: 'string' inlineJs: true required: false order: 2 MeasureName: label: 'Metric Name' description: 'The name of the metric to filter against.' type: 'string' inlineJs: true required: false order: 3 Dimensions: label: 'Dimensions' description: 'Optional; a list of Dimension key/values to filter against.' type: 'hash' required: false inlineJsValue: true inlineEncryption: true order: 4 Statistics: label: 'Statistics' description: 'Specifies one or more Statistics to return.' type: 'string[]' inlineJs: true options: SampleCount: value: 'SampleCount' Average: value: 'Average' Sum: value: 'Sum' Minimum: value: 'Minimum' Maximum: value: 'Maximum' required: true order: 5 Period: label: 'Period' description: 'The granularity, in seconds, of the returned datapoints. A Period can be as short as one minute (60 seconds) or as long as one day (86,400 seconds), and must be a multiple of 60.' type: 'integer' default: 60 required: false placeholder: 'Number of Seconds' order: 6 StartTime: label: 'Start Time' description: 'The date/time of the first datapoint to return. The time stamp must be in ISO 8601 UTC format (e.g., 2014-09-03T23:00:00Z).' type: 'string' inlineJs: true required: false order: 8 EndTime: label: 'End Time' description: 'The date/time of the last datapoint to return. The time stamp must be in ISO 8601 UTC format (e.g., 2014-09-03T23:00:00Z).' type: 'string' inlineJs: true required: false order: 9 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 15 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 16 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 17 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 11 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 18 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 cyclotronData: value: 'cyclotronData' label: 'CyclotronData' icon: 'fa-cloud-download' message: 'Cyclotron has built-in support for a limited amount of data storage using uniquely-named buckets. Refer to to the Documentation for more details.' properties: key: label: 'Bucket Key' description: 'Specifies the unique key to a Cyclotron Data bucket.' placeholder: 'Bucket Key' type: 'string' inlineJs: true required: true order: 10 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 14 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 15 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 16 url: label: 'Cyclotron Server' description: 'Specifies which Cyclotron server to request data from. If omitted, the default sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 11 elasticsearch: value: 'elasticsearch' label: 'Elasticsearch' icon: 'fa-cloud-download' properties: url: label: 'URL' description: 'Specifies the Elasticsearch endpoint.' placeholder: 'Elasticsearch URL' type: 'url' inlineJs: true inlineEncryption: true required: true order: 10 index: label: 'Index' description: 'Specifies the name of the Elasticsearch index to query.' type: 'string' inlineJs: true inlineEncryption: true required: true order: 12 method: label: 'API Name' description: 'Indicates which Elasticsearch API method to use; defaults to "_search".' type: 'string' inlineJs: true inlineEncryption: true defaultHidden: true default: '_search' required: false order: 13 request: label: 'Elasticsearch Request' description: 'Specifies the Elasticsearch JSON request.' placeholder: 'JSON' type: 'editor' editorMode: 'json' inlineJs: true inlineEncryption: true required: true order: 14 responseAdapter: label: 'Response Adapter' description: 'Determines how the Elasticsearch response will be converted to Cyclotron\'s data format. Defaults to "auto".' type: 'string' default: 'auto' inlineJs: true options: 'Auto': value: 'auto' 'Hits': value: 'hits' 'Aggregations': value: 'aggregations' 'Raw': value: 'raw' required: false order: 15 awsCredentials: label: 'AWS Credentials' description: 'Optional AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 16 properties: accessKeyId: label: 'Access Key Id' description: 'AWS access key id' type: 'string' placeholder: 'Access Key Id' inlineJs: true inlineEncryption: true order: 1 secretAccessKey: label: 'Secret Access Key' description: 'AWS sercet access key' type: 'string' placeholder: 'Secret Access Key' inlineJs: true inlineEncryption: true order: 2 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 20 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 21 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 22 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 23 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 24 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 graphite: value: 'graphite' label: 'Graphite' icon: 'fa-cloud-download' message: 'The Graphite Data Source connects to any <a href="http://graphite.readthedocs.org/" target="_blank">Graphite<a> server to load time-series metrics via the Render api. For more details on usage, refer to the Graphite <a href="http://graphite.readthedocs.org/en/latest/render_api.html" target="_blank">documentation</a>.' properties: url: label: 'URL' description: 'The Graphite server' placeholder: 'Graphite Server URL or IP' type: 'url' inlineJs: true inlineEncryption: true required: true order: 10 targets: label: 'Targets' description: 'One or more Graphite metrics, optionally with metrics.' type: 'string[]' inlineJs: true inlineEncryption: true required: true order: 11 from: label: 'From' description: 'Specifies the absolute or relative beginning of the time period to retrieve. If omitted, it defaults to 24 hours ago (per Graphite).' placeholder: 'Start Time' type: 'string' inlineJs: true inlineEncryption: true required: false order: 12 until: label: 'Until' description: 'Specifies the absolute or relative end of the time period to retrieve. If omitted, it defaults now (per Graphite).' placeholder: 'End Time' type: 'string' inlineJs: true inlineEncryption: true required: false order: 13 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 14 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 15 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Graphite result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 16 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 11 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 17 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 influxdb: value: 'influxdb' label: 'InfluxDB' icon: 'fa-cloud-download' message: '<a href="https://www.influxdata.com/time-series-platform/influxdb/" target="_blank">InfluxDB</a> is an open source time series database built from the ground up to handle high write and query loads.' properties: url: label: 'URL' description: 'The InfluxDB server' placeholder: 'InfluxDB Server URL or IP' type: 'url' inlineJs: true required: true order: 10 database: label: 'Database' description: 'Specifies the target InfluxDB database for the query.' placeholder: 'Database' type: 'string' required: true inlineJs: true inlineEncryption: true required: false order: 11 query: label: 'Query' description: 'An InfluxQL query.' type: 'string' inlineJs: true inlineEncryption: true required: true order: 11 precision: label: 'Precision' description: 'Overrides the default timestamp precision.' type: 'string' default: 'ms' inlineJs: true options: h: value: 'h' m: value: 'm' s: value: 's' ms: value: 'ms' u: value: 'u' ns: value: 'ns' order: 11 username: label: 'Username' description: 'Optional; username for authentication, if enabled.' type: 'string' inlineJs: true inlineEncryption: true order: 15 password: label: 'Password' description: 'Optional; password for authentication, if enabled.' type: 'string' inputType: 'password' inlineJs: true inlineEncryption: true order: 16 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 21 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 22 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Graphite result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 23 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 11 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 24 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 javascript: value: 'javascript' label: 'JavaScript' icon: 'fa-cloud-download' message: 'The JavaScript Data Source allows custom JavaScript to be used to load or generate a Data Source.' properties: processor: label: 'Processor' description: 'Specifies a JavaScript function used to provide data for the Data Source, either by directly returning a data set, or resolving a promise asynchronously. The function is called with an optional promise which can be used for this purpose.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: true order: 10 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 11 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 12 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the JavaScript result dataset before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 13 json: value: 'json' label: 'JSON' icon: 'fa-cloud-download' properties: url: label: 'URL' description: 'Specifies the JSON Web Service URL.' placeholder: 'Web Service URL' type: 'url' inlineJs: true inlineEncryption: true required: true order: 10 queryParameters: label: 'Query Parameters' description: 'Optional query parameters which are added to the URL. If there are already query parameters in the URL, these will be appended. The keys and values are both URL-encoded.' type: 'hash' required: false inlineJsKey: true inlineJsValue: true inlineEncryption: true defaultHidden: true order: 12 options: label: 'Options' description: 'Optional request parameters that are passed to the library making the request.' type: 'hash' required: false inlineJsValue: true inlineEncryption: true defaultHidden: true order: 13 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 14 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 15 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 16 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 11 awsCredentials: label: 'AWS Credentials' description: 'Optional AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 17 properties: accessKeyId: label: 'Access Key Id' description: 'AWS access key id' type: 'string' placeholder: 'Access Key Id' inlineJs: true inlineEncryption: true order: 1 secretAccessKey: label: 'Secret Access Key' description: 'AWS sercet access key' type: 'string' placeholder: 'Secret Access Key' inlineJs: true inlineEncryption: true order: 2 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 18 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 ###scopes: label: 'Scopes' description: 'Optional list of scopes (comma- or space-separated, according to what the authorization server accepts) that will be passed to the authorization server' type: 'string' placeholder: 'Scopes' inlineJs: true inlineEncryption: true order: 4 ### mock: value: 'mock' label: 'Mock' icon: 'fa-cloud-download' message: 'The Mock Data Source generates sample data for testing a dashboard.' properties: format: label: 'Format' description: 'Selects the format of the mock data from these possible values: ["object", "pie", "ducati"]. Defaults to "object".' type: 'string' required: false default: 'object' options: object: value: 'object' pie: value: 'pie' large: value: 'large' ducati: value: 'ducati' order: 10 refresh: label: 'Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 11 odata: value: 'odata' label: 'OData' icon: 'fa-cloud-download' properties: url: label: 'URL' description: 'Specifies the OData Service URL.' placeholder: 'Service URL' type: 'url' inlineJs: true inlineEncryption: true required: true order: 10 responseAdapter: label: 'Response Adapter' description: 'Determines how the response will be converted to Cyclotron\'s data format. Defaults to "raw", i.e. the result is returned as is. Use "Entity Set" to read a list of objects. Use "Single Entity" to read a single object. Use "Primitive Property" to have a single value.' type: 'string' default: 'raw' inlineJs: true options: 'Primitive Property': value: 'primitive_prop' 'Single Entity': value: 'single_entity' 'Entity Set': value: 'entity_set' 'Raw': value: 'raw' required: false order: 11 queryParameters: label: 'Query Parameters' description: 'Optional query parameters which are added to the URL. If there are already query parameters in the URL, these will be appended. The keys and values are both URL-encoded.' type: 'hash' required: false inlineJsKey: true inlineJsValue: true inlineEncryption: true defaultHidden: true order: 12 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 13 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not a JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 14 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not a JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 15 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 16 options: label: 'Options' description: 'Optional request parameters that are passed to the library making the request.' type: 'hash' required: false inlineJsValue: true inlineEncryption: true defaultHidden: true order: 17 awsCredentials: label: 'AWS Credentials' description: 'Optional AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 18 properties: accessKeyId: label: 'Access Key Id' description: 'AWS access key id' type: 'string' placeholder: 'Access Key Id' inlineJs: true inlineEncryption: true order: 1 secretAccessKey: label: 'Secret Access Key' description: 'AWS sercet access key' type: 'string' placeholder: 'Secret Access Key' inlineJs: true inlineEncryption: true order: 2 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 19 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 splunk: value: 'splunk' label: 'Splunk' icon: 'fa-cloud-download' properties: query: label: 'Query' description: 'Splunk query' placeholder: 'Splunk query' type: 'textarea' required: true order: 10 earliest: label: 'Earliest Time' description: 'Sets the earliest (inclusive), respectively, time bounds for the search. The time string can be either a UTC time (with fractional seconds), a relative time specifier (to now) or a formatted time string.' placeholder: 'Earliest Time' type: 'string' inlineJs: true inlineEncryption: true required: false order: 11 latest: label: 'Latest Time' description: 'Sets the latest (exclusive), respectively, time bounds for the search. The time string can be either a UTC time (with fractional seconds), a relative time specifier (to now) or a formatted time string.' placeholder: 'Latest Time' type: 'string' inlineJs: true inlineEncryption: true required: false order: 12 username: label: 'Username' description: 'Username to authenticate with Splunk' type: 'string' required: true inlineJs: true inlineEncryption: true order: 13 password: label: '<PASSWORD>' description: '<PASSWORD> to authenticate with Splunk' type: 'string' inputType: 'password' required: true inlineJs: true inlineEncryption: true order: 14 host: label: 'Host' description: 'Splunk API host name' placeholder: 'Splunk API host name' type: 'string' inputType: 'string' required: false defaultHidden: false order: 15 url: label: 'URL' description: 'The Splunk API Search URL' placeholder: 'Splunk API Search URL' type: 'url' inlineJs: true inlineEncryption: true default: 'https://#{host}:8089/services/search/jobs/export' defaultHidden: true required: false order: 16 refresh: label: 'Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 17 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 18 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Splunk result dataset before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 19 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. This is required to use encrypted strings within the Data Source properties. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 20 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 21 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 parameters: label: 'Parameters' description: 'A list of Parameters that can be used to configure the Dashboard.' type: 'propertyset[]' default: [] required: false properties: name: label: 'Name' description: 'The name used to set or reference this Parameter.' type: 'string' required: true placeholder: 'Parameter Name' order: 0 defaultValue: label: 'Default Value' description: 'The value used if the Parameter is not set when opening the Dashboard.' type: 'string' placeholder: 'Default Value' required: false inlineJs: true order: 1 showInUrl: label: 'Show in URL' description: 'Determines whether or not the Parameter is displayed in the query string of the Dashboard URL.' type: 'boolean' default: true required: false order: 2 editInHeader: label: 'Editable in Header' description: 'If true, the Parameter will be displayed and configurable in the Parameter section of the Header Widget (if used).' type: 'boolean' default: false required: false order: 3 persistent: label: 'Persistent' description: 'If true, the value of this Parameter will be persisted in the user\'s browser across multiple sessions.' type: 'boolean' default: false required: false order: 4 changeEvent: label: 'Change Event' description: 'This event occurs when the Parameter value is modified. It does not fire when the Dashboard is being initialized. Expects a JavaScript function in the form function(parameterName, newValue, oldValue).' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 10 editing: label: 'Editing' description: 'Configuration for how this Parameter can be edited in the Dashboard.' type: 'propertyset' required: false default: {} defaultHidden: true order: 15 properties: displayName: label: 'Display Name' description: 'The display name used for this Parameter.' type: 'string' required: false placeholder: 'Display Name' order: 1 editorType: label: 'Editor Type' description: 'Determines the type of editor used to configured this Parameter (e.g. in the Header Widget).' type: 'string' required: false default: 'textbox' order: 2 options: textbox: value: 'textbox' dropdown: value: 'dropdown' autocomplete: value: 'autocomplete' links: value: 'links' checkbox: value: 'checkbox' radiobuttons: value: 'radiobuttons' datetime: value: 'datetime' date: value: 'date' time: value: 'time' dataSource: label: 'Data Source' description: 'Optionally specifies a Data Source providing dropdown options for this Parameter.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions order: 4 datetimeFormat: label: 'Date/Time Format' description: 'The Moment.js-compatible date/time format string used to read/write datetimes to this Parameter. Only used if the editor type is "datetime", "date", or "time". Defaults to an ISO 8601 format.' type: 'string' required: false placeholder: 'Format' defaultHidden: true order: 5 minCharNumber: label: 'Minimal Number of Characters' description: 'Minimal number of characters typed before autocomplete activates. Must be greather than or equal to 0. Defaults to 1.' type: 'integer' required: false default: 1 defaultHidden: true order: 6 allowNonMatching: label: 'Allow Non-Matching Values' description: 'If true, values that do not match any value in the list can be entered in the autocomplete input field. If false, only values in the list are allowed.' type: 'boolean' default: true required: false defaultHidden: true order: 7 allowEmpty: label: 'Allow Empty Input field' description: 'If true, the autocomplete input field can be empty. If false, the field is automatically populated with the currently highlighted value of the list when it is not focused.' type: 'boolean' default: true required: false defaultHidden: true order: 7 broadcastUpdate: label: 'Broadcast Parameter update' description: 'Notify the dashboard that the value has changed' type: 'boolean' default: true required: false defaultHidden: true order: 8 sample: name: '' defaultValue: '' scripts: label: 'Scripts' description: 'Defines a list of inline JavaScript or external JavaScript URIs that are loaded when the Dashboard initializes.' type: 'propertyset[]' default: [] required: false properties: name: label: 'Name' description: 'Display name of the script' type: 'string' placeholder: 'Name' required: false order: 0 path: label: 'Path' description: 'URL to a JavaScript file, to be loaded along with the Dashboard' type: 'url' placeholder: 'JavaScript file URL' required: false order: 1 text: label: 'JavaScript Text' description: 'Inline JavaScript to be run when the Dashboard is loaded' type: 'editor' editorMode: 'javascript' placeholder: 'Inline JavaScript' required: false order: 2 singleLoad: label: 'Single-Load' description: 'If true, this Script will only be loaded once when the Dashboard is loaded. Otherwise, it will be rerun every time the Dashboard internally refreshes. Scripts loaded from a path are always treated as single-load, and this property is ignored.' type: 'boolean' required: false default: false order: 3 sample: text: '' styles: label: 'Styles' description: 'Defines a list of inline CSS or external CSS URIs that are loaded when the Dashboard initializes.' type: 'propertyset[]' default: [] required: false properties: name: label: 'Name' description: 'Display name of the style' type: 'string' placeholder: 'Name' required: false order: 0 path: label: 'Path' description: 'URL to a CSS file, to be loaded along with the Dashboard' type: 'url' placeholder: 'CSS file URL' required: false order: 0 text: label: 'CSS Text' description: 'Inline CSS to be run when the Dashboard is loaded' type: 'editor' editorMode: 'css' placeholder: 'Inline CSS' required: false order: 1 sample: text: '' controls: # Controls how long to display the controls before hiding. duration: 1000 # Controls how close the mouse must be before the controls appear hitPaddingX: 60 hitPaddingY: 50 sample: name: '' sidebar: showDashboardSidebar: true pages: [] # Dashboard Sidebar dashboardSidebar: footer: logos: [{ title: 'Cyclotron' src: '/img/favicon32.png' href: '/' }] # List of help pages help: [ { name: 'About' path: '/partials/help/about.html' tags: ['about', 'terminology', 'features'] children: [ { name: 'Quick Start' path: '/partials/help/quickstart.html' tags: ['help', 'creating', 'tags', 'theme', 'revisions', 'preview', 'data sources', 'pages', 'layout', 'widgets'] } { name: 'JSON' path: '/partials/help/json.html' tags: ['json'] } { name: 'Examples' path: '/partials/help/examples.html' tags: ['examples', 'cyclotron-examples'] } { name: 'Browser Compatibility' path: '/partials/help/browserCompat.html' tags: ['browser', 'compatibility', 'firefox', 'chrome', 'internet explorer', 'ie', 'safari', 'browsercheck'] } { name: 'Permissions' path: '/partials/help/permissions.html' tags: ['permissions', 'edit permission', 'view permission', 'editors', 'viewers', 'restricted', 'login', 'rest', 'api'] } { name: 'Analytics' path: '/partials/help/analytics.html' tags: ['analytics', 'pageviews', 'visits', 'metrics'] } { name: 'Encrypted Strings' path: '/partials/help/encryptedStrings.html' tags: ['encryption', 'encrypted', '!{', 'decrypt', 'encrypt'] } { name: 'JavaScript API' path: '/partials/help/javascriptApi.html' tags: ['javascript', 'api', 'scripting'] } { name: 'CyclotronData' path: '/partials/help/cyclotrondata.html' tags: ['cyclotrondata', 'data', 'storage', 'bucket', 'api'] } { name: '3rd Party Libraries' path: '/partials/help/3rdparty.html' tags: ['libraries', 'jquery', 'moment', 'lodash', 'angular', 'numeral', 'localforage', 'uri', 'bootstrap', 'c3.js', 'd3.js', 'font awesome', 'highcharts', 'masonry', 'metricsgraphics', 'select2', 'spin.js'] } { name: 'Hotkeys' path: '/partials/help/hotkeys.html' tags: ['hotkeys', 'keys', 'shortcuts'] } { name: 'API' path: '/partials/help/api.html' tags: ['api', 'rest', 'service'] } ] } { name: 'Dashboards' path: '/partials/help/dashboards.html' tags: ['dashboards', 'pages', 'dataSources', 'scripts', 'parameters'] children: [ { name: 'Pages' path: '/partials/help/pages.html' tags: ['pages', 'widgets'] } { name: 'Layout' path: '/partials/help/layout.html' tags: ['layout', 'grid', 'mobile', 'scrolling', 'position', 'absolute'] } { name: 'Parameters' path: '/partials/help/parameters.html' tags: ['parameters'] } { name: 'Scripts' path: '/partials/help/scripts.html' tags: ['scripts', 'javascript'] } { name: 'Styles' path: '/partials/help/styles.html' tags: ['styles', 'css'] } ] } { name: 'Data Sources' path: '/partials/help/dataSources.html' tags: ['data sources', 'dataSources', 'tabular', 'post-processor', 'post processor', 'pre-processor', 'pre processor'] } { name: 'Widgets' path: '/partials/help/widgets.html' tags: ['widgets'] } ] # Formats supported for Dashboard Export exportFormats: [{ label: 'PDF', value: 'pdf' }] # Page settings page: sample: frequency: 1 layout: gridColumns: 2 gridRows: 2 widgets: [] # Widget settings widgets: annotationChart: name: 'annotationChart' label: 'Annotation Chart' icon: 'fa-bar-chart-o' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for this Widget.' placeholder: 'Data Source name' type: 'string' required: true options: datasourceOptions order: 10 xAxis: label: 'X-Axis' description: 'Configuration of the X-axis.' type: 'propertyset' required: true properties: column: label: 'Column Name' description: 'Name of the column in the Data Source used for the x-axis.' placeholder: 'Column Name' inlineJs: true type: 'string' order: 1 format: label: 'Format' description: 'Specifies which format the incoming datetime data is in.' type: 'string' options: date: value: 'date' epoch: value: 'epoch' epochmillis: value: 'epochmillis' string: value: 'string' order: 2 formatString: label: 'Format String' description: 'Used with the String format to specify how the string should be parsed.' type: 'string' order: 3 order: 11 series: label: 'Series' singleLabel: 'series' description: 'One or more series to display in the annotation chart.' type: 'propertyset[]' required: true default: [] order: 12 properties: column: label: 'Column Name' description: 'Name of the column in the Data Source to use as the y-axis value for this series.' placeholder: 'Column Name' inlineJs: true type: 'string' order: 1 label: label: 'Label' description: 'Display label for the series; if omitted, the column name will be used.' placeholder: 'Label' inlineJs: true type: 'string' order: 2 annotationTitleColumn: label: 'Annotation Title Column Name' description: 'Name of the column in the Data Source to use as the title of annotations corresponding to each point.' placeholder: 'Column Name' inlineJs: true type: 'string' order: 3 annotationTextColumn: label: 'Annotation Text Column Name' description: 'Name of the column in the Data Source to use as the text of annotations corresponding to each point.' placeholder: 'Column Name' inlineJs: true type: 'string' order: 4 secondaryAxis: label: 'Secondary Axis' description: 'If true, places the series on a second axis on the left of the chart.' inlineJs: true type: 'boolean' order: 5 options: label: 'Options' description: 'Additional options for the Google Annotation chart. Any supported option is allowed here.' type: 'propertyset' required: false inlineJs: true properties: allValuesSuffix: label: 'All Values Suffix' description: 'A suffix to be added to all values in the legend and tick labels in the vertical axes.' placeholder: 'Suffix' type: 'string' inlineJs: true defaultHidden: true annotationsWidth: label: 'Annotations Width' description: 'The width (in percent) of the annotations area, out of the entire chart area. Must be a number in the range 5-80.' type: 'integer' inlineJs: true defaultHidden: true displayAnnotations: label: 'Display Annotations' description: 'Controls whether annotations are displayed along with the chart.' type: 'boolean' inlineJs: true default: true defaultHidden: true displayAnnotationsFilter: label: 'Display Annotations Filter' description: 'If set to true, the chart will display a filter control to filter annotations.' type: 'boolean' inlineJs: true default: false defaultHidden: true displayDateBarSeparator: label: 'Display Date Bar Separator' description: 'If set to true, the chart will display a small bar separator ( | ) between the series values and the date in the legend.' type: 'boolean' inlineJs: true default: false defaultHidden: true displayLegendDots: label: 'Display Legend Dots' description: 'If set to true, the chart will display dots next to the values in the legend text.' type: 'boolean' inlineJs: true defaultHidden: true displayLegendValues: label: 'Display Legend Values' description: 'If set to true, the chart will display the highlighted values in the legend.' type: 'boolean' inlineJs: true defaultHidden: true displayRangeSelector: label: 'Display Range Selector' description: 'If set to true, the chart will display the zoom range selection area (the area at the bottom of the chart).' type: 'boolean' inlineJs: true defaultHidden: true displayZoomButtons: label: 'Display Zoom Buttons' description: 'If set to true, the chart will display the zoom buttons ("1d 5d 1m" etc).' type: 'boolean' inlineJs: true defaultHidden: true fill: label: 'Fill' description: 'A number from 0—100 (inclusive) specifying the alpha of the fill below each line in the line graph. 100 means 100% opaque, and 0 means no fill at all. The fill color is the same color as the line above it.' type: 'integer' inlineJs: true defaultHidden: true focusTarget: label: 'Focus Target' description: 'Determines whether mouse hover focuses on individual points, or is shared by all series. Defaults to category, unless Annotation editing is enabled, which forces "datum".' type: 'string' inlineJs: true defaultHidden: true default: 'category' options: datum: value: 'datum' category: value: 'category' legendPosition: label: 'Legend Position' description: 'Determines whether the legend is put on the same row as the zoom buttons, or a new row.' type: 'string' inlineJs: true defaultHidden: true options: sameRow: value: 'sameRow' newRow: value: 'newRow' max: label: 'Maximum' description: 'The maximum value to show on the Y-axis. If the maximum data point is less than this value, this setting will be ignored.' type: 'number' inlineJs: true defaultHidden: true min: label: 'Minimum' description: 'The minimum value to show on the Y-axis. If the minimum data point is less than this value, this setting will be ignored.' type: 'number' inlineJs: true defaultHidden: true scaleFormat: label: 'Scale Format' description: 'Number format to be used for the axis tick labels. Format reference: https://developers.google.com/chart/interactive/docs/customizing_axes#number-formats.' placeholder: 'Format' type: 'string' inlineJs: true defaultHidden: true scaleType: label: 'Scale Type' description: 'Sets the maximum and minimum values shown on the Y-axis. Reference: https://developers.google.com/chart/interactive/docs/gallery/annotationchart.' type: 'string' inlineJs: true defaultHidden: true options: maximized: value: 'maximized' fixed: value: 'fixed' allmaximized: value: 'allmaximized' allfixed: value: 'allfixed' thickness: label: 'Thickness' description: 'A number from 0—10 (inclusive) specifying the thickness of the lines, where 0 is the thinnest.' placeholder: 'Thickness' type: 'integer' inlineJs: true defaultHidden: true zoomStartTime: label: 'Zoom Start Time' description: 'Sets the initial start datetime of the selected zoom range. Should be provided as a JavaScript Date.' placeholder: 'Date Time' type: 'datetime' inlineJs: true defaultHidden: true zoomEndTime: label: 'Zoom End Time' description: 'Sets the initial end datetime of the selected zoom range. Should be provided as a JavaScript Date.' placeholder: 'Date Time' type: 'datetime' inlineJs: true defaultHidden: true order: 13 annotationEditing: label: 'Built-In Annotation Editing' description: 'Optional, but if enabled, allows users to create new annotations for points on the chart. Annotations are stored automatically within Cyclotron.' type: 'boolean' required: false default: false order: 13 annotationKey: label: 'Built-In Annotation Key' description: 'Provides a CyclotronData bucket key to be used for built-in annotation editing. This property is automatically initialized with a random UUID.' type: 'string' inlineJs: true required: false defaultHidden: true order: 14 events: label: 'Events' description: 'Optional event handlers for various events.' type: 'propertyset' required: false defaultHidden: true order: 15 properties: rangechange: label: 'Range Change Event' description: 'This event occurs when the user changes the range slider. The new endpoints are available as e.start and e.end.' type: 'editor' editorMode: 'javascript' required: false order: 1 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 20 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' order: 20 # Common options options: displayAnnotations: true # Undocumented "chart" options chart: focusTarget: 'category' sample: -> # Generate new Annotation Chart Widget { annotationKey: uuid.v4() } # Theme-specific options themes: dark: options: dbackgroundColor: '#222222' darkmetro: options: dbackgroundColor: '#202020' ### chart: name: 'chart' label: 'Chart' icon: 'fa-bar-chart-o' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for this Widget.' placeholder: 'Data Source name' type: 'string' required: true options: datasourceOptions order: 10 drilldownDataSource: label: 'Drilldown Data Source' description: 'The name of the Data Source providing drilldown data for this Widget.' placeholder: 'Data Source name' type: 'string' required: false defaultHidden: true options: datasourceOptions order: 11 highchart: label: 'Highchart Definition' description: 'Contains all the options for the chart, in the format expected by Highcharts. Any valid Highcharts properties can be set under this property and will be applied to the chart.' type: 'json' inlineJs: true required: true order: 12 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 13 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' order: 14 addShiftPoints: label: 'Add/Shift Points' description: 'If true, identifies new points on each data reload and appends them to the right side of the chart, shifting points off of the left side. This is ideal for rolling time-series charts with a fixed number of points. The default is false, which forces a complete redraw of all points.' type: 'boolean' default: false required: false order: 15 sample: highchart: series: [{ x: '' y: '' } ] xAxis: [{ type: 'linear' } ] yAxis: [{ title: text: 'Values' } ] themes: light: chart: style: fontFamily: '"Open Sans", sans-serif' drilldown: activeAxisLabelStyle: color: '#333' textDecoration: 'none' plotOptions: series: shadow: false marker: enabled: false states: hover: enabled: true bar: borderWidth: 0 column: borderWidth: 0 pie: borderWidth: 0 title: style: font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 labels: style: fontSize: '11px' title: style: fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null lineWidth: 0 tickWidth: 0 labels: style: fontSize: '11px' title: style: fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 symbolWidth: 40 gto: chart: style: fontFamily: '"Open Sans", sans-serif' plotOptions: series: shadow: false marker: enabled: false states: hover: enabled: true bar: borderWidth: 0 column: borderWidth: 0 pie: borderWidth: 0 title: style: font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 labels: style: fontSize: '11px' title: style: fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null lineWidth: 0 tickWidth: 0 labels: style: fontSize: '11px' title: style: fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 symbolWidth: 40 dark: colors: [ '#007D9D' #Blue '#82B93A' #Green '#E3AAD5' #Pink '#EBDC46' #Yellow '#AC5B41' #Red '#D1D1D0' #Offwhite '#B07288' #Purple ] chart: backgroundColor: null #'#333333' borderWidth: 0 borderRadius: 0 plotBackgroundColor: null plotShadow: false plotBorderWidth: 0 style: fontFamily: '"Open Sans", sans-serif' color: '#FFF' drilldown: activeAxisLabelStyle: color: '#999' textDecoration: 'none' activeDataLabelStyle: color: '#999' textDecoration: 'none' title: style: color: '#FFF' font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: color: '#FFF' font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 lineColor: '#999' tickColor: '#999' labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null gridLineColor: 'rgba(255, 255, 255, .1)' minorGridLineColor: 'rgba(255,255,255,0.07)' lineWidth: 0 tickWidth: 0 labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 itemStyle: color: '#CCC' itemHoverStyle: color: '#FFF' itemHiddenStyle: color: '#333' symbolWidth: 40 labels: style: color: '#CCC' tooltip: backgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, 'rgba(96, 96, 96, .8)'] [1, 'rgba(16, 16, 16, .8)'] ] borderWidth: 0 style: color: '#FFF' plotOptions: series: dataLabels: style: color: '#999' textShadow: false shadow: true marker: enabled: false states: hover: enabled: true bar: borderWidth: 0 column: borderWidth: 0 line: dataLabels: color: '#CCC' marker: lineColor: '#333' pie: borderWidth: 0 dataLabels: color: '#999' fontSize: '14px' spline: marker: lineColor: '#333' scatter: marker: lineColor: '#333' candlestick: lineColor: 'white' toolbar: itemStyle: color: '#CCC' navigation: buttonOptions: symbolStroke: '#DDDDDD' hoverSymbolStroke: '#FFFFFF' theme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#606060'] [0.6, '#333333'] ] stroke: '#000000' # scroll charts rangeSelector: buttonTheme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] stroke: '#000000' style: color: '#CCC' fontWeight: 'bold' states: hover: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#BBB'] [0.6, '#888'] ] stroke: '#000000' style: color: 'white' select: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.1, '#000'] [0.3, '#333'] ] stroke: '#000000' style: color: 'yellow' inputStyle: backgroundColor: '#333' color: 'silver' labelStyle: color: 'silver' navigator: handles: backgroundColor: '#666' borderColor: '#AAA' outlineColor: '#CCC' maskFill: 'rgba(16, 16, 16, 0.5)' series: color: '#7798BF' lineColor: '#A6C7ED' scrollbar: barBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] barBorderColor: '#CCC' buttonArrowColor: '#CCC' buttonBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] buttonBorderColor: '#CCC' rifleColor: '#FFF' trackBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, '#000'] [1, '#333'] ] trackBorderColor: '#666' dark2: colors: [ '#2095F0' #Blue '#FF9A13' #Orange '#FFFF13' #Yellow '#A61DF1' #Purple '#28F712' #Green '#FE131E' #Red '#D1D1D0' #Offwhite ] chart: backgroundColor: null #'#333333' borderWidth: 0 borderRadius: 0 plotBackgroundColor: null plotShadow: false plotBorderWidth: 0 style: fontFamily: '"Open Sans", sans-serif' color: '#FFF' drilldown: activeAxisLabelStyle: color: '#999' textDecoration: 'none' activeDataLabelStyle: color: '#999' textDecoration: 'none' title: style: color: '#FFF' font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: color: '#FFF' font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 lineColor: '#999' tickColor: '#999' labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null gridLineColor: 'rgba(255, 255, 255, .1)' minorGridLineColor: 'rgba(255,255,255,0.07)' lineWidth: 0 tickWidth: 0 labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 itemStyle: color: '#CCC' itemHoverStyle: color: '#FFF' itemHiddenStyle: color: '#333' symbolWidth: 40 labels: style: color: '#CCC' tooltip: backgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, 'rgba(96, 96, 96, .8)'] [1, 'rgba(16, 16, 16, .8)'] ] borderWidth: 0 style: color: '#FFF' plotOptions: series: shadow: true marker: enabled: false states: hover: enabled: true dataLabels: style: color: '#999' textShadow: false bar: borderWidth: 0 column: borderWidth: 0 line: dataLabels: color: '#CCC' marker: lineColor: '#333' pie: borderWidth: 0 dataLabels: color: '#999' fontSize: '14px' spline: marker: lineColor: '#333' scatter: marker: lineColor: '#333' candlestick: lineColor: 'white' toolbar: itemStyle: color: '#CCC' navigation: buttonOptions: symbolStroke: '#DDDDDD' hoverSymbolStroke: '#FFFFFF' theme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#606060'] [0.6, '#333333'] ] stroke: '#000000' # scroll charts rangeSelector: buttonTheme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] stroke: '#000000' style: color: '#CCC' fontWeight: 'bold' states: hover: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#BBB'] [0.6, '#888'] ] stroke: '#000000' style: color: 'white' select: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.1, '#000'] [0.3, '#333'] ] stroke: '#000000' style: color: 'yellow' inputStyle: backgroundColor: '#333' color: 'silver' labelStyle: color: 'silver' navigator: handles: backgroundColor: '#666' borderColor: '#AAA' outlineColor: '#CCC' maskFill: 'rgba(16, 16, 16, 0.5)' series: color: '#7798BF' lineColor: '#A6C7ED' scrollbar: barBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] barBorderColor: '#CCC' buttonArrowColor: '#CCC' buttonBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] buttonBorderColor: '#CCC' rifleColor: '#FFF' trackBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, '#000'] [1, '#333'] ] trackBorderColor: '#666' darkmetro: colors: [ '#007D9D' #Blue '#82B93A' #Green '#E3AAD5' #Pink '#EBDC46' #Yellow '#AC5B41' #Red '#D1D1D0' #Offwhite '#B07288' #Purple ] chart: backgroundColor: null #'#333333' borderWidth: 0 borderRadius: 0 plotBackgroundColor: null plotShadow: false plotBorderWidth: 0 style: fontFamily: '"Open Sans", sans-serif' color: '#FFF' drilldown: activeAxisLabelStyle: color: '#999' textDecoration: 'none' activeDataLabelStyle: color: '#999' textDecoration: 'none' title: style: color: '#FFF' font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: color: '#FFF' font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 lineColor: '#999' tickColor: '#999' labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null gridLineColor: 'rgba(255, 255, 255, .1)' minorGridLineColor: 'rgba(255,255,255,0.07)' lineWidth: 0 tickWidth: 0 labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 itemStyle: color: '#CCC' itemHoverStyle: color: '#FFF' itemHiddenStyle: color: '#333' symbolWidth: 40 labels: style: color: '#CCC' tooltip: backgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, 'rgba(96, 96, 96, .8)'] [1, 'rgba(16, 16, 16, .8)'] ] borderWidth: 0 style: color: '#FFF' plotOptions: series: dataLabels: style: color: '#999' textShadow: false shadow: true marker: enabled: false states: hover: enabled: true bar: borderWidth: 0 column: borderWidth: 0 line: dataLabels: color: '#CCC' marker: lineColor: '#333' pie: borderWidth: 0 dataLabels: color: '#999' fontSize: '14px' spline: marker: lineColor: '#333' scatter: marker: lineColor: '#333' candlestick: lineColor: 'white' toolbar: itemStyle: color: '#CCC' navigation: buttonOptions: symbolStroke: '#DDDDDD' hoverSymbolStroke: '#FFFFFF' theme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#606060'] [0.6, '#333333'] ] stroke: '#000000' # scroll charts rangeSelector: buttonTheme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] stroke: '#000000' style: color: '#CCC' fontWeight: 'bold' states: hover: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#BBB'] [0.6, '#888'] ] stroke: '#000000' style: color: 'white' select: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.1, '#000'] [0.3, '#333'] ] stroke: '#000000' style: color: 'yellow' inputStyle: backgroundColor: '#333' color: 'silver' labelStyle: color: 'silver' navigator: handles: backgroundColor: '#666' borderColor: '#AAA' outlineColor: '#CCC' maskFill: 'rgba(16, 16, 16, 0.5)' series: color: '#7798BF' lineColor: '#A6C7ED' scrollbar: barBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] barBorderColor: '#CCC' buttonArrowColor: '#CCC' buttonBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] buttonBorderColor: '#CCC' rifleColor: '#FFF' trackBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, '#000'] [1, '#333'] ] trackBorderColor: '#666' charcoal: colors: [ '#007D9D' #Blue '#82B93A' #Green '#E3AAD5' #Pink '#EBDC46' #Yellow '#AC5B41' #Red '#D1D1D0' #Offwhite '#B07288' #Purple ] chart: backgroundColor: null #'#333333' borderWidth: 0 borderRadius: 0 plotBackgroundColor: null plotShadow: false plotBorderWidth: 0 style: fontFamily: '"Open Sans", sans-serif' color: '#FFF' drilldown: activeAxisLabelStyle: color: '#999' textDecoration: 'none' activeDataLabelStyle: color: '#999' textDecoration: 'none' title: style: color: '#FFF' font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: color: '#FFF' font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 lineColor: '#999' tickColor: '#999' labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null gridLineColor: 'rgba(255, 255, 255, .1)' minorGridLineColor: 'rgba(255,255,255,0.07)' lineWidth: 0 tickWidth: 0 labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 itemStyle: color: '#CCC' itemHoverStyle: color: '#FFF' itemHiddenStyle: color: '#333' symbolWidth: 40 labels: style: color: '#CCC' tooltip: backgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, 'rgba(96, 96, 96, .8)'] [1, 'rgba(16, 16, 16, .8)'] ] borderWidth: 0 style: color: '#FFF' plotOptions: series: dataLabels: style: color: '#999' textShadow: false shadow: false marker: enabled: false states: hover: enabled: true bar: borderWidth: 0 column: borderWidth: 0 line: dataLabels: color: '#CCC' marker: lineColor: '#333' pie: borderWidth: 0 dataLabels: color: '#999' fontSize: '14px' spline: marker: lineColor: '#333' scatter: marker: lineColor: '#333' candlestick: lineColor: 'white' toolbar: itemStyle: color: '#CCC' navigation: buttonOptions: symbolStroke: '#DDDDDD' hoverSymbolStroke: '#FFFFFF' theme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#606060'] [0.6, '#333333'] ] stroke: '#000000' # scroll charts rangeSelector: buttonTheme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] stroke: '#000000' style: color: '#CCC' fontWeight: 'bold' states: hover: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#BBB'] [0.6, '#888'] ] stroke: '#000000' style: color: 'white' select: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.1, '#000'] [0.3, '#333'] ] stroke: '#000000' style: color: 'yellow' inputStyle: backgroundColor: '#333' color: 'silver' labelStyle: color: 'silver' navigator: handles: backgroundColor: '#666' borderColor: '#AAA' outlineColor: '#CCC' maskFill: 'rgba(16, 16, 16, 0.5)' series: color: '#7798BF' lineColor: '#A6C7ED' scrollbar: barBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] barBorderColor: '#CCC' buttonArrowColor: '#CCC' buttonBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] buttonBorderColor: '#CCC' rifleColor: '#FFF' trackBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, '#000'] [1, '#333'] ] trackBorderColor: '#666' ### gchart: name: 'gchart' label: 'Google Charts' icon: 'fa-rocket' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing table-like data for this Widget.' placeholder: 'Data Source name' type: 'string' required: true options: datasourceOptions order: 10 chartType: label: 'Chart Type' description: 'Type of the chart.' type: 'string' required: true options: AnnotatedTimeLine: value: 'AnnotatedTimeLine' AreaChart: value: 'AreaChart' BarChart: value: 'BarChart' BubbleChart: value: 'BubbleChart' CandlestickChart: value: 'CandlestickChart' ColumnChart: value: 'ColumnChart' ComboChart: value: 'ComboChart' Gauge: value: 'Gauge' GeoChart: value: 'GeoChart' IntensityMap: value: 'IntensityMap' Map: value: 'Map' Histogram: value: 'Histogram' LineChart: value: 'LineChart' OrgChart: value: 'OrgChart' PieChart: value: 'PieChart' ScatterChart: value: 'ScatterChart' SteppedAreaChart: value: 'SteppedAreaChart' Table: value: 'Table' Timeline: value: 'Timeline' TreeMap: value: 'TreeMap' order: 11 options: label: 'Options' description: 'JSON object with configuration options for the chart.' type: 'editor' editorMode: 'javascript' required: false order: 12 columns: label: 'Columns' singleLabel: 'column' description: 'Array of columns of the table-like dataset. If not provided, the column labels will be inferred from the keys of the first dataset object. Note that this property must be used if some columns contain dates, times or datetimes or if the column role should differ from "data" (e.g. for annotations; see https://developers.google.com/chart/interactive/docs/roles).' type: 'propertyset[]' inlineJs: true required: false properties: name: label: 'Name' description: 'Indicates the name of the data source field to use for this column.' type: 'string' inlineJs: true required: true order: 1 type: label: 'Type' description: 'Type of the column values. If omitted, "string" will be assigned.' type: 'string' options: string: value: 'string' number: value: 'number' boolean: value: 'boolean' date: value: 'date' datetime: value: 'datetime' timeofday: value: 'timeofday' order: 2 role: label: 'Role' description: 'Optional role of the column. If omitted, "data" will be assigned. Note that columns with role "annotation" must immediately follow the series column that should be annotated, and columns with role "annotationText" must follow the annotated column.' type: 'string' options: annotation: value: 'annotation' annotationText: value: 'annotationText' order: 3 order: 13 formatters: label: 'Formatters' singleLabel: 'formatter' description: 'Optional JavaScript functions that will be applied to all the values of the specified datasource columns.' type: 'propertyset[]' properties: columnName: label: 'Column Name' description: 'Indicates the name of the datasource column' type: 'string' inlineJs: true order: 1 formatter: label: 'Formatter' description: 'The function must take a single value as argument and return the new value.' type: 'editor' editorMode: 'javascript' required: false order: 2 order: 14 clock: name: 'clock' label: 'Clock' icon: 'fa-clock-o' properties: format: label: 'Format' description: 'Enter time format of your choice. "http://momentjs.com/docs/#/displaying/format/" can help in choosing time formats' type: 'string' default: 'dddd, MMMM Do YYYY, h:mm:ss a' required: false order: 10 timezone: label: 'Time Zone' description: 'Enter time zone of your choice. "http://momentjs.com/timezone/" can help in choosing time zone' required: false type: 'string' order: 11 deckgl: name: 'deckgl' label: 'Deck.gl' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for the layers.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions order: 10 ###mapboxApiAccessToken: label: 'Mapbox Token' description: '' type: 'string' required: false order: 11 mapStyle: label: 'Map Style' description: '' type: 'string' required: false order: 12### viewState: label: 'View State' description: 'viewState property' type: 'propertyset' properties: longitude: label: 'Longitude' description: '' type: 'string' required: true order: 1 latitude: label: 'Latitude' description: '' type: 'string' required: true order: 2 zoom: label: 'Zoom' description: 'Default is 0' type: 'integer' required: false default: 0 order: 3 bearing: label: 'Bearing' description: '' type: 'integer' required: false defaultHidden: true order: 4 pitch: label: 'Pitch' description: '' type: 'integer' required: false defaultHidden: true order: 5 order: 13 additionalDeckProps: label: 'Additional Deck Properties' description: 'Additional supported Deck properties. See https://deck.gl/#/documentation/deckgl-api-reference/deck' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 14 layers: label: 'Layers' singleLabel: 'layer' description: '' type: 'propertyset[]' properties: type: label: 'Type' description: 'The type of layer that will be added to the deck.' type: 'string' required: true options: ArcLayer: value: 'ArcLayer' BitmapLayer: value: 'BitmapLayer' ColumnLayer: value: 'ColumnLayer' GeoJsonLayer: value: 'GeoJsonLayer' GridCellLayer: value: 'GridCellLayer' IconLayer: value: 'IconLayer' LineLayer: value: 'LineLayer' PathLayer: value: 'PathLayer' PointCloudLayer: value: 'PointCloudLayer' PolygonLayer: value: 'PolygonLayer' ScatterplotLayer: value: 'ScatterplotLayer' SolidPolygonLayer: value: 'SolidPolygonLayer' TextLayer: value: 'TextLayer' order: 1 configProperties: label: 'Configuration Properties' description: 'See https://deck.gl/#/documentation/deckgl-api-reference/layers/overview for supported properties. Note that they may vary depending on the layer type.' type: 'editor' editorMode: 'javascript' required: false order: 2 useDataSource: label: 'Use Data Source' description: 'Use the Data Source to provide data for this layer. The data will be used for the first layer found with this property set to true.' type: 'boolean' required: false default: false order: 3 order: 14 header: name: 'header' label: 'Header' icon: 'fa-header' properties: headerTitle: label: 'Header Title' description: 'Contains properties for displaying a title in the header.' type: 'propertyset' order: 10 properties: showTitle: label: 'Show Title' description: 'Determines whether a title will be shown. If the Widget has a Title, it will be shown, otherwise it defaults to the Dashboard\'s Display Name or Name.' type: 'boolean' default: true required: false inlineJs: true order: 1 showPageName: label: 'Show Page Name' description: 'Determines whether the current page name will be shown as part of the title.' type: 'boolean' default: true required: false inlineJs: true order: 2 pageNameSeparator: label: 'Page Name Separator' description: 'Configures a string to use to separate the Dashboard name from the Page name. Defaults to a space.' type: 'string' required: false default: '' inlineJs: true defaultHidden: true order: 3 titleSize: label: 'Title Size' description: 'Sets the font size for the header title (if displayed). Any valid CSS height is allowed.' type: 'string' required: false inlineJs: true order: 5 logoUrl: label: 'Logo URL' description: 'Contains a URL to a dashboard logo to display before the title. Data URLs can be used.' type: 'string' required: false inlineJs: true order: 10 logoSize: label: 'Logo Size' description: 'Sets the height for the header logo (if displayed). The logo will be scaled without changing the aspect ratio. Any valid CSS height is allowed.' type: 'string' required: false inlineJs: true order: 11 link: label: 'Link' description: 'If set, makes the Logo and Title a link to this URL.' type: 'string' required: false inlineJs: true order: 20 parameters: label: 'Parameters' description: 'Contains properties for displaying Dashboard Parameters in the header.' type: 'propertyset' order: 20 properties: showParameters: label: 'Show Parameters' description: 'Determines whether Parameters will be shown.' type: 'boolean' default: false required: false inlineJs: true order: 1 showUpdateButton: label: 'Show Update Button' description: 'If true, an "Update" button will be displayed after the Parameters. The updateEvent property must be used to apply an action to the button click event, else nothing will happen.' type: 'boolean' default: false required: false order: 2 updateButtonLabel: label: 'Update Button Label' description: 'Customizes the label for the Update button, if shown.' type: 'string' default: 'Update' defaultHidden: true required: false order: 2 updateEvent: label: 'Update Button Click Event' description: 'This event occurs when the Update button is clicked, if shown.' type: 'editor' editorMode: 'javascript' required: false order: 10 parametersIncluded: label: 'Included Parameters' description: 'Optionally specifies an array of Parameter names, limiting the Header to only displaying the specified Parameters. This does not override the editInHeader property of each Parameter, which needs to be set true to appear in the Header.' type: 'string[]' required: false defaultHidden: true order: 11 customHtml: label: 'HTML Content' description: 'Provides additional HTML content to be displayed in the header. This can be used to customize the header display.' type: 'editor' editorMode: 'html' required: false inlineJs: true order: 30 html: name: 'html' label: 'HTML' icon: 'fa-html5' properties: dataSource: label: 'Data Source' description: 'Optional; the name of the Data Source providing data for this Widget. If set, the `html` property will be used as a repeater and rendered once for each row.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions order: 10 html: label: 'HTML' description: 'Contains HTML markup to be displayed. If dataSource is set, this HTML will be repeated for each row in the result.' type: 'editor' editorMode: 'html' required: false default: '' order: 11 preHtml: label: 'Pre-HTML' description: 'Optional, contains HTML markup which is displayed before the main body of HTML.' type: 'editor' editorMode: 'html' required: false default: '' order: 12 postHtml: label: 'Post-HTML' description: 'Optional, contains HTML markup which is displayed after the main body of HTML.' type: 'editor' editorMode: 'html' required: false default: '' order: 13 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 14 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' placeholder: 'Column name' type: 'string[]' inlineJs: true required: false order: 15 iframe: name: 'iframe' label: 'iFrame' icon: 'fa-desktop' properties: url: label: 'Url' description: 'Specifies the URL to be loaded within the Widget.' type: 'string' placeholder: 'Url' required: true default: 'http://www.expedia.com' order: 10 refresh: label: 'Refresh' description: 'Optional number of seconds; enables reloading the iframe contents periodically every N seconds.' placeholder: 'Seconds' type: 'integer' required: false order: 11 image: name: 'image' label: 'Image' icon: 'fa-image-o' properties: images: label: 'Images' singleLabel: 'Image' description: 'One or more Images to display in this widget.' type: 'propertyset[]' required: true default: [] order: 10 properties: url: label: 'URL' description: 'URL to the image to be displayed.' placeholder: 'Url' inlineJs: true required: true type: 'string' order: 1 link: label: 'Link' description: 'Optional, specifies a URL that will be opened if the image is clicked on.' placeholder: 'URL' type: 'url' inlineJs: true required: false order: 13 tooltip: label: 'Tooltip' description: 'Sets the tooltip of the image.' placeholder: 'Tooltip' type: 'string' inlineJs: true required: false defaultHidden: true order: 2 backgroundSize: label: 'Background-Size' description: 'Specifies the CSS property background-size, which determines how the image is fit into the Widget.' type: 'string' inlineJs: true required: false defaultHidden: true options: auto: value: 'auto' contain: value: 'contain' cover: value: 'cover' '100%': value: '100%' order: 3 backgroundPosition: label: 'Background Position' description: 'Specifies the CSS property background-position, which determines where the image is positioned in the Widget.' type: 'string' inlineJs: true required: false default: 'center' defaultHidden: true options: center: value: 'center' top: value: 'top' bottom: value: 'bottom' left: value: 'left' right: value: 'right' order: 4 backgroundColor: label: 'Background Color' description: 'Optionally specifies the CSS property background-color, which is drawn behind this image. It may appear if the image does not cover the Widget, or if the image is not opaque.' type: 'string' inlineJs: true required: false defaultHidden: true order: 5 backgroundRepeat: label: 'Background Repeat' description: 'Optionally specifies the CSS property background-repeat, which determiens if or how the image is repeated within the Widget.' type: 'string' inlineJs: true required: false default: 'no-repeat' defaultHidden: true options: 'no-repeat': value: 'no-repeat' 'repeat': value: 'repeat' 'repeat-x': value: 'repeat-x' 'repeat-y': value: 'repeat-y' 'space': value: 'space' 'round': value: 'round' order: 6 filters: label: 'Filters' description: 'Optionally applies one or more CSS filters to the image. If provided, it should be a string containing one or more filters, separated by spaces.' type: 'string' inlineJs: true required: false defaultHidden: true order: 7 duration: label: 'Auto-Rotate Duration' description: 'Optional number of seconds; enables rotating among a set of images periodically.' placeholder: 'Seconds' type: 'integer' default: 0 required: false order: 11 javascript: name: 'javascript' label: 'JavaScript' icon: 'fa-cogs' properties: dataSource: label: 'Data Source' description: 'Optional; the name of the Data Source providing data for this Widget. If set, the data source will be called and the result will be passed to the JavaScript function.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions order: 10 functionName: label: 'Function Name' description: 'JavaScript function name used to create a controller instance. Supports namespaces/drilldown using periods, e.g. Cyclotron.functions.scatterPlot' placeholder: 'Function Name' type: 'string' required: true order: 11 refresh: label: 'Refresh' description: 'Optional; enables re-invoking the javascript object periodically every N seconds.' placeholder: 'Seconds' type: 'integer' required: false order: 12 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 13 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' placeholder: 'Column name' type: 'string[]' inlineJs: true required: false order: 14 linkedWidget: name: 'linkedWidget' label: 'Linked Widget' icon: 'fa-link' properties: linkedWidget: label: 'Linked Widget' description: 'Selects another Widget in this Dashboard to link.' type: 'string' required: true options: linkedWidgetOptions order: 10 number: name: 'number' label: 'Number' icon: 'fa-cog' properties: dataSource: label: 'Data Source' description: 'Optional, but required to use data expressions e.g. "#{columnName}". The name of the Data Source providing data for this Widget.' placeholder: 'Data Source Name' type: 'string' required: false options: datasourceOptions order: 10 numbers: label: 'Numbers' singleLabel: 'number' description: 'One or more Numbers to display in this widget.' type: 'propertyset[]' required: true default: [] order: 11 properties: number: label: 'Number' description: 'Number value or expression.' placeholder: 'Value' inlineJs: true required: false type: 'string' order: 1 prefix: label: 'Prefix' description: 'Optional; specifies a prefix to append to the number.' placeholder: 'Prefix' type: 'string' inlineJs: true order: 2 suffix: label: 'Suffix' description: 'Optional; specifies a suffix to append to the number.' placeholder: 'Suffix' type: 'string' inlineJs: true order: 3 color: label: 'Color' description: 'Sets the color of the number.' placeholder: 'Color' type: 'string' inlineJs: true required: false defaultHidden: true order: 4 tooltip: label: 'Tooltip' description: 'Sets the tooltip of the number.' placeholder: 'Tooltip' type: 'string' inlineJs: true required: false defaultHidden: true order: 5 icon: label: 'Icon' description: 'Optional Font Awesome icon class to be displayed with the number.' placeholder: 'Icon Class' inlineJs: true type: 'string' defaultHidden: true order: 6 iconColor: label: 'Icon Color' description: 'Optionally specifies a color for the icon if the icon property is also set. The value can be a named color (e.g. "red"), a hex color (e.g. "#AA0088") or a data source column/inline javascript (e.g. "#{statusColor}").' type: 'string' inlineJs: true defaultHidden: true order: 7 iconTooltip: label: 'IconTooltip' description: 'Sets the tooltip of the icon.' placeholder: 'Icon Tooltip' type: 'string' inlineJs: true required: false defaultHidden: true order: 8 onClick: label: 'Click Event' description: 'This event occurs when the user clicks on the number. If this property is set with a JavaScript function, the function will be called as an event handler.' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 9 orientation: label: 'Orientation' description: 'Controls the direction in which the numbers are arranged.' type: 'string' required: false default: 'vertical' options: vertical: value: 'vertical' horizontal: value: 'horizontal' order: 12 autoSize: label: 'Auto-Size Numbers' description: 'If true, up to 4 numbers will be automatically sized-to-fit in the Widget. If false, or if there are more than four numbers, all numbers will be listed sequentially.' type: 'boolean' required: false default: true order: 13 link: label: 'Link' description: 'Optional, specifies a URL that will be displayed at the bottom of the widget as a link.' placeholder: 'URL' type: 'url' required: false order: 14 filters: label: 'Filters' description: "Optional, but if provided, specifies name-value pairs used to filter the data source's result set. This has no effect if the dataSource property is not set.\nOnly the first row of the data source is used to get data, so this property can be used to narrow down on the correct row" type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 15 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.\nOnly the first row of the data source is used to get data, so this property can be used to sort the data and ensure the correct row comes first.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' order: 16 openLayersMap: name: 'openLayersMap' label: 'OpenLayers Map' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for the overlays.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions order: 10 center: label: 'Center' description: 'X and Y coordinates to center the map on' type: 'propertyset' required: true properties: x: label: 'X' type: 'string' required: true order: 1 y: label: 'Y' type: 'string' required: true order: 2 order: 11 zoom: label: 'Zoom' description: 'Zoom level (0 is zoomed out)' type: 'integer' required: true order: 12 layers: label: 'Layers' singleLabel: 'layer' description: 'An array of layers that will be added to the map. Default is a single OpenStreetMap (OSM) layer.' type: 'propertyset[]' inlineJs: true properties: type: label: 'Type' description: 'The type of layer that will be added to the map. Specifying a source is mandatory except for VectorTile layers. Heatmap layer also requires Weight to be specified. If no type nor source are specified, Tile and OSM are used.' type: 'string' required: false default: 'Tile' options: image: value: 'Image' tile: value: 'Tile' heatmap: value: 'Heatmap' vector: value: 'Vector' vectortile: value: 'VectorTile' order: 1 source: label: 'Source' description: 'Source for the layer. Please refer to the help page if you do not know which one you need. Note that depending on the layer type (Image, Tile, Heatmap or VectorTile) only a subset of these sources is accepted.' type: 'propertyset' properties: name: label: 'Name' type: 'string' required: false default: 'OSM' options: BingMaps: value: 'BingMaps' CartoDB: value: 'CartoDB' Cluster: value: 'Cluster' ImageArcGISRest: value: 'ImageArcGISRest' ImageCanvas: value: 'ImageCanvas' ImageMapGuide: value: 'ImageMapGuide' ImageStatic: value: 'ImageStatic' ImageWMS: value: 'ImageWMS' OSM: value: 'OSM' Raster: value: 'Raster' Stamen: value: 'Stamen' TileArcGISRest: value: 'TileArcGISRest' TileDebug: value: 'TileDebug' TileJSON: value: 'TileJSON' TileUTFGrid: value: 'TileUTFGrid' TileWMS: value: 'TileWMS' Vector: value: 'Vector' VectorTile: value: 'VectorTile' WMTS: value: 'WMTS' XYZ: value: 'XYZ' Zoomify: value: 'Zoomify' order: 1 configuration: label: 'Configuration' description: 'Configuration object. Please refer to the widget help page to know how to configure each source.' type: 'editor' editorMode: 'javascript' required: false order: 2 order: 2 weight: label: 'Weight (for heatmap)' description: '' type: 'string' required: false order: 3 styleFunction: label: 'Style function' description: 'Style function (for vector layers, see https://openlayers.org/en/v4.6.5/apidoc/ol.html#.StyleFunction). You can specify a style function to be applied when selecting a feature by defining it as "Cyclotron.featureSelectStyleFunction" in the Scripts section, otherwise the default select style will be applied.' type: 'editor' editorMode: 'javascript' required: false order: 4 order: 13 overlayGroups: label: 'Overlay Groups' singleLabel: 'group' description: 'Groups of overlays that will be added to the map, i.e., elements that will be displayed over the map and attached to a given position. Each group of overlays can have one overlay selected at a time.' type: 'propertyset[]' inlineJs: true properties: name: label: 'Name' type: 'string' required: true order: 1 initiallySelected: label: 'Overlay Initially Selected' description: 'Name of the overlay that will be assigned the CSS class on selection when the page is loaded. If not provided, all overlays will have the regular CSS class until one is clicked. Note that to use this field you must provide names for the overlays.' type: 'string' required: false order: 2 overlays: label: 'Overlays' singleLabel: 'overlay' description: '' type: 'propertyset[]' inlineJs: true required: true properties: name: label: 'Name' description: 'Unique identifier for the overlay' type: 'string' required: false order: 1 cssClass: label: 'CSS Class' description: 'CSS class name (defined beforehand in the Styles section of the dashboard) for the overlay' type: 'string' required: true order: 2 cssClassSelected: label: 'CSS Class On Selection' description: 'Optional CSS class name (defined beforehand in the Styles section of the dashboard) for the selected overlay' type: 'string' required: false order: 3 position: label: 'Position' description: 'X and Y coordinates of the location where the overlay will be attached' type: 'propertyset' properties: x: label: 'X' type: 'string' required: false order: 1 y: label: 'Y' type: 'string' required: false order: 2 order: 4 positioning: label: 'Positioning' description: 'Where the overlay is placed with respect to Position. Default is top-left.' type: 'string' required: false default: 'top-left' options: bottomLeft: value: 'bottom-left' bottomCenter: value: 'bottom-center' bottomRight: value: 'bottom-right' centerLeft: value: 'center-left' centerCenter: value: 'center-center' centerRight: value: 'center-right' topLeft: value: 'top-left' topCenter: value: 'top-center' topRight: value: 'top-right' order: 5 template: label: 'Template' description: 'HTML template for overlay content.' type: 'editor' editorMode: 'html' required: false default: '' order: 6 order: 3 order: 15 controls: label: 'Controls' singleLabel: 'control' description: 'An array of controls that will be added to the map.' type: 'propertyset[]' inlineJs: true defaultHidden: true default: [] properties: control: label: 'Control' type: 'string' required: false options: Attribution: value: 'Attribution' MousePosition: value: 'MousePosition' OverviewMap: value: 'OverviewMap' ScaleLine: value: 'ScaleLine' Zoom: value: 'Zoom' ZoomSlider: value: 'ZoomSlider' ZoomToExtent: value: 'ZoomToExtent' order: 1 order: 16 dataSourceMapping: label: 'DataSource Mapping' description: 'Overlay properties must be mapped to datasource fields. The datasource is required to have at least fields for CSS class and the list of overlays.' type: 'propertyset' defaultHidden: true properties: identifierField: label: 'Identifier Field' description: 'Datasource field with a unique identifier for the overlay group. If it is not specified and the datasource provides more that one object (i.e. overlay group), each group will be assigned a random ID.' type: 'string' required: false order: 1 initiallySelectedField: label: 'Overlay Initially Selected Field' description: 'Optional datasource field with the ID of the overlay that will be assigned the CSS class on selection when the page is loaded. If not provided, all overlays will have the regular CSS class until one is clicked.' type: 'string' required: false defaultHidden: true order: 2 overlayListField: label: 'Overlay List Field' description: 'Datasource field containing the list of overlays for the group' type: 'string' required: true order: 3 cssClassField: label: 'CSS Class Field' description: 'Datasource field with the style for each overlay in the group as name of a CSS class defined in the Styles section of the editor.' type: 'string' required: true order: 4 cssClassOnSelectionField: label: 'CSS Class On Selection Field' description: 'Optional datasource field with the CSS class for each overlay after it has been clicked. It must be the name of a CSS class defined in the Styles section of the editor.' type: 'string' required: false defaultHidden: true order: 5 overlayIdField: label: 'Overlay Identifier Field' description: 'Datasource field with a unique identifier for each overlay in the group list. If it is missing, a random ID will be generated.' type: 'string' required: false order: 6 positionField: label: 'Position Field' description: 'Datasource field with an array of coordinates (i.e. [x_coord, y_coord]) for each overlay in the group list. Alternatively, single fields for X and Y can be specified.' type: 'string' required: false order: 7 xField: label: 'X Coordinate Field' description: 'Datasource field with X coordinate for each overlay in the group list.' type: 'string' required: false defaultHidden: true order: 8 yField: label: 'Y Coordinate Field' description: 'Datasource field with Y coordinate for each overlay in the group list.' type: 'string' required: false defaultHidden: true order: 9 positioningField: label: 'Positioning Field' description: 'Datasource field with the positioning (e.g. "center-center") of each overlay.' type: 'string' required: false defaultHidden: true order: 10 templateField: label: 'Template Field' description: 'Datasource field with the HTML template for the content of each overlay.' type: 'string' required: false defaultHidden: true order: 11 order: 14 specificEvents: label: 'Specific Events' singleLabel: 'param-event' description: 'Array of parameters (defined beforehand in the Parameters section of the dashboard) and widget events that can trigger their change.' type: 'propertyset[]' inlineJs: true defaultHidden: true default: [] properties: paramName: label: 'Parameter Name' type: 'string' required: true order: 1 event: label: 'Event' type: 'string' required: true options: clickOnOverlay: value: 'clickOnOverlay' clickOnWMSLayer: value: 'clickOnWMSLayer' selectVectorFeature: value: 'selectVectorFeature' order: 2 section: label: 'Section' description: 'Name of the overlay group that triggers the event, for the event "clickOnOverlay". Name of the WMS layer that triggers the event (e.g. "topp:states"), for the event "clickOnWMSLayer". For other events, you can leave this option empty. For the event "selectVectorFeature", you can set the index (zero-based) of the layer the features should be selected from, so that features of the specified layer will be stored in the parameter, otherwise features of any layer will be stored in the same parameter. Some widgets (e.g. slider) have one section only, i.e. the whole widget triggers the event, while others may have some sections that trigger the same kind of event (e.g. in OpenLayers maps, any overlay group can trigger clickOnOverlay event).' type: 'string' required: false order: 3 order: 17 projection: label: 'Projection' description: 'Projection. Default is EPSG:3857 (Spherical Mercator).' type: 'string' required: false default: 'EPSG:3857' options: 'EPSG:3857': value: 'EPSG:3857' 'EPSG:4326': value: 'EPSG:4326' order: 18 qrcode: name: 'qrcode' label: 'QRcode' icon: 'fa-cogs' properties: text: label: 'Text' description: 'Text content of the generated QR code.' placeholder: 'QR Code Contents' type: 'string' required: false order: 10 maxSize: label: 'Max Size' description: 'Maximum height/width of the QR code.' type: 'integer' required: false order: 11 useUrl: label: 'Use URL' description: 'Overrides the text property and generates a QR code with the current Dashboard\'s URL.' type: 'boolean' default: false required: false order: 12 dataSource: label: 'Data Source' description: 'Optional; specifies the name of a Dashboard data source. If set, the data source will be called and the result will be available for the QR code generation.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions defaultHidden: true order: 13 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false defaultHidden: true order: 14 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' placeholder: 'Column name' type: 'string[]' inlineJs: true required: false defaultHidden: true order: 15 colorDark: label: 'Dark Color' description: 'CSS color name or hex color code, used to draw the dark portions of the QR code.' placeholder: 'CSS color or hex color code' type: 'string' default: '#000000' required: false defaultHidden: true order: 16 colorLight: label: 'Light Color' description: 'CSS color name or hex color code, used to draw the dark portions of the QR code.' placeholder: 'CSS color or hex color code' type: 'string' default: '#ffffff' required: false defaultHidden: true order: 17 sample: text: 'hello' slider: name: 'slider' label: 'Slider' icon: 'fa-bar-chart-o' properties: minValue: label: 'Minimum date-time' description: 'Starting value of the slider' type: 'string' placeholder: 'YYYY-MM-DD HH:mm' required: true order: 10 maxValue: label: 'Maximum date-time' description: 'Ending value of the slider' type: 'string' placeholder: 'YYYY-MM-DD HH:mm' required: true order: 11 momentFormat: label: 'Date-time Format' description: 'Any valid moment() format. Default is YYYY-MM-DD HH:mm.' type: 'string' default: 'YYYY-MM-DD HH:mm' required: false order: 12 step: label: 'Step' description: 'Number of time units (e.g. days) between slider values (default is 1)' type: 'integer' required: false default: 1 order: 13 direction: label: 'Direction' description: 'Left-to-right or right-to-left. Default is left-to-right.' type: 'string' required: false defaultHidden: true default: 'ltr' options: ltr: value: 'ltr' rtl: value: 'rtl' order: 14 orientation: label: 'Orientation' description: 'Horizontal or vertical. Default is horizontal.' type: 'string' required: false defaultHidden: true default: 'horizontal' options: horizontal: value: 'horizontal' vertical: value: 'vertical' order: 15 player: label: 'Player' description: 'Play/pause button for automatic sliding' type: 'propertyset' properties: showPlayer: label: 'Show Player' description: 'Show player. Default is false.' type: 'boolean' required: false default: false order: 1 interval: label: 'Interval' description: 'Seconds between each sliding. Default is 1.' type: 'integer' required: false default: 1 order: 2 startOnPageReady: label: 'Start On Page Ready' description: 'Start the player automatically when the page is loaded' type: 'boolean' required: false default: false order: 3 order: 16 timeUnit: label: 'Time Unit' description: 'Each slider value corresponds to a minute, hour, day or month. Default is days.' type: 'string' required: false defaultHidden: true default: 'days' options: minutes: value: 'minutes' hours: value: 'hours' days: value: 'days' months: value: 'months' order: 17 pips: label: 'Pips' description: 'Scale/points shown near the slider' type: 'propertyset' properties: mode: label: 'Mode' description: 'Determines where to place pips.' type: 'string' required: false default: 'steps' options: range: value: 'range' steps: value: 'steps' positions: value: 'positions' count: value: 'count' values: value: 'values' order: 1 values: label: 'Values' description: 'Additional options for Positions, Count and Values mode. For Count mode provide an integer. For Positions and Values mode provide comma-separated integers.' type: 'string' required: false order: 2 stepped: label: 'Stepped' description: 'Match pips with slider values (default is false)' required: false default: false type: 'boolean' order: 3 density: label: 'Density' description: 'Number of pips in one percent of the slider range (default is 1)' type: 'integer' required: false default: 1 order: 4 format: label: 'Format' description: 'Show pip values in the same format as slider format (default is true)' type: 'boolean' required: false default: true order: 5 order: 18 tooltips: label: 'Tooltips' description: 'Show tooltips (default is false)' type: 'boolean' required: false defaultHidden: true default: false order: 19 twoHandles: label: 'Show Two Handles' description: 'Show two handles instead of one (default is false). In this case automatic sliding cannot be used. The handles will be placed at the first and last steps unless you specify a different position with Initial Handle Position.' type: 'boolean' required: false defaultHidden: true default: false order: 20 handlePosition: label: 'Initial Handle Position' description: 'Initial position of the handle, as a date-time in the same format used for Minimum and Maximum date-time. If the slider has two handles, enter two comma-separated date-times. Inline JavaScript can also be used, e.g. "${Cyclotron.parameters.handlePos}". By default the handle(s) will be positioned at the first (and last) value.' type: 'string' required: false defaultHidden: true order: 21 specificEvents: label: 'Specific Events' singleLabel: 'param-event' description: 'Array of parameters (defined beforehand in the Parameters section of the dashboard) and widget events that can trigger their change.' type: 'propertyset[]' inlineJs: true defaultHidden: true default: [] properties: paramName: label: 'Parameter Name' type: 'string' required: true order: 1 event: label: 'Event' type: 'string' required: true options: dateTimeChange: value: 'dateTimeChange' order: 2 section: label: 'Section' description: 'Specify which handle generates this event. If the slider has only one handle, you can leave this option empty.' type: 'string' default: 'first' required: false options: firstHandle: value: 'first' secondHandle: value: 'second' order: 3 order: 22 stoplight: name: 'stoplight' label: 'Stoplight' icon: 'fa-cog' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for this Widget.' placeholder: 'Data Source Name' type: 'string' required: false options: datasourceOptions order: 10 rules: label: 'Rules' description: 'Contains rule expressions for the different states of the Stoplight. The rules will be evaluated from red to green, and only the first rule that returns true will be enabled' type: 'propertyset' required: true order: 11 properties: green: label: 'Green' description: 'The rule expression evaluated to determine if the green light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.' type: 'string' placeholder: 'Rule Expression' inlineJs: true order: 3 yellow: label: 'Yellow' description: 'The rule expression evaluated to determine if the yellow light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.' type: 'string' placeholder: 'Rule Expression' inlineJs: true order: 2 red: label: 'Red' description: 'The rule expression evaluated to determine if the red light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.' type: 'string' placeholder: 'Rule Expression' inlineJs: true order: 1 tooltip: label: 'Tooltip' description: 'Sets the tooltip of the stoplight.' placeholder: 'Tooltip' type: 'string' inlineJs: true required: false defaultHidden: true order: 12 filters: label: 'Filters' description: "Optional, but if provided, specifies name-value pairs used to filter the data source's result set. This has no effect if the dataSource property is not set.\nOnly the first row of the data source is used to get data, so this property can be used to narrow down on the correct row" type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 15 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.\nOnly the first row of the data source is used to get data, so this property can be used to sort the data and ensure the correct row comes first.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' order: 16 table: name: 'table' label: 'Table' icon: 'fa-table' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for this Widget.' placeholder: 'Data Source name' type: 'string' required: true options: datasourceOptions order: 10 columns: label: 'Columns' singleLabel: 'column' description: 'Specifies the columns to display in the table, and their properties. If omitted, the columns will be automatically determined, either using a list of fields provided by the data source, or by looking at the first row.' type: 'propertyset[]' inlineJs: true properties: name: label: 'Name' description: 'Indicates the name of the data source field to use for this column.' type: 'string' inlineJs: true order: 1 label: label: 'Label' description: 'If provided, sets the header text for the column. If omitted, the name will be used. "#value" can be used to reference the "name" property of the column.' type: 'string' inlineJs: true order: 2 text: label: 'Text' description: 'Overrides the text in the cell using this value as an expression.' type: 'string' inlineJs: true defaultHidden: true order: 3 tooltip: label: 'Tooltip' description: 'Optionally specifies a tooltip to display for each cell in the column.' type: 'string' inlineJs: true defaultHidden: true headerTooltip: label: 'Header Tooltip' description: 'Optionally specifies a tooltip to display for the column header. "#value" can be used to reference the "name" property of the column.' type: 'string' inlineJs: true defaultHidden: true onClick: label: 'Click Event' description: 'This event occurs when the user clicks on a cell in this column. If this property is set with a JavaScript function, the function will be called as an event handler.' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true link: label: 'Link' description: 'If provided, the cell text will be made into a link rather than plain text.' type: 'url' inlineJs: true defaultHidden: true openLinksInNewWindow: label: 'Open Links in New Window' description: 'If true, links will open in a new browser window; this is the default.' type: 'boolean' default: true defaultHidden: true numeralformat: label: 'Numeral Format' description: 'Optionally specifies a Numeral.js-compatible format string, used to reformat the column value for display.' type: 'string' inlineJs: true defaultHidden: true image: label: 'Image' description: 'Optionally specifies a URL to an image to display in the column. The URL can be parameterized using any column values.' type: 'url' inlineJs: true defaultHidden: true imageHeight: label: 'Image Height' description: 'Optionally sets the height for the images displayed using the image property. If omitted, each image will be displayed at "1em" (the same height as text in the cell). Any valid CSS value string can be used, e.g. "110%", "20px", etc.' type: 'string' inlineJs: true defaultHidden: true icon: label: 'Icon' description: 'Optionally specifies a Font Awesome icon class to be displayed in the cell.' type: 'string' inlineJs: true defaultHidden: true iconColor: label: 'Icon Color' description: 'Optionally specifies a color for the icon if the icon property is also set. The value can be a named color (e.g. "red"), a hex color (e.g. "#AA0088") or a data source column/inline javascript (e.g. "#{statusColor}").' type: 'string' inlineJs: true defaultHidden: true border: label: 'Border' description: 'Optionally draws a border on either or both sides of the column. If set, this value should be either "left", "right", or "left,right" to indicate on which sides of the column to draw the borders.' type: 'string' inlineJs: true defaultHidden: true group: label: 'Column Group' description: 'Optionally puts the column in a column group. The value must be a string, which will be displayed above all consecutive columns with the same group property. The column group row will not appear unless at least one column has a group specified.' type: 'string' inlineJs: true defaultHidden: true groupRows: label: 'Group Rows' description: 'Optionally combines identical, consecutive values within a column. If set to true, and depending on the sort, repeated values in a column will be combined into a single cell with its rowspan value set. If the rows are separated by a resort, the combined cells will be split apart again. This property can be applied to any column(s) in the table. The default value is false.' type: 'boolean' default: false defaultHidden: true columnSortFunction: label: 'Column Sort Function' description: 'When using wildcard or regex expression in the `name` field, this property optionally provides a sort function used to order the generated columns. This function takes an array of column names and can return a sorted (or modified) array. Example: "${function(columns){return _.sortBy(columns);}}".' type: 'string' inlineJs: true defaultHidden: true columnsIgnored: label: 'Columns Ignored' description: 'When using wildcard or regex expression in the `name` field, this can contain a list of one or more column names that should not be matched.' type: 'string[]' required: false inlineJs: false defaultHidden: true order: 10 sample: name: '' rules: label: 'Rules' singleLabel: 'rule' description: 'Specifies an array of rules that will be run on each row in the table. Style properties can be set for every matching rule, on either the entire row or a subset of columns.' type: 'propertyset[]' inlineJs: true properties: rule: label: 'Rule' description: 'The rule expression evaluated to determine if this rule applies to a row. It can contain column values using #{name} notation. It will be evaluated as javascript, and should return true or false.' type: 'string' required: true inlineJs: true order: 1 columns: label: 'Columns Affected' description: 'Optionally specifies an array of column names, limiting the rule\'s effect to only the cells specified, rather than the entire row.' type: 'string[]' required: false order: 2 columnsIgnored: label: 'Columns Ignored' description: 'Optionally specifies an array of column names that the rule does NOT apply to.' type: 'string[]' required: false order: 3 name: label: 'Name' description: 'Indicates the name of the data source field to use for this column.' type: 'string' inlineJs: true defaultHidden: true 'font-weight': label: 'Font-Weight (CSS)' description: 'CSS setting for `font-weight`' type: 'string' inlineJs: true defaultHidden: true color: label: 'Color (CSS)' description: 'CSS setting for `color`' type: 'string' inlineJs: true defaultHidden: true 'background-color': label: 'Background Color (CSS)' description: 'CSS setting for `background-color`' type: 'string' inlineJs: true defaultHidden: true order: 11 sample: rule: 'true' freezeHeaders: label: 'Freeze Headers' description: 'Enables frozen headers at the top of the widget when scrolling' type: 'boolean' default: false required: false order: 12 omitHeaders: label: 'Omit Headers' description: 'Disables the table header row' type: 'boolean' default: false required: false order: 13 enableSort: label: 'Enable Sort' description: 'Enable or disable user sort controls' type: 'boolean' default: true required: false order: 14 rowHeight: label: 'Minimum Row Height' description: 'Specifies the (minimum) height in pixels of all rows (including the header row). The actual height of a row may be greater than this value, depending on the contents. If this is not set, each row will automatically size to its contents.' type: 'integer' required: false order: 15 pagination: label: 'Pagination' description: 'Controls pagination of the Table.' type: 'propertyset' required: false defaultHidden: true order: 16 properties: enabled: label: 'Enable Pagination' description: 'Enables or disables pagination for this Table Widget.' type: 'boolean' default: false required: false order: 1 autoItemsPerPage: label: 'Auto Items Per Page' description: 'Enables automatic detection of the number of rows to display in order to fit in the widget dimensions. Requires rowHeight property to be configured to work accurately. To manually size, set false and configure itemsPerPage instead.' type: 'boolean' default: true required: false order: 2 itemsPerPage: label: 'Items Per Page' description: 'Controls how many row are displayed on each page. If autoItemsPerPage is true, this is ignored.' type: 'integer' required: false order: 3 belowPagerMessage: label: 'Below Pager Message' description: 'If set, displays a message below the pager at the bottom of the Widget. The following variables can be used: #{itemsPerPage}, #{totalItems}, #{currentPage}.' type: 'string' required: false order: 4 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 17 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' order: 18 sortFunction: label: 'Sort Function' description: 'Optional, specifies an alternative function to the default sort implementation.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 19 onSort: label: 'Sort Event' description: 'This event occurs when the user changes the sort order of a column. If this property is set with a JavaScript function, the function will be called as an event handler. Return false from the function to prevent the default sort implementation from being applied.' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 20 tableau: name: 'tableau' label: 'Tableau' icon: 'fa-cog' properties: params: label: 'Parameters' description: 'An object of key-value pairs that Tableau uses to render the report. These parameters are specific to Tableau and will be passed-through to the view.' type: 'hash' required: true editorMode: 'json' order: 10 treemap: name: 'treemap' label: 'Treemap' icon: 'fa-tree' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for this Widget.' placeholder: 'Data Source name' type: 'string' required: true options: datasourceOptions order: 10 labelProperty: label: 'Label Property' description: 'The name of the property to use as the label of each item.' type: 'string' inlineJs: true required: false default: 'name' defaultHidden: true order: 11 valueProperty: label: 'Value Property' description: 'The name of the property to use to calculate the size of each item.' type: 'string' inlineJs: true required: false default: 'value' defaultHidden: true order: 12 valueDescription: label: 'Value Description' description: 'A short description of the property used to calculate the size of each item. Used in tooltips.' type: 'string' inlineJs: true required: false defaultHidden: true order: 13 valueFormat: label: 'Value Format' description: 'Specifies a Numeral.js-compatible format string used to format the label of the size value.' type: 'string' default: ',.2f' required: false defaultHidden: true inlineJs: true options: default: value: '0,0.[0]' percent: value: '0,0%' integer: value: '0,0' currency: value: '$0,0' order: 14 colorProperty: label: 'Color Property' description: 'The name of the property to use to calculate the color of each item. If omitted, the TreeMap will not be colored.' type: 'string' inlineJs: true required: false default: 'color' order: 15 colorDescription: label: 'Color Description' description: 'A short description of the property used to calculate the color of each item. Used in tooltips.' type: 'string' inlineJs: true required: false defaultHidden: true order: 16 colorFormat: label: 'Color Format' description: 'Specifies a Numeral.js-compatible format string used to format the label of the color value.' type: 'string' default: ',.2f' required: false defaultHidden: true inlineJs: true options: default: value: '0,0.[0]' percent: value: '0,0%' integer: value: '0,0' currency: value: '$0,0' large: value: '0a' order: 17 colorStops: label: 'Color Stops' singleLabel: 'color' description: 'Specifies a list of color stops used to build a gradient.' type: 'propertyset[]' inlineJs: true properties: value: label: 'Value' description: 'The numerical value assigned to this color stop.' type: 'number' required: true inlineJs: true order: 1 color: label: 'Color' description: 'The color to display at this color stop. Hex codes or CSS colors are permitted.' type: 'string' required: false inlineJs: true order: 2 order: 18 showLegend: label: 'Show Legend' description: 'Enables or disables the color legend.' type: 'boolean' default: true required: false order: 19 legendHeight: label: 'Legend Height' description: 'Specifies the height of the legend in pixels.' type: 'number' default: 30 required: false defaultHidden: true order: 20 widgetContainer: name: 'widgetContainer' label: 'Widget Container' icon: 'fa-desktop' properties: layout: label: 'Layout' description: 'Contains properties for configuring the Container layout and dimensions.' type: 'propertyset' default: {} required: false properties: gridColumns: label: 'Grid Columns' description: 'Specifies the total number of horizonal grid squares available in the grid. The grid squares will be scaled to fit the container. If omitted, the number of columns will be calculated dynamically.' type: 'integer' required: false order: 0 gridRows: label: 'Grid Rows' description: 'Specifies the total number of vertical grid squares available in the grid. The grid squares will be scaled vertically to fit the container. If omitted, the grid squares will be literally square, e.g. the height and width will be the same. When omitted, the widgets may not fill the entire container, or they may scroll vertically. Use this property to make widgets scale vertically to fit the container.' type: 'integer' required: false order: 1 gridWidthAdjustment: label: 'Grid Container Width Adjustment' description: 'Specifies an adjustment (in pixels) to the width of the container when calculating the grid layout. If the value is positive, the container width will have the adjustment added to it (making each column wider), whereas if it is negative, the container width will be reduced (making each column skinnier).' type: 'integer' default: 0 required: false defaultHidden: true order: 2 gridHeightAdjustment: label: 'Grid Container Height Adjustment' description: 'Specifies an adjustment (in pixels) to the height of the container when calculating the grid layout. If the value is positive, the container height will have the adjustment added to it (making each row taller), whereas if it is negative, the container height will be reduced (making each row shorter).' type: 'integer' default: 0 required: false order: 3 gutter: label: 'Gutter' description: 'Controls the space (in pixels) between widgets positioned in the grid. The default value is 10.' type: 'integer' default: 10 required: false defaultHidden: true order: 5 borderWidth: label: 'Border Width' description: 'Specifies the pixel width of the border around each widget. Can be set to 0 to remove the border. If omitted, the theme default will be used.' type: 'integer' default: null required: false defaultHidden: true order: 6 margin: label: 'Margin' description: 'Controls the empty margin width (in pixels) around the outer edge of the container. Can be set to 0 to remove the margin.' type: 'integer' default: 10 required: false defaultHidden: true order: 7 scrolling: label: 'Scrolling Enabled' description: 'Enables vertical scrolling of the container to display content longer than the current size.' type: 'boolean' default: true required: false defaultHidden: true order: 8 order: 10 sample: layout: gridColumns: 2 gridRows: 2 youtube: name: 'youtube' label: 'YouTube' icon: 'fa-youtube' properties: videoId: label: 'Video / Playlist ID' description: 'A YouTube video ID or Playlist ID. Multiple video IDs can be separated by commas.' type: 'string' inlineJs: true placeholder: 'ID' required: true order: 10 autoplay: label: 'Auto-Play' description: 'If true, automatically plays the video when the Widget is loaded.' type: 'boolean' inlineJs: true default: true required: false order: 13 loop: label: 'Loop' description: 'If true, automatically loops the video when it completes.' type: 'boolean' inlineJs: true default: true required: false order: 14 enableKeyboard: label: 'Enable Keyboard' description: 'If true, enables keyboard controls which are disabled by default.' type: 'boolean' inlineJs: true default: false required: false defaultHidden: true order: 15 enableControls: label: 'Enable Controls' description: 'If true, enables on-screen video controls which are disabled by default.' type: 'boolean' inlineJs: true default: false required: false defaultHidden: true order: 16 showAnnotations: label: 'Show Annotations' description: 'If true, displays available annotations over the video.' type: 'boolean' inlineJs: true default: false required: false defaultHidden: true order: 17 showRelated: label: 'Show Related' description: 'If true, displays related videos at the end of this video.' type: 'boolean' inlineJs: true default: false required: false defaultHidden: true order: 18 } # Copy Theme options to inherited locations exports.dashboard.properties.pages.properties.theme.options = exports.dashboard.properties.theme.options exports.dashboard.properties.pages.properties.widgets.properties.theme.options = exports.dashboard.properties.theme.options exports.dashboard.properties.pages.properties.themeVariant.options = exports.dashboard.properties.themeVariant.options exports.dashboard.properties.pages.properties.widgets.properties.themeVariant.options = exports.dashboard.properties.themeVariant.options # Copy Style options to inherited locations exports.dashboard.properties.pages.properties.style.options = exports.dashboard.properties.style.options # Table Widget: Column properties duplicated in Rules: tableProperties = exports.widgets.table.properties _.defaults tableProperties.rules.properties, _.omit(tableProperties.columns.properties, 'label') # Copy some chart themes #exports.widgets.chart.themes.lightborderless = exports.widgets.chart.themes.light # Populate Help tags with properties helpDashboards = _.find(exports.help, { name: 'Dashboards' }) helpDashboards.tags = _.union helpDashboards.tags, _.map exports.dashboard.properties, (value, name) -> name helpDataSources = _.find(exports.help, { name: 'Data Sources' }) helpDataSources.tags = _.union helpDataSources.tags, _.map exports.dashboard.properties.dataSources.properties, (value, name) -> name helpWidgets = _.find(exports.help, { name: 'Widgets' }) helpWidgets.tags = _.union helpWidgets.tags, _.map exports.dashboard.properties.pages.properties.widgets.properties, (value, name) -> name propertyMapHelper = (value, name) -> v = _.cloneDeep value v.name = name v # Add Widget and Data Source help pages helpDataSources.children = _.map _.sortBy(exports.dashboard.properties.dataSources.options, 'name'), (dataSource) -> { name: dataSource.label || dataSource.value path: '/partials/help/datasources/' + dataSource.value + '.html' tags: _.map dataSource.properties, propertyMapHelper } helpWidgets.children = _.map _.sortBy(exports.widgets, 'name'), (widget) -> { name: widget.label || widget.name path: '/widgets/' + widget.name + '/help.html' tags: _.map widget.properties, propertyMapHelper } return exports
true
### # Copyright (c) 2013-2015 the original author or authors. # # Licensed under the MIT License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.opensource.org/licenses/mit-license.php # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific # language governing permissions and limitations under the License. ### # Common Config File - all default or shared configs cyclotronServices.factory 'commonConfigService', -> linkedWidgetOptions = (dashboard) -> linkedWidgets = {} _.each dashboard.pages, (page, pageIndex) -> _.each page.widgets, (widget, widgetIndex) -> return if widget.widget == 'linkedWidget' widgetName = _.titleCase(widget.widget) if widget.name?.length > 0 or widget.title?.length > 0 widgetName += ': ' + (widget.name || widget.title) linkedWidgets['Page ' + (pageIndex + 1) + ': ' + widgetName] = { value: pageIndex + ',' + widgetIndex } linkedWidgets datasourceOptions = (dashboard) -> dataSources = {} _.each dashboard.dataSources, (dataSource) -> dataSources[dataSource.name] = { value: dataSource.name } dataSources exports = { version: '1.48.0' logging: enableDebug: false authentication: enable: false loginMessage: 'Please login using your LDAP username and password.' analytics: enable: false newUser: enableMessage: true welcomeMessage: 'It looks like you\'re new here! Take a look at the <a href="/help"><i class="fa fa-question-circle" /> Help</a> page.' iconClass: 'fa-info' autoDecayDuration: 1 # Dashboard settings dashboard: properties: name: label: 'Name' description: 'Dashboard Name. This is required and cannot be changed after the Dashboard is created.' placeholder: 'Dashboard Name' type: 'string' required: true order: 0 displayName: label: 'Display Name' description: 'Display Name; this is displayed in the browser title bar or the Header Widget.' placeholder: 'Display Name' type: 'string' required: false inlineJs: true defaultHidden: true order: 1 description: label: 'Description' description: 'A short summary of the Dashboard\'s purpose or capabilities.' placeholder: 'A short summary of the Dashboard\'s purpose or capabilities.' type: 'string' required: false order: 2 theme: label: 'Theme' description: 'The default Page Theme for the Dashboard. If this property is set, the value will be applied to any Pages that have not specified a Theme. If it is not set, the default value of "Dark" will be used.' type: 'string' default: 'dark' required: false options: charcoal: label: 'Charcoal' value: 'charcoal' dashboardBackgroundColor: '#1E2328' dark: label: 'Dark' value: 'dark' dashboardBackgroundColor: '#2f2f2f' darkmetro: label: 'Dark Metro' value: 'darkmetro' dashboardBackgroundColor: '#2f2f2f' gto: label: 'GTO' value: 'gto' dashboardBackgroundColor: 'white' light: label: 'Light' value: 'light' dashboardBackgroundColor: 'white' lightborderless: label: 'Light (borderless)' value: 'lightborderless' dashboardBackgroundColor: 'white' dark2: label: 'Very Dark' value: 'dark2' dashboardBackgroundColor: 'black' order: 5 themeVariant: label: 'Theme Variant' description: 'The default Theme Variant for the Dashboard; each Theme may or may not implement each variant. If this property is set, the value will be applies to any Pages that have not specified a Theme Variant. If it is not set, the default variant will be used.' type: 'string' default: 'default' required: false defaultHidden: true options: default: value: 'default' transparent: value: 'transparent' 'transparent-unpadded': value: 'transparent-unpadded' order: 6 style: label: 'Style' description: 'The default Page Style for the Dashboard. If this property is set, the value will be applied to any Pages that have not specified a Style. If it is not set, the default value of "Normal" will be used.' type: 'string' default: 'normal' required: false options: normal: value: 'normal' fullscreen: value: 'fullscreen' defaultHidden: true order: 7 autoRotate: label: 'Auto-Rotate' description: 'If set to true, Cyclotron will automatically rotate between pages of the Dashboard based on the duration property for each Page. Set this value false to require manual rotation.' type: 'boolean' default: false required: false defaultHidden: true order: 10 duration: label: 'Auto-Rotate Duration (seconds)' description: 'If autoRotate is enabled, this controls the default interval to rotate to the next page. This value can be overridded at a page level.' type: 'integer' placeholder: 'Seconds per page' default: 60 required: false defaultHidden: true order: 11 preload: label: 'Pre-Load Time (seconds)' description: 'The amount of time, in seconds, before rotating to preload the next page. If set, this value will apply to all pages in the Dashboard. If autoRotate is false, this value is ignored.' placeholder: 'Seconds' type: 'integer' default: 0.050 required: false defaultHidden: true order: 12 allowFullscreen: label: 'Allow Fullscreen' description: 'If true, each Widget on a Page can be maximized to fill the entire Dashboard. This setting can be overridden by each Page/Widget.' type: 'boolean' default: true required: false defaultHidden: true allowExport: label: 'Allow Export' description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This setting can be overridden by each Page/Widget.' type: 'boolean' default: true required: false defaultHidden: true openLinksInNewWindow: label: 'Open Links in New Window' description: 'If true, all links will open in a new browser window; this is the default.' type: 'boolean' required: false default: true defaultHidden: true showWidgetErrors: label: 'Show Error Messages on Widgets' description: 'If true, allows error messages to be displayed on Widgets. This setting can be overridden by each Page/Widget.' type: 'boolean' required: false default: true defaultHidden: true showDashboardControls: label: 'Show Dashboard Controls' description: 'If false, hides the default Dashboard controls (rotation, export, etc)' type: 'boolean' required: false default: true defaultHidden: true sidebar: label: 'Sidebar' description: '' type: 'propertyset' default: {} defaultHidden: true properties: showDashboardSidebar: label: 'Show Dashboard Sidebar' description: 'If false, hides the default Dashboard Sidebar.' type: 'boolean' required: false default: false order: 10 showDashboardTitle: label: 'Include Dashboard Title' description: 'Enables a section of the sidebar for the Dashboard title.' type: 'boolean' required: false default: true defaultHidden: true order: 11 showToolbar: label: 'Include Toolbar' description: 'Enables a toolbar in the sidebar.' type: 'boolean' required: false default: true defaultHidden: true order: 12 showHideWidgets: label: 'Include Show/Hide Widgets' description: 'Enables a section of the sidebar for overriding the visibility of Widgets.' type: 'boolean' required: false default: false defaultHidden: true order: 13 sidebarContent: label: 'Custom Sidebar Sections' singleLabel: 'Section' description: 'One or more sections of content to display in the Sidebar.' type: 'propertyset[]' default: [] order: 15 properties: heading: label: 'Heading' description: 'Heading for the Sidebar section.' type: 'string' inlineJs: true order: 1 html: label: 'HTML Content' description: 'HTML Content to display.' placeholder: 'Value' type: 'editor' editorMode: 'html' inlineJs: true order: 2 pages: label: 'Pages' description: 'The list of Page definitions which compose the Dashboard.' type: 'pages' default: [] required: true properties: name: label: 'Name' description: 'Name of this page; used in the browser title and URL.' placeholder: 'Page Name' type: 'string' required: false order: 0 layout: label: 'Layout' description: 'Contains properties for configuring the Page layout and dimensions.' type: 'propertyset' default: {} required: false properties: gridColumns: label: 'Grid Columns' description: 'Specifies the total number of horizonal grid squares available in the grid. The grid squares will be scaled to fit the browser window. If omitted, the number of columns will be calculated dynamically.' type: 'integer' required: false order: 0 gridRows: label: 'Grid Rows' description: 'Specifies the total number of vertical grid squares available in the grid. The grid squares will be scaled vertically to fit the browser window. If omitted, the grid squares will be literally square, e.g. the height and width will be the same. When omitted, the widgets may not fill the entire browser window, or they may scroll vertically. Use this property to make widgets scale vertically to fit the dashboard.' type: 'integer' required: false order: 1 gridWidthAdjustment: label: 'Grid Page Width Adjustment' description: 'Specifies an adjustment (in pixels) to the width of the page when calculating the grid layout. If the value is positive, the page width will have the adjustment added to it (making each column wider), whereas if it is negative, the page width will be reduced (making each column skinnier).' type: 'integer' default: 0 required: false defaultHidden: true order: 2 gridHeightAdjustment: label: 'Grid Page Height Adjustment' description: 'Specifies an adjustment (in pixels) to the height of the page when calculating the grid layout. If the value is positive, the page height will have the adjustment added to it (making each row taller), whereas if it is negative, the page height will be reduced (making each row shorter). This is commonly used with a fixed-height Header widget.' type: 'integer' default: 0 required: false order: 3 gutter: label: 'Gutter' description: 'Controls the space (in pixels) between widgets positioned in the grid. The default value is 10.' type: 'integer' default: 10 required: false defaultHidden: true order: 5 borderWidth: label: 'Border Width' description: 'Specifies the pixel width of the border around each widget. Can be set to 0 to remove the border. If omitted, the theme default will be used.' type: 'integer' default: null required: false defaultHidden: true order: 6 margin: label: 'Margin' description: 'Controls the empty margin width (in pixels) around the outer edge of the Dashboard. Can be set to 0 to remove the margin.' type: 'integer' default: 10 required: false defaultHidden: true order: 7 scrolling: label: 'Scrolling Enabled' description: 'Enables vertical scrolling of the page to display content longer than the current browser size.' type: 'boolean' default: true required: false defaultHidden: true order: 8 order: 2 widgets: label: 'Widgets' description: 'An array of one or more Widgets to display on the page' type: 'propertyset[]' subState: 'edit.widget' headingfn: 'getWidgetName' default: [] required: true properties: widget: label: 'Type' description: 'The type of Widget to be rendered.' type: 'string' required: true name: label: 'Name' description: 'Internal Widget name, displayed in the Dashboard Editor.' placeholder: 'Name' type: 'string' required: false defaultHidden: true inlineJs: false order: 1 title: label: 'Title' description: 'Specifies the title of the widget. Most widgets will display the title at the top of the widget. If omitted, nothing will be displayed and the widget contents will occupy the entire widget boundaries.' placeholder: 'Widget Title' type: 'string' required: false inlineJs: true order: 2 gridHeight: label: 'Grid Rows' description: 'Specifies the number of vertical grid squares for this widget to occupy. Instead of an absolute height, this sets the relative size based on grid units.' placeholder: 'Number of Rows' type: 'integer' default: '1' required: false order: 100 gridWidth: label: 'Grid Columns' description: 'Specifies the number of horizontal grid squares for this widget to occupy. Instead of an absolute width, this sets the relative size based on grid units.' placeholder: 'Number of Columns' type: 'integer' default: '1' required: false order: 101 height: label: 'Height' description: 'If set, specifies the absolute display height of the widget. Any valid CSS value can be used (e.g. "200px", "40%", etc).' placeholder: 'Height' type: 'string' required: false defaultHidden: true order: 102 width: label: 'Width' description: 'If set, specifies the absolute display width of the widget. Any valid CSS value can be used (e.g. "200px", "40%", etc).' placeholder: 'Width' type: 'string' required: false defaultHidden: true order: 103 autoHeight: label: 'Auto-Height (Fit to Contents)' description: 'If true, disables both the gridHeight and height properties, and allows the Widget to be vertically sized to fit its contents.' type: 'boolean' required: false defaultHidden: true order: 104 helpText: label: 'Help Text' description: 'Provides an optional help text for the Widget, available via a help icon in the corner of the Widget.' type: 'string' required: false inlineJs: true defaultHidden: true order: 109 theme: label: 'Theme' description: 'If set, overrides the Page theme and allows a widget to have a different theme from the rest of the Page and Widgets.' type: 'string' inherit: true required: false defaultHidden: true order: 110 themeVariant: label: 'Theme Variant' description: 'If set, overrides the Page theme variant and allows a widget to have a different theme variant from the rest of the Page and Widgets.' type: 'string' inherit: true required: false defaultHidden: true order: 111 noData: label: 'No Data Message' description: 'If set, displays this message in the Widget when no data is loaded from the Data Source. If not set, no message will be displayed' type: 'string' inlineJs: true required: false defaultHidden: true order: 120 noscroll: label: 'No Scroll' description: 'If set to true, the widget will not have scrollbars and any overflow will be hidden. The effect of this setting varies per widget.' type: 'boolean' default: false required: false defaultHidden: true order: 121 allowFullscreen: label: 'Allow Fullscreen' description: 'If true, the Widget can be maximized to fill the entire Dashboard; if false, the ability to view in fullscreen is disabled. This property overrides the Page setting.' type: 'boolean' inherit: true required: false defaultHidden: true order: 122 allowExport: label: 'Allow Export' description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This property overrides the Page setting.' type: 'boolean' inherit: true required: false defaultHidden: true order: 123 showWidgetErrors: label: 'Show Error Messages on Widgets' description: 'If true, allows error messages to be displayed on Widgets. This property overrides the Page setting.' type: 'boolean' required: false inherit: true defaultHidden: true order: 124 hidden: label: 'Hidden' description: 'If true, the Widget will not be displayed in the Dashboard and will not occupy space in the Layout rendering. The Widget will still be initialized, however.' type: 'boolean' default: false required: false defaultHidden: true order: 125 genericEvents: label: 'Generic Events' singleLabel: 'param-event' description: 'Array of parameters (defined beforehand in the Parameters section of the dashboard) and events that can trigger their change within widgets. Note that adding a Name to the widget is mandatory for this property to work.' type: 'propertyset[]' inlineJs: true defaultHidden: true default: [] properties: paramName: label: 'Parameter Name' type: 'string' required: true order: 1 event: label: 'Event' type: 'string' required: true options: clickOnWidget: value: 'clickOnWidget' order: 2 order: 126 parameterSubscription: label: 'Subscription To Parameters' singleLabel: 'param' description: 'Specifies a list of parameters the widget subscribes to, i.e., that the widget uses and that can cause its reload upon change. See section Parameters for more details.' type: 'string[]' inlineJs: true defaultHidden: true default: [] order: 127 container: label: 'Container' description: 'Name of the Container Widget that should contain this widget' type: 'string' inlineJs: true defaultHidden: true order: 128 order: 3 duration: label: 'Auto-Rotate Duration (seconds)' description: 'The number of seconds to remain on this page before rotating to the next page. If autoRotate is set to false, this value is ignored.' placeholder: 'Seconds per page' inherit: true type: 'integer' required: false defaultHidden: true order: 4 frequency: label: 'Frequency' description: 'If greater than one, this page will only be shown on every N cycles through the dashboard. Defaults to 1, meaning the Page will be shown on every cycle.' default: 1 type: 'integer' required: false defaultHidden: true order: 5 theme: label: 'Theme' description: 'The theme for the Page. If not set, the Dashboard setting or default value will apply.' type: 'string' inherit: true required: false defaultHidden: true order: 6 themeVariant: label: 'Theme Variant' description: 'The theme variant for the Page. If not set, the Dashboard setting or default value will apply.' type: 'string' inherit: true required: false defaultHidden: true order: 7 style: label: 'Style' description: 'The style for the Page. If not set, the Dashboard setting or default value will apply.' type: 'string' inherit: true required: false defaultHidden: true order: 8 allowFullscreen: label: 'Allow Fullscreen' description: 'If true, each Widget on the page can be maximized to fill the entire Dashboard. This setting can be overridden by each Widget.' type: 'boolean' inherit: true required: false defaultHidden: true order: 10 allowExport: label: 'Allow Export' description: 'If true, the Widget data can be exported via a dropdown menu in the Widget. This setting can be overridden by each Widget.' type: 'boolean' inherit: true required: false defaultHidden: true order: 11 showWidgetErrors: label: 'Show Error Messages on Widgets' description: 'If true, allows error messages to be displayed on Widgets. This setting can be overridden by each Widget.' type: 'boolean' required: false inherit: true defaultHidden: true order: 12; dataSources: label: 'Data Sources' description: 'A list of Data Sources which connect to external services and pull in data for the Dashboard.' type: 'datasources' default: [] required: false properties: name: label: 'Name' description: 'The Data Source Name is used to reference the Data Source from a widget' placeholder: 'Data Source Name' type: 'string' required: true order: 1 type: label: 'Type' description: 'Specifies the implementation type of the Data Source' type: 'string' required: true order: 0 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted' type: 'hash' inlineJsKey: true inlineJsValue: true required: false defaultHidden: true order: 101 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' defaultHidden: true order: 102 preload: label: 'Preload' description: 'By default, each Data Source is loaded only when it is used, e.g. when a Widget consuming it is rendered. Setting this true causes Cyclotron to load the Data Source when the Dashboard is initialized.' type: 'boolean' inlineJs: false required: false default: false defaultHidden: true order: 103 deferred: label: 'Deferred' description: 'Prevents execution of the data source until execute() is manually called on the Data Source. This should only be used when using custom JavaScript to execute this Data Source, otherwise the Data Source will never run.' type: 'boolean' inlineJs: false required: false default: false defaultHidden: true order: 103 errorHandler: label: 'Error Handler' description: 'Specifies an optional JavaScript function that is called if an errors occurs. It can return a different or modified error message. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 104 parameterSubscription: label: 'Subscription To Parameters' singleLabel: 'param' description: 'Specifies a list of parameters the data source subscribes to, i.e., that can cause the re-execution of the data source upon change. See section Parameters for more details.' type: 'string[]' inlineJs: true defaultHidden: true default: [] order: 105 options: cloudwatch: value: 'cloudwatch' label: 'CloudWatch' message: 'Amazon CloudWatch monitors operational and performance metrics for your AWS cloud resources and applications. Refer to the <a href="http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/Welcome.html" target="_blank">API Documentation</a> for information on configuring the available options.' icon: 'fa-cloud-download' properties: url: label: 'URL' description: 'Specifies the Amazon CloudWatch Endpoint for the desired region, e.g. "monitoring.us-west-2.amazonaws.com".' placeholder: 'CloudWatch Endpoint' type: 'url' inlineJs: true inlineEncryption: true required: true order: 10 awsCredentials: label: 'AWS Credentials' description: 'AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.' type: 'propertyset' required: true order: 12 properties: accessKeyId: label: 'Access Key Id' description: 'AWS access key id' type: 'string' placeholder: 'Access Key Id' inlineJs: true inlineEncryption: true order: 1 secretAccessKey: label: 'Secret Access Key' description: 'AWS sercet access key' type: 'string' placeholder: 'Secret Access Key' inlineJs: true inlineEncryption: true order: 2 parameters: label: 'CloudWatch Parameters' description: 'Set of parameters for the CloudWatch API.' type: 'propertyset' required: true order: 13 properties: Action: label: 'Action' description: 'Specifies one of the CloudWatch actions.' type: 'string' default: 'auto' inlineJs: true options: ListMetrics: value: 'ListMetrics' GetMetricStatistics: value: 'GetMetricStatistics' required: true order: 1 Namespace: label: 'Namespace' description: 'The namespace to filter against.' type: 'string' inlineJs: true required: false order: 2 MeasureName: label: 'Metric Name' description: 'The name of the metric to filter against.' type: 'string' inlineJs: true required: false order: 3 Dimensions: label: 'Dimensions' description: 'Optional; a list of Dimension key/values to filter against.' type: 'hash' required: false inlineJsValue: true inlineEncryption: true order: 4 Statistics: label: 'Statistics' description: 'Specifies one or more Statistics to return.' type: 'string[]' inlineJs: true options: SampleCount: value: 'SampleCount' Average: value: 'Average' Sum: value: 'Sum' Minimum: value: 'Minimum' Maximum: value: 'Maximum' required: true order: 5 Period: label: 'Period' description: 'The granularity, in seconds, of the returned datapoints. A Period can be as short as one minute (60 seconds) or as long as one day (86,400 seconds), and must be a multiple of 60.' type: 'integer' default: 60 required: false placeholder: 'Number of Seconds' order: 6 StartTime: label: 'Start Time' description: 'The date/time of the first datapoint to return. The time stamp must be in ISO 8601 UTC format (e.g., 2014-09-03T23:00:00Z).' type: 'string' inlineJs: true required: false order: 8 EndTime: label: 'End Time' description: 'The date/time of the last datapoint to return. The time stamp must be in ISO 8601 UTC format (e.g., 2014-09-03T23:00:00Z).' type: 'string' inlineJs: true required: false order: 9 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 15 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 16 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 17 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 11 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 18 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 cyclotronData: value: 'cyclotronData' label: 'CyclotronData' icon: 'fa-cloud-download' message: 'Cyclotron has built-in support for a limited amount of data storage using uniquely-named buckets. Refer to to the Documentation for more details.' properties: key: label: 'Bucket Key' description: 'Specifies the unique key to a Cyclotron Data bucket.' placeholder: 'Bucket Key' type: 'string' inlineJs: true required: true order: 10 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 14 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 15 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 16 url: label: 'Cyclotron Server' description: 'Specifies which Cyclotron server to request data from. If omitted, the default sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 11 elasticsearch: value: 'elasticsearch' label: 'Elasticsearch' icon: 'fa-cloud-download' properties: url: label: 'URL' description: 'Specifies the Elasticsearch endpoint.' placeholder: 'Elasticsearch URL' type: 'url' inlineJs: true inlineEncryption: true required: true order: 10 index: label: 'Index' description: 'Specifies the name of the Elasticsearch index to query.' type: 'string' inlineJs: true inlineEncryption: true required: true order: 12 method: label: 'API Name' description: 'Indicates which Elasticsearch API method to use; defaults to "_search".' type: 'string' inlineJs: true inlineEncryption: true defaultHidden: true default: '_search' required: false order: 13 request: label: 'Elasticsearch Request' description: 'Specifies the Elasticsearch JSON request.' placeholder: 'JSON' type: 'editor' editorMode: 'json' inlineJs: true inlineEncryption: true required: true order: 14 responseAdapter: label: 'Response Adapter' description: 'Determines how the Elasticsearch response will be converted to Cyclotron\'s data format. Defaults to "auto".' type: 'string' default: 'auto' inlineJs: true options: 'Auto': value: 'auto' 'Hits': value: 'hits' 'Aggregations': value: 'aggregations' 'Raw': value: 'raw' required: false order: 15 awsCredentials: label: 'AWS Credentials' description: 'Optional AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 16 properties: accessKeyId: label: 'Access Key Id' description: 'AWS access key id' type: 'string' placeholder: 'Access Key Id' inlineJs: true inlineEncryption: true order: 1 secretAccessKey: label: 'Secret Access Key' description: 'AWS sercet access key' type: 'string' placeholder: 'Secret Access Key' inlineJs: true inlineEncryption: true order: 2 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 20 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 21 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 22 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 23 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 24 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 graphite: value: 'graphite' label: 'Graphite' icon: 'fa-cloud-download' message: 'The Graphite Data Source connects to any <a href="http://graphite.readthedocs.org/" target="_blank">Graphite<a> server to load time-series metrics via the Render api. For more details on usage, refer to the Graphite <a href="http://graphite.readthedocs.org/en/latest/render_api.html" target="_blank">documentation</a>.' properties: url: label: 'URL' description: 'The Graphite server' placeholder: 'Graphite Server URL or IP' type: 'url' inlineJs: true inlineEncryption: true required: true order: 10 targets: label: 'Targets' description: 'One or more Graphite metrics, optionally with metrics.' type: 'string[]' inlineJs: true inlineEncryption: true required: true order: 11 from: label: 'From' description: 'Specifies the absolute or relative beginning of the time period to retrieve. If omitted, it defaults to 24 hours ago (per Graphite).' placeholder: 'Start Time' type: 'string' inlineJs: true inlineEncryption: true required: false order: 12 until: label: 'Until' description: 'Specifies the absolute or relative end of the time period to retrieve. If omitted, it defaults now (per Graphite).' placeholder: 'End Time' type: 'string' inlineJs: true inlineEncryption: true required: false order: 13 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 14 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 15 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Graphite result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 16 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 11 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 17 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 influxdb: value: 'influxdb' label: 'InfluxDB' icon: 'fa-cloud-download' message: '<a href="https://www.influxdata.com/time-series-platform/influxdb/" target="_blank">InfluxDB</a> is an open source time series database built from the ground up to handle high write and query loads.' properties: url: label: 'URL' description: 'The InfluxDB server' placeholder: 'InfluxDB Server URL or IP' type: 'url' inlineJs: true required: true order: 10 database: label: 'Database' description: 'Specifies the target InfluxDB database for the query.' placeholder: 'Database' type: 'string' required: true inlineJs: true inlineEncryption: true required: false order: 11 query: label: 'Query' description: 'An InfluxQL query.' type: 'string' inlineJs: true inlineEncryption: true required: true order: 11 precision: label: 'Precision' description: 'Overrides the default timestamp precision.' type: 'string' default: 'ms' inlineJs: true options: h: value: 'h' m: value: 'm' s: value: 's' ms: value: 'ms' u: value: 'u' ns: value: 'ns' order: 11 username: label: 'Username' description: 'Optional; username for authentication, if enabled.' type: 'string' inlineJs: true inlineEncryption: true order: 15 password: label: 'Password' description: 'Optional; password for authentication, if enabled.' type: 'string' inputType: 'password' inlineJs: true inlineEncryption: true order: 16 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 21 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 22 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Graphite result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 23 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 11 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 24 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 javascript: value: 'javascript' label: 'JavaScript' icon: 'fa-cloud-download' message: 'The JavaScript Data Source allows custom JavaScript to be used to load or generate a Data Source.' properties: processor: label: 'Processor' description: 'Specifies a JavaScript function used to provide data for the Data Source, either by directly returning a data set, or resolving a promise asynchronously. The function is called with an optional promise which can be used for this purpose.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: true order: 10 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 11 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 12 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the JavaScript result dataset before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 13 json: value: 'json' label: 'JSON' icon: 'fa-cloud-download' properties: url: label: 'URL' description: 'Specifies the JSON Web Service URL.' placeholder: 'Web Service URL' type: 'url' inlineJs: true inlineEncryption: true required: true order: 10 queryParameters: label: 'Query Parameters' description: 'Optional query parameters which are added to the URL. If there are already query parameters in the URL, these will be appended. The keys and values are both URL-encoded.' type: 'hash' required: false inlineJsKey: true inlineJsValue: true inlineEncryption: true defaultHidden: true order: 12 options: label: 'Options' description: 'Optional request parameters that are passed to the library making the request.' type: 'hash' required: false inlineJsValue: true inlineEncryption: true defaultHidden: true order: 13 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 14 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 15 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 16 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 11 awsCredentials: label: 'AWS Credentials' description: 'Optional AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 17 properties: accessKeyId: label: 'Access Key Id' description: 'AWS access key id' type: 'string' placeholder: 'Access Key Id' inlineJs: true inlineEncryption: true order: 1 secretAccessKey: label: 'Secret Access Key' description: 'AWS sercet access key' type: 'string' placeholder: 'Secret Access Key' inlineJs: true inlineEncryption: true order: 2 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 18 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 ###scopes: label: 'Scopes' description: 'Optional list of scopes (comma- or space-separated, according to what the authorization server accepts) that will be passed to the authorization server' type: 'string' placeholder: 'Scopes' inlineJs: true inlineEncryption: true order: 4 ### mock: value: 'mock' label: 'Mock' icon: 'fa-cloud-download' message: 'The Mock Data Source generates sample data for testing a dashboard.' properties: format: label: 'Format' description: 'Selects the format of the mock data from these possible values: ["object", "pie", "ducati"]. Defaults to "object".' type: 'string' required: false default: 'object' options: object: value: 'object' pie: value: 'pie' large: value: 'large' ducati: value: 'ducati' order: 10 refresh: label: 'Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 11 odata: value: 'odata' label: 'OData' icon: 'fa-cloud-download' properties: url: label: 'URL' description: 'Specifies the OData Service URL.' placeholder: 'Service URL' type: 'url' inlineJs: true inlineEncryption: true required: true order: 10 responseAdapter: label: 'Response Adapter' description: 'Determines how the response will be converted to Cyclotron\'s data format. Defaults to "raw", i.e. the result is returned as is. Use "Entity Set" to read a list of objects. Use "Single Entity" to read a single object. Use "Primitive Property" to have a single value.' type: 'string' default: 'raw' inlineJs: true options: 'Primitive Property': value: 'primitive_prop' 'Single Entity': value: 'single_entity' 'Entity Set': value: 'entity_set' 'Raw': value: 'raw' required: false order: 11 queryParameters: label: 'Query Parameters' description: 'Optional query parameters which are added to the URL. If there are already query parameters in the URL, these will be appended. The keys and values are both URL-encoded.' type: 'hash' required: false inlineJsKey: true inlineJsValue: true inlineEncryption: true defaultHidden: true order: 12 refresh: label: 'Auto-Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 13 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not a JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 14 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the result before it is sent to the Widgets. If this value is not a JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false order: 15 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 16 options: label: 'Options' description: 'Optional request parameters that are passed to the library making the request.' type: 'hash' required: false inlineJsValue: true inlineEncryption: true defaultHidden: true order: 17 awsCredentials: label: 'AWS Credentials' description: 'Optional AWS IAM signing credentials for making authenticated requests. If set, the request will be signed before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 18 properties: accessKeyId: label: 'Access Key Id' description: 'AWS access key id' type: 'string' placeholder: 'Access Key Id' inlineJs: true inlineEncryption: true order: 1 secretAccessKey: label: 'Secret Access Key' description: 'AWS sercet access key' type: 'string' placeholder: 'Secret Access Key' inlineJs: true inlineEncryption: true order: 2 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 19 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 splunk: value: 'splunk' label: 'Splunk' icon: 'fa-cloud-download' properties: query: label: 'Query' description: 'Splunk query' placeholder: 'Splunk query' type: 'textarea' required: true order: 10 earliest: label: 'Earliest Time' description: 'Sets the earliest (inclusive), respectively, time bounds for the search. The time string can be either a UTC time (with fractional seconds), a relative time specifier (to now) or a formatted time string.' placeholder: 'Earliest Time' type: 'string' inlineJs: true inlineEncryption: true required: false order: 11 latest: label: 'Latest Time' description: 'Sets the latest (exclusive), respectively, time bounds for the search. The time string can be either a UTC time (with fractional seconds), a relative time specifier (to now) or a formatted time string.' placeholder: 'Latest Time' type: 'string' inlineJs: true inlineEncryption: true required: false order: 12 username: label: 'Username' description: 'Username to authenticate with Splunk' type: 'string' required: true inlineJs: true inlineEncryption: true order: 13 password: label: 'PI:PASSWORD:<PASSWORD>END_PI' description: 'PI:PASSWORD:<PASSWORD>END_PI to authenticate with Splunk' type: 'string' inputType: 'password' required: true inlineJs: true inlineEncryption: true order: 14 host: label: 'Host' description: 'Splunk API host name' placeholder: 'Splunk API host name' type: 'string' inputType: 'string' required: false defaultHidden: false order: 15 url: label: 'URL' description: 'The Splunk API Search URL' placeholder: 'Splunk API Search URL' type: 'url' inlineJs: true inlineEncryption: true default: 'https://#{host}:8089/services/search/jobs/export' defaultHidden: true required: false order: 16 refresh: label: 'Refresh' description: 'Optional; specifies the number of seconds after which the Data Source reloads' type: 'integer' required: false placeholder: 'Number of Seconds' order: 17 preProcessor: label: 'Pre-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Data Source properties before it is executed. This method will be called before the Data Source is executed, and passed the Data Source object as an argument. This object can be modified, or a new/modified object returned. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 18 postProcessor: label: 'Post-Processor' description: 'Specifies an optional JavaScript function that can inspect and modify the Splunk result dataset before it is sent to the Widgets. If this value is not an JavaScript function, it will be ignored.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 19 proxy: label: 'Proxy Server' description: 'Specifies which Proxy server to route the requests through. This is required to use encrypted strings within the Data Source properties. If omitted, the default proxy sever will be used.' type: 'url' inlineJs: true required: false defaultHidden: true order: 20 oauth2ClientCredentials: label: 'OAuth2.0 Client Credentials' description: 'Optional OAuth2.0 client credentials for making authenticated requests. If set, the request will be added an Authorization header before it is sent.' type: 'propertyset' required: false defaultHidden: true order: 21 properties: authorizationServerUrl: label: 'Authorization Server URL' description: 'URL of the server that will provide the access token' type: 'url' placeholder: 'Authorization Server URL' inlineJs: true inlineEncryption: true order: 1 clientId: label: 'Client ID' description: 'Client ID of the application' type: 'string' placeholder: 'Client ID' inlineJs: true inlineEncryption: true order: 2 clientSecret: label: 'Client Secret' description: 'Client secret of the application' type: 'string' placeholder: 'Client Secret' inlineJs: true inlineEncryption: true order: 3 parameters: label: 'Parameters' description: 'A list of Parameters that can be used to configure the Dashboard.' type: 'propertyset[]' default: [] required: false properties: name: label: 'Name' description: 'The name used to set or reference this Parameter.' type: 'string' required: true placeholder: 'Parameter Name' order: 0 defaultValue: label: 'Default Value' description: 'The value used if the Parameter is not set when opening the Dashboard.' type: 'string' placeholder: 'Default Value' required: false inlineJs: true order: 1 showInUrl: label: 'Show in URL' description: 'Determines whether or not the Parameter is displayed in the query string of the Dashboard URL.' type: 'boolean' default: true required: false order: 2 editInHeader: label: 'Editable in Header' description: 'If true, the Parameter will be displayed and configurable in the Parameter section of the Header Widget (if used).' type: 'boolean' default: false required: false order: 3 persistent: label: 'Persistent' description: 'If true, the value of this Parameter will be persisted in the user\'s browser across multiple sessions.' type: 'boolean' default: false required: false order: 4 changeEvent: label: 'Change Event' description: 'This event occurs when the Parameter value is modified. It does not fire when the Dashboard is being initialized. Expects a JavaScript function in the form function(parameterName, newValue, oldValue).' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 10 editing: label: 'Editing' description: 'Configuration for how this Parameter can be edited in the Dashboard.' type: 'propertyset' required: false default: {} defaultHidden: true order: 15 properties: displayName: label: 'Display Name' description: 'The display name used for this Parameter.' type: 'string' required: false placeholder: 'Display Name' order: 1 editorType: label: 'Editor Type' description: 'Determines the type of editor used to configured this Parameter (e.g. in the Header Widget).' type: 'string' required: false default: 'textbox' order: 2 options: textbox: value: 'textbox' dropdown: value: 'dropdown' autocomplete: value: 'autocomplete' links: value: 'links' checkbox: value: 'checkbox' radiobuttons: value: 'radiobuttons' datetime: value: 'datetime' date: value: 'date' time: value: 'time' dataSource: label: 'Data Source' description: 'Optionally specifies a Data Source providing dropdown options for this Parameter.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions order: 4 datetimeFormat: label: 'Date/Time Format' description: 'The Moment.js-compatible date/time format string used to read/write datetimes to this Parameter. Only used if the editor type is "datetime", "date", or "time". Defaults to an ISO 8601 format.' type: 'string' required: false placeholder: 'Format' defaultHidden: true order: 5 minCharNumber: label: 'Minimal Number of Characters' description: 'Minimal number of characters typed before autocomplete activates. Must be greather than or equal to 0. Defaults to 1.' type: 'integer' required: false default: 1 defaultHidden: true order: 6 allowNonMatching: label: 'Allow Non-Matching Values' description: 'If true, values that do not match any value in the list can be entered in the autocomplete input field. If false, only values in the list are allowed.' type: 'boolean' default: true required: false defaultHidden: true order: 7 allowEmpty: label: 'Allow Empty Input field' description: 'If true, the autocomplete input field can be empty. If false, the field is automatically populated with the currently highlighted value of the list when it is not focused.' type: 'boolean' default: true required: false defaultHidden: true order: 7 broadcastUpdate: label: 'Broadcast Parameter update' description: 'Notify the dashboard that the value has changed' type: 'boolean' default: true required: false defaultHidden: true order: 8 sample: name: '' defaultValue: '' scripts: label: 'Scripts' description: 'Defines a list of inline JavaScript or external JavaScript URIs that are loaded when the Dashboard initializes.' type: 'propertyset[]' default: [] required: false properties: name: label: 'Name' description: 'Display name of the script' type: 'string' placeholder: 'Name' required: false order: 0 path: label: 'Path' description: 'URL to a JavaScript file, to be loaded along with the Dashboard' type: 'url' placeholder: 'JavaScript file URL' required: false order: 1 text: label: 'JavaScript Text' description: 'Inline JavaScript to be run when the Dashboard is loaded' type: 'editor' editorMode: 'javascript' placeholder: 'Inline JavaScript' required: false order: 2 singleLoad: label: 'Single-Load' description: 'If true, this Script will only be loaded once when the Dashboard is loaded. Otherwise, it will be rerun every time the Dashboard internally refreshes. Scripts loaded from a path are always treated as single-load, and this property is ignored.' type: 'boolean' required: false default: false order: 3 sample: text: '' styles: label: 'Styles' description: 'Defines a list of inline CSS or external CSS URIs that are loaded when the Dashboard initializes.' type: 'propertyset[]' default: [] required: false properties: name: label: 'Name' description: 'Display name of the style' type: 'string' placeholder: 'Name' required: false order: 0 path: label: 'Path' description: 'URL to a CSS file, to be loaded along with the Dashboard' type: 'url' placeholder: 'CSS file URL' required: false order: 0 text: label: 'CSS Text' description: 'Inline CSS to be run when the Dashboard is loaded' type: 'editor' editorMode: 'css' placeholder: 'Inline CSS' required: false order: 1 sample: text: '' controls: # Controls how long to display the controls before hiding. duration: 1000 # Controls how close the mouse must be before the controls appear hitPaddingX: 60 hitPaddingY: 50 sample: name: '' sidebar: showDashboardSidebar: true pages: [] # Dashboard Sidebar dashboardSidebar: footer: logos: [{ title: 'Cyclotron' src: '/img/favicon32.png' href: '/' }] # List of help pages help: [ { name: 'About' path: '/partials/help/about.html' tags: ['about', 'terminology', 'features'] children: [ { name: 'Quick Start' path: '/partials/help/quickstart.html' tags: ['help', 'creating', 'tags', 'theme', 'revisions', 'preview', 'data sources', 'pages', 'layout', 'widgets'] } { name: 'JSON' path: '/partials/help/json.html' tags: ['json'] } { name: 'Examples' path: '/partials/help/examples.html' tags: ['examples', 'cyclotron-examples'] } { name: 'Browser Compatibility' path: '/partials/help/browserCompat.html' tags: ['browser', 'compatibility', 'firefox', 'chrome', 'internet explorer', 'ie', 'safari', 'browsercheck'] } { name: 'Permissions' path: '/partials/help/permissions.html' tags: ['permissions', 'edit permission', 'view permission', 'editors', 'viewers', 'restricted', 'login', 'rest', 'api'] } { name: 'Analytics' path: '/partials/help/analytics.html' tags: ['analytics', 'pageviews', 'visits', 'metrics'] } { name: 'Encrypted Strings' path: '/partials/help/encryptedStrings.html' tags: ['encryption', 'encrypted', '!{', 'decrypt', 'encrypt'] } { name: 'JavaScript API' path: '/partials/help/javascriptApi.html' tags: ['javascript', 'api', 'scripting'] } { name: 'CyclotronData' path: '/partials/help/cyclotrondata.html' tags: ['cyclotrondata', 'data', 'storage', 'bucket', 'api'] } { name: '3rd Party Libraries' path: '/partials/help/3rdparty.html' tags: ['libraries', 'jquery', 'moment', 'lodash', 'angular', 'numeral', 'localforage', 'uri', 'bootstrap', 'c3.js', 'd3.js', 'font awesome', 'highcharts', 'masonry', 'metricsgraphics', 'select2', 'spin.js'] } { name: 'Hotkeys' path: '/partials/help/hotkeys.html' tags: ['hotkeys', 'keys', 'shortcuts'] } { name: 'API' path: '/partials/help/api.html' tags: ['api', 'rest', 'service'] } ] } { name: 'Dashboards' path: '/partials/help/dashboards.html' tags: ['dashboards', 'pages', 'dataSources', 'scripts', 'parameters'] children: [ { name: 'Pages' path: '/partials/help/pages.html' tags: ['pages', 'widgets'] } { name: 'Layout' path: '/partials/help/layout.html' tags: ['layout', 'grid', 'mobile', 'scrolling', 'position', 'absolute'] } { name: 'Parameters' path: '/partials/help/parameters.html' tags: ['parameters'] } { name: 'Scripts' path: '/partials/help/scripts.html' tags: ['scripts', 'javascript'] } { name: 'Styles' path: '/partials/help/styles.html' tags: ['styles', 'css'] } ] } { name: 'Data Sources' path: '/partials/help/dataSources.html' tags: ['data sources', 'dataSources', 'tabular', 'post-processor', 'post processor', 'pre-processor', 'pre processor'] } { name: 'Widgets' path: '/partials/help/widgets.html' tags: ['widgets'] } ] # Formats supported for Dashboard Export exportFormats: [{ label: 'PDF', value: 'pdf' }] # Page settings page: sample: frequency: 1 layout: gridColumns: 2 gridRows: 2 widgets: [] # Widget settings widgets: annotationChart: name: 'annotationChart' label: 'Annotation Chart' icon: 'fa-bar-chart-o' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for this Widget.' placeholder: 'Data Source name' type: 'string' required: true options: datasourceOptions order: 10 xAxis: label: 'X-Axis' description: 'Configuration of the X-axis.' type: 'propertyset' required: true properties: column: label: 'Column Name' description: 'Name of the column in the Data Source used for the x-axis.' placeholder: 'Column Name' inlineJs: true type: 'string' order: 1 format: label: 'Format' description: 'Specifies which format the incoming datetime data is in.' type: 'string' options: date: value: 'date' epoch: value: 'epoch' epochmillis: value: 'epochmillis' string: value: 'string' order: 2 formatString: label: 'Format String' description: 'Used with the String format to specify how the string should be parsed.' type: 'string' order: 3 order: 11 series: label: 'Series' singleLabel: 'series' description: 'One or more series to display in the annotation chart.' type: 'propertyset[]' required: true default: [] order: 12 properties: column: label: 'Column Name' description: 'Name of the column in the Data Source to use as the y-axis value for this series.' placeholder: 'Column Name' inlineJs: true type: 'string' order: 1 label: label: 'Label' description: 'Display label for the series; if omitted, the column name will be used.' placeholder: 'Label' inlineJs: true type: 'string' order: 2 annotationTitleColumn: label: 'Annotation Title Column Name' description: 'Name of the column in the Data Source to use as the title of annotations corresponding to each point.' placeholder: 'Column Name' inlineJs: true type: 'string' order: 3 annotationTextColumn: label: 'Annotation Text Column Name' description: 'Name of the column in the Data Source to use as the text of annotations corresponding to each point.' placeholder: 'Column Name' inlineJs: true type: 'string' order: 4 secondaryAxis: label: 'Secondary Axis' description: 'If true, places the series on a second axis on the left of the chart.' inlineJs: true type: 'boolean' order: 5 options: label: 'Options' description: 'Additional options for the Google Annotation chart. Any supported option is allowed here.' type: 'propertyset' required: false inlineJs: true properties: allValuesSuffix: label: 'All Values Suffix' description: 'A suffix to be added to all values in the legend and tick labels in the vertical axes.' placeholder: 'Suffix' type: 'string' inlineJs: true defaultHidden: true annotationsWidth: label: 'Annotations Width' description: 'The width (in percent) of the annotations area, out of the entire chart area. Must be a number in the range 5-80.' type: 'integer' inlineJs: true defaultHidden: true displayAnnotations: label: 'Display Annotations' description: 'Controls whether annotations are displayed along with the chart.' type: 'boolean' inlineJs: true default: true defaultHidden: true displayAnnotationsFilter: label: 'Display Annotations Filter' description: 'If set to true, the chart will display a filter control to filter annotations.' type: 'boolean' inlineJs: true default: false defaultHidden: true displayDateBarSeparator: label: 'Display Date Bar Separator' description: 'If set to true, the chart will display a small bar separator ( | ) between the series values and the date in the legend.' type: 'boolean' inlineJs: true default: false defaultHidden: true displayLegendDots: label: 'Display Legend Dots' description: 'If set to true, the chart will display dots next to the values in the legend text.' type: 'boolean' inlineJs: true defaultHidden: true displayLegendValues: label: 'Display Legend Values' description: 'If set to true, the chart will display the highlighted values in the legend.' type: 'boolean' inlineJs: true defaultHidden: true displayRangeSelector: label: 'Display Range Selector' description: 'If set to true, the chart will display the zoom range selection area (the area at the bottom of the chart).' type: 'boolean' inlineJs: true defaultHidden: true displayZoomButtons: label: 'Display Zoom Buttons' description: 'If set to true, the chart will display the zoom buttons ("1d 5d 1m" etc).' type: 'boolean' inlineJs: true defaultHidden: true fill: label: 'Fill' description: 'A number from 0—100 (inclusive) specifying the alpha of the fill below each line in the line graph. 100 means 100% opaque, and 0 means no fill at all. The fill color is the same color as the line above it.' type: 'integer' inlineJs: true defaultHidden: true focusTarget: label: 'Focus Target' description: 'Determines whether mouse hover focuses on individual points, or is shared by all series. Defaults to category, unless Annotation editing is enabled, which forces "datum".' type: 'string' inlineJs: true defaultHidden: true default: 'category' options: datum: value: 'datum' category: value: 'category' legendPosition: label: 'Legend Position' description: 'Determines whether the legend is put on the same row as the zoom buttons, or a new row.' type: 'string' inlineJs: true defaultHidden: true options: sameRow: value: 'sameRow' newRow: value: 'newRow' max: label: 'Maximum' description: 'The maximum value to show on the Y-axis. If the maximum data point is less than this value, this setting will be ignored.' type: 'number' inlineJs: true defaultHidden: true min: label: 'Minimum' description: 'The minimum value to show on the Y-axis. If the minimum data point is less than this value, this setting will be ignored.' type: 'number' inlineJs: true defaultHidden: true scaleFormat: label: 'Scale Format' description: 'Number format to be used for the axis tick labels. Format reference: https://developers.google.com/chart/interactive/docs/customizing_axes#number-formats.' placeholder: 'Format' type: 'string' inlineJs: true defaultHidden: true scaleType: label: 'Scale Type' description: 'Sets the maximum and minimum values shown on the Y-axis. Reference: https://developers.google.com/chart/interactive/docs/gallery/annotationchart.' type: 'string' inlineJs: true defaultHidden: true options: maximized: value: 'maximized' fixed: value: 'fixed' allmaximized: value: 'allmaximized' allfixed: value: 'allfixed' thickness: label: 'Thickness' description: 'A number from 0—10 (inclusive) specifying the thickness of the lines, where 0 is the thinnest.' placeholder: 'Thickness' type: 'integer' inlineJs: true defaultHidden: true zoomStartTime: label: 'Zoom Start Time' description: 'Sets the initial start datetime of the selected zoom range. Should be provided as a JavaScript Date.' placeholder: 'Date Time' type: 'datetime' inlineJs: true defaultHidden: true zoomEndTime: label: 'Zoom End Time' description: 'Sets the initial end datetime of the selected zoom range. Should be provided as a JavaScript Date.' placeholder: 'Date Time' type: 'datetime' inlineJs: true defaultHidden: true order: 13 annotationEditing: label: 'Built-In Annotation Editing' description: 'Optional, but if enabled, allows users to create new annotations for points on the chart. Annotations are stored automatically within Cyclotron.' type: 'boolean' required: false default: false order: 13 annotationKey: label: 'Built-In Annotation Key' description: 'Provides a CyclotronData bucket key to be used for built-in annotation editing. This property is automatically initialized with a random UUID.' type: 'string' inlineJs: true required: false defaultHidden: true order: 14 events: label: 'Events' description: 'Optional event handlers for various events.' type: 'propertyset' required: false defaultHidden: true order: 15 properties: rangechange: label: 'Range Change Event' description: 'This event occurs when the user changes the range slider. The new endpoints are available as e.start and e.end.' type: 'editor' editorMode: 'javascript' required: false order: 1 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 20 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' order: 20 # Common options options: displayAnnotations: true # Undocumented "chart" options chart: focusTarget: 'category' sample: -> # Generate new Annotation Chart Widget { annotationKey: uuid.v4() } # Theme-specific options themes: dark: options: dbackgroundColor: '#222222' darkmetro: options: dbackgroundColor: '#202020' ### chart: name: 'chart' label: 'Chart' icon: 'fa-bar-chart-o' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for this Widget.' placeholder: 'Data Source name' type: 'string' required: true options: datasourceOptions order: 10 drilldownDataSource: label: 'Drilldown Data Source' description: 'The name of the Data Source providing drilldown data for this Widget.' placeholder: 'Data Source name' type: 'string' required: false defaultHidden: true options: datasourceOptions order: 11 highchart: label: 'Highchart Definition' description: 'Contains all the options for the chart, in the format expected by Highcharts. Any valid Highcharts properties can be set under this property and will be applied to the chart.' type: 'json' inlineJs: true required: true order: 12 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 13 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' order: 14 addShiftPoints: label: 'Add/Shift Points' description: 'If true, identifies new points on each data reload and appends them to the right side of the chart, shifting points off of the left side. This is ideal for rolling time-series charts with a fixed number of points. The default is false, which forces a complete redraw of all points.' type: 'boolean' default: false required: false order: 15 sample: highchart: series: [{ x: '' y: '' } ] xAxis: [{ type: 'linear' } ] yAxis: [{ title: text: 'Values' } ] themes: light: chart: style: fontFamily: '"Open Sans", sans-serif' drilldown: activeAxisLabelStyle: color: '#333' textDecoration: 'none' plotOptions: series: shadow: false marker: enabled: false states: hover: enabled: true bar: borderWidth: 0 column: borderWidth: 0 pie: borderWidth: 0 title: style: font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 labels: style: fontSize: '11px' title: style: fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null lineWidth: 0 tickWidth: 0 labels: style: fontSize: '11px' title: style: fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 symbolWidth: 40 gto: chart: style: fontFamily: '"Open Sans", sans-serif' plotOptions: series: shadow: false marker: enabled: false states: hover: enabled: true bar: borderWidth: 0 column: borderWidth: 0 pie: borderWidth: 0 title: style: font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 labels: style: fontSize: '11px' title: style: fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null lineWidth: 0 tickWidth: 0 labels: style: fontSize: '11px' title: style: fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 symbolWidth: 40 dark: colors: [ '#007D9D' #Blue '#82B93A' #Green '#E3AAD5' #Pink '#EBDC46' #Yellow '#AC5B41' #Red '#D1D1D0' #Offwhite '#B07288' #Purple ] chart: backgroundColor: null #'#333333' borderWidth: 0 borderRadius: 0 plotBackgroundColor: null plotShadow: false plotBorderWidth: 0 style: fontFamily: '"Open Sans", sans-serif' color: '#FFF' drilldown: activeAxisLabelStyle: color: '#999' textDecoration: 'none' activeDataLabelStyle: color: '#999' textDecoration: 'none' title: style: color: '#FFF' font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: color: '#FFF' font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 lineColor: '#999' tickColor: '#999' labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null gridLineColor: 'rgba(255, 255, 255, .1)' minorGridLineColor: 'rgba(255,255,255,0.07)' lineWidth: 0 tickWidth: 0 labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 itemStyle: color: '#CCC' itemHoverStyle: color: '#FFF' itemHiddenStyle: color: '#333' symbolWidth: 40 labels: style: color: '#CCC' tooltip: backgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, 'rgba(96, 96, 96, .8)'] [1, 'rgba(16, 16, 16, .8)'] ] borderWidth: 0 style: color: '#FFF' plotOptions: series: dataLabels: style: color: '#999' textShadow: false shadow: true marker: enabled: false states: hover: enabled: true bar: borderWidth: 0 column: borderWidth: 0 line: dataLabels: color: '#CCC' marker: lineColor: '#333' pie: borderWidth: 0 dataLabels: color: '#999' fontSize: '14px' spline: marker: lineColor: '#333' scatter: marker: lineColor: '#333' candlestick: lineColor: 'white' toolbar: itemStyle: color: '#CCC' navigation: buttonOptions: symbolStroke: '#DDDDDD' hoverSymbolStroke: '#FFFFFF' theme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#606060'] [0.6, '#333333'] ] stroke: '#000000' # scroll charts rangeSelector: buttonTheme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] stroke: '#000000' style: color: '#CCC' fontWeight: 'bold' states: hover: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#BBB'] [0.6, '#888'] ] stroke: '#000000' style: color: 'white' select: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.1, '#000'] [0.3, '#333'] ] stroke: '#000000' style: color: 'yellow' inputStyle: backgroundColor: '#333' color: 'silver' labelStyle: color: 'silver' navigator: handles: backgroundColor: '#666' borderColor: '#AAA' outlineColor: '#CCC' maskFill: 'rgba(16, 16, 16, 0.5)' series: color: '#7798BF' lineColor: '#A6C7ED' scrollbar: barBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] barBorderColor: '#CCC' buttonArrowColor: '#CCC' buttonBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] buttonBorderColor: '#CCC' rifleColor: '#FFF' trackBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, '#000'] [1, '#333'] ] trackBorderColor: '#666' dark2: colors: [ '#2095F0' #Blue '#FF9A13' #Orange '#FFFF13' #Yellow '#A61DF1' #Purple '#28F712' #Green '#FE131E' #Red '#D1D1D0' #Offwhite ] chart: backgroundColor: null #'#333333' borderWidth: 0 borderRadius: 0 plotBackgroundColor: null plotShadow: false plotBorderWidth: 0 style: fontFamily: '"Open Sans", sans-serif' color: '#FFF' drilldown: activeAxisLabelStyle: color: '#999' textDecoration: 'none' activeDataLabelStyle: color: '#999' textDecoration: 'none' title: style: color: '#FFF' font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: color: '#FFF' font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 lineColor: '#999' tickColor: '#999' labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null gridLineColor: 'rgba(255, 255, 255, .1)' minorGridLineColor: 'rgba(255,255,255,0.07)' lineWidth: 0 tickWidth: 0 labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 itemStyle: color: '#CCC' itemHoverStyle: color: '#FFF' itemHiddenStyle: color: '#333' symbolWidth: 40 labels: style: color: '#CCC' tooltip: backgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, 'rgba(96, 96, 96, .8)'] [1, 'rgba(16, 16, 16, .8)'] ] borderWidth: 0 style: color: '#FFF' plotOptions: series: shadow: true marker: enabled: false states: hover: enabled: true dataLabels: style: color: '#999' textShadow: false bar: borderWidth: 0 column: borderWidth: 0 line: dataLabels: color: '#CCC' marker: lineColor: '#333' pie: borderWidth: 0 dataLabels: color: '#999' fontSize: '14px' spline: marker: lineColor: '#333' scatter: marker: lineColor: '#333' candlestick: lineColor: 'white' toolbar: itemStyle: color: '#CCC' navigation: buttonOptions: symbolStroke: '#DDDDDD' hoverSymbolStroke: '#FFFFFF' theme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#606060'] [0.6, '#333333'] ] stroke: '#000000' # scroll charts rangeSelector: buttonTheme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] stroke: '#000000' style: color: '#CCC' fontWeight: 'bold' states: hover: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#BBB'] [0.6, '#888'] ] stroke: '#000000' style: color: 'white' select: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.1, '#000'] [0.3, '#333'] ] stroke: '#000000' style: color: 'yellow' inputStyle: backgroundColor: '#333' color: 'silver' labelStyle: color: 'silver' navigator: handles: backgroundColor: '#666' borderColor: '#AAA' outlineColor: '#CCC' maskFill: 'rgba(16, 16, 16, 0.5)' series: color: '#7798BF' lineColor: '#A6C7ED' scrollbar: barBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] barBorderColor: '#CCC' buttonArrowColor: '#CCC' buttonBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] buttonBorderColor: '#CCC' rifleColor: '#FFF' trackBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, '#000'] [1, '#333'] ] trackBorderColor: '#666' darkmetro: colors: [ '#007D9D' #Blue '#82B93A' #Green '#E3AAD5' #Pink '#EBDC46' #Yellow '#AC5B41' #Red '#D1D1D0' #Offwhite '#B07288' #Purple ] chart: backgroundColor: null #'#333333' borderWidth: 0 borderRadius: 0 plotBackgroundColor: null plotShadow: false plotBorderWidth: 0 style: fontFamily: '"Open Sans", sans-serif' color: '#FFF' drilldown: activeAxisLabelStyle: color: '#999' textDecoration: 'none' activeDataLabelStyle: color: '#999' textDecoration: 'none' title: style: color: '#FFF' font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: color: '#FFF' font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 lineColor: '#999' tickColor: '#999' labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null gridLineColor: 'rgba(255, 255, 255, .1)' minorGridLineColor: 'rgba(255,255,255,0.07)' lineWidth: 0 tickWidth: 0 labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 itemStyle: color: '#CCC' itemHoverStyle: color: '#FFF' itemHiddenStyle: color: '#333' symbolWidth: 40 labels: style: color: '#CCC' tooltip: backgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, 'rgba(96, 96, 96, .8)'] [1, 'rgba(16, 16, 16, .8)'] ] borderWidth: 0 style: color: '#FFF' plotOptions: series: dataLabels: style: color: '#999' textShadow: false shadow: true marker: enabled: false states: hover: enabled: true bar: borderWidth: 0 column: borderWidth: 0 line: dataLabels: color: '#CCC' marker: lineColor: '#333' pie: borderWidth: 0 dataLabels: color: '#999' fontSize: '14px' spline: marker: lineColor: '#333' scatter: marker: lineColor: '#333' candlestick: lineColor: 'white' toolbar: itemStyle: color: '#CCC' navigation: buttonOptions: symbolStroke: '#DDDDDD' hoverSymbolStroke: '#FFFFFF' theme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#606060'] [0.6, '#333333'] ] stroke: '#000000' # scroll charts rangeSelector: buttonTheme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] stroke: '#000000' style: color: '#CCC' fontWeight: 'bold' states: hover: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#BBB'] [0.6, '#888'] ] stroke: '#000000' style: color: 'white' select: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.1, '#000'] [0.3, '#333'] ] stroke: '#000000' style: color: 'yellow' inputStyle: backgroundColor: '#333' color: 'silver' labelStyle: color: 'silver' navigator: handles: backgroundColor: '#666' borderColor: '#AAA' outlineColor: '#CCC' maskFill: 'rgba(16, 16, 16, 0.5)' series: color: '#7798BF' lineColor: '#A6C7ED' scrollbar: barBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] barBorderColor: '#CCC' buttonArrowColor: '#CCC' buttonBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] buttonBorderColor: '#CCC' rifleColor: '#FFF' trackBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, '#000'] [1, '#333'] ] trackBorderColor: '#666' charcoal: colors: [ '#007D9D' #Blue '#82B93A' #Green '#E3AAD5' #Pink '#EBDC46' #Yellow '#AC5B41' #Red '#D1D1D0' #Offwhite '#B07288' #Purple ] chart: backgroundColor: null #'#333333' borderWidth: 0 borderRadius: 0 plotBackgroundColor: null plotShadow: false plotBorderWidth: 0 style: fontFamily: '"Open Sans", sans-serif' color: '#FFF' drilldown: activeAxisLabelStyle: color: '#999' textDecoration: 'none' activeDataLabelStyle: color: '#999' textDecoration: 'none' title: style: color: '#FFF' font: '16px "Lato", sans-serif' fontWeight: 'bold' subtitle: style: color: '#FFF' font: '12px "Lato", sans-serif' xAxis: gridLineWidth: 0 lineColor: '#999' tickColor: '#999' labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' yAxis: alternateGridColor: null minorTickInterval: null gridLineColor: 'rgba(255, 255, 255, .1)' minorGridLineColor: 'rgba(255,255,255,0.07)' lineWidth: 0 tickWidth: 0 labels: style: color: '#999' fontSize: '11px' title: style: color: '#EEE' fontSize: '14px' fontWeight: '300' legend: borderRadius: 0 borderWidth: 0 itemStyle: color: '#CCC' itemHoverStyle: color: '#FFF' itemHiddenStyle: color: '#333' symbolWidth: 40 labels: style: color: '#CCC' tooltip: backgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, 'rgba(96, 96, 96, .8)'] [1, 'rgba(16, 16, 16, .8)'] ] borderWidth: 0 style: color: '#FFF' plotOptions: series: dataLabels: style: color: '#999' textShadow: false shadow: false marker: enabled: false states: hover: enabled: true bar: borderWidth: 0 column: borderWidth: 0 line: dataLabels: color: '#CCC' marker: lineColor: '#333' pie: borderWidth: 0 dataLabels: color: '#999' fontSize: '14px' spline: marker: lineColor: '#333' scatter: marker: lineColor: '#333' candlestick: lineColor: 'white' toolbar: itemStyle: color: '#CCC' navigation: buttonOptions: symbolStroke: '#DDDDDD' hoverSymbolStroke: '#FFFFFF' theme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#606060'] [0.6, '#333333'] ] stroke: '#000000' # scroll charts rangeSelector: buttonTheme: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] stroke: '#000000' style: color: '#CCC' fontWeight: 'bold' states: hover: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#BBB'] [0.6, '#888'] ] stroke: '#000000' style: color: 'white' select: fill: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.1, '#000'] [0.3, '#333'] ] stroke: '#000000' style: color: 'yellow' inputStyle: backgroundColor: '#333' color: 'silver' labelStyle: color: 'silver' navigator: handles: backgroundColor: '#666' borderColor: '#AAA' outlineColor: '#CCC' maskFill: 'rgba(16, 16, 16, 0.5)' series: color: '#7798BF' lineColor: '#A6C7ED' scrollbar: barBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] barBorderColor: '#CCC' buttonArrowColor: '#CCC' buttonBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0.4, '#888'] [0.6, '#555'] ] buttonBorderColor: '#CCC' rifleColor: '#FFF' trackBackgroundColor: linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 } stops: [ [0, '#000'] [1, '#333'] ] trackBorderColor: '#666' ### gchart: name: 'gchart' label: 'Google Charts' icon: 'fa-rocket' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing table-like data for this Widget.' placeholder: 'Data Source name' type: 'string' required: true options: datasourceOptions order: 10 chartType: label: 'Chart Type' description: 'Type of the chart.' type: 'string' required: true options: AnnotatedTimeLine: value: 'AnnotatedTimeLine' AreaChart: value: 'AreaChart' BarChart: value: 'BarChart' BubbleChart: value: 'BubbleChart' CandlestickChart: value: 'CandlestickChart' ColumnChart: value: 'ColumnChart' ComboChart: value: 'ComboChart' Gauge: value: 'Gauge' GeoChart: value: 'GeoChart' IntensityMap: value: 'IntensityMap' Map: value: 'Map' Histogram: value: 'Histogram' LineChart: value: 'LineChart' OrgChart: value: 'OrgChart' PieChart: value: 'PieChart' ScatterChart: value: 'ScatterChart' SteppedAreaChart: value: 'SteppedAreaChart' Table: value: 'Table' Timeline: value: 'Timeline' TreeMap: value: 'TreeMap' order: 11 options: label: 'Options' description: 'JSON object with configuration options for the chart.' type: 'editor' editorMode: 'javascript' required: false order: 12 columns: label: 'Columns' singleLabel: 'column' description: 'Array of columns of the table-like dataset. If not provided, the column labels will be inferred from the keys of the first dataset object. Note that this property must be used if some columns contain dates, times or datetimes or if the column role should differ from "data" (e.g. for annotations; see https://developers.google.com/chart/interactive/docs/roles).' type: 'propertyset[]' inlineJs: true required: false properties: name: label: 'Name' description: 'Indicates the name of the data source field to use for this column.' type: 'string' inlineJs: true required: true order: 1 type: label: 'Type' description: 'Type of the column values. If omitted, "string" will be assigned.' type: 'string' options: string: value: 'string' number: value: 'number' boolean: value: 'boolean' date: value: 'date' datetime: value: 'datetime' timeofday: value: 'timeofday' order: 2 role: label: 'Role' description: 'Optional role of the column. If omitted, "data" will be assigned. Note that columns with role "annotation" must immediately follow the series column that should be annotated, and columns with role "annotationText" must follow the annotated column.' type: 'string' options: annotation: value: 'annotation' annotationText: value: 'annotationText' order: 3 order: 13 formatters: label: 'Formatters' singleLabel: 'formatter' description: 'Optional JavaScript functions that will be applied to all the values of the specified datasource columns.' type: 'propertyset[]' properties: columnName: label: 'Column Name' description: 'Indicates the name of the datasource column' type: 'string' inlineJs: true order: 1 formatter: label: 'Formatter' description: 'The function must take a single value as argument and return the new value.' type: 'editor' editorMode: 'javascript' required: false order: 2 order: 14 clock: name: 'clock' label: 'Clock' icon: 'fa-clock-o' properties: format: label: 'Format' description: 'Enter time format of your choice. "http://momentjs.com/docs/#/displaying/format/" can help in choosing time formats' type: 'string' default: 'dddd, MMMM Do YYYY, h:mm:ss a' required: false order: 10 timezone: label: 'Time Zone' description: 'Enter time zone of your choice. "http://momentjs.com/timezone/" can help in choosing time zone' required: false type: 'string' order: 11 deckgl: name: 'deckgl' label: 'Deck.gl' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for the layers.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions order: 10 ###mapboxApiAccessToken: label: 'Mapbox Token' description: '' type: 'string' required: false order: 11 mapStyle: label: 'Map Style' description: '' type: 'string' required: false order: 12### viewState: label: 'View State' description: 'viewState property' type: 'propertyset' properties: longitude: label: 'Longitude' description: '' type: 'string' required: true order: 1 latitude: label: 'Latitude' description: '' type: 'string' required: true order: 2 zoom: label: 'Zoom' description: 'Default is 0' type: 'integer' required: false default: 0 order: 3 bearing: label: 'Bearing' description: '' type: 'integer' required: false defaultHidden: true order: 4 pitch: label: 'Pitch' description: '' type: 'integer' required: false defaultHidden: true order: 5 order: 13 additionalDeckProps: label: 'Additional Deck Properties' description: 'Additional supported Deck properties. See https://deck.gl/#/documentation/deckgl-api-reference/deck' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 14 layers: label: 'Layers' singleLabel: 'layer' description: '' type: 'propertyset[]' properties: type: label: 'Type' description: 'The type of layer that will be added to the deck.' type: 'string' required: true options: ArcLayer: value: 'ArcLayer' BitmapLayer: value: 'BitmapLayer' ColumnLayer: value: 'ColumnLayer' GeoJsonLayer: value: 'GeoJsonLayer' GridCellLayer: value: 'GridCellLayer' IconLayer: value: 'IconLayer' LineLayer: value: 'LineLayer' PathLayer: value: 'PathLayer' PointCloudLayer: value: 'PointCloudLayer' PolygonLayer: value: 'PolygonLayer' ScatterplotLayer: value: 'ScatterplotLayer' SolidPolygonLayer: value: 'SolidPolygonLayer' TextLayer: value: 'TextLayer' order: 1 configProperties: label: 'Configuration Properties' description: 'See https://deck.gl/#/documentation/deckgl-api-reference/layers/overview for supported properties. Note that they may vary depending on the layer type.' type: 'editor' editorMode: 'javascript' required: false order: 2 useDataSource: label: 'Use Data Source' description: 'Use the Data Source to provide data for this layer. The data will be used for the first layer found with this property set to true.' type: 'boolean' required: false default: false order: 3 order: 14 header: name: 'header' label: 'Header' icon: 'fa-header' properties: headerTitle: label: 'Header Title' description: 'Contains properties for displaying a title in the header.' type: 'propertyset' order: 10 properties: showTitle: label: 'Show Title' description: 'Determines whether a title will be shown. If the Widget has a Title, it will be shown, otherwise it defaults to the Dashboard\'s Display Name or Name.' type: 'boolean' default: true required: false inlineJs: true order: 1 showPageName: label: 'Show Page Name' description: 'Determines whether the current page name will be shown as part of the title.' type: 'boolean' default: true required: false inlineJs: true order: 2 pageNameSeparator: label: 'Page Name Separator' description: 'Configures a string to use to separate the Dashboard name from the Page name. Defaults to a space.' type: 'string' required: false default: '' inlineJs: true defaultHidden: true order: 3 titleSize: label: 'Title Size' description: 'Sets the font size for the header title (if displayed). Any valid CSS height is allowed.' type: 'string' required: false inlineJs: true order: 5 logoUrl: label: 'Logo URL' description: 'Contains a URL to a dashboard logo to display before the title. Data URLs can be used.' type: 'string' required: false inlineJs: true order: 10 logoSize: label: 'Logo Size' description: 'Sets the height for the header logo (if displayed). The logo will be scaled without changing the aspect ratio. Any valid CSS height is allowed.' type: 'string' required: false inlineJs: true order: 11 link: label: 'Link' description: 'If set, makes the Logo and Title a link to this URL.' type: 'string' required: false inlineJs: true order: 20 parameters: label: 'Parameters' description: 'Contains properties for displaying Dashboard Parameters in the header.' type: 'propertyset' order: 20 properties: showParameters: label: 'Show Parameters' description: 'Determines whether Parameters will be shown.' type: 'boolean' default: false required: false inlineJs: true order: 1 showUpdateButton: label: 'Show Update Button' description: 'If true, an "Update" button will be displayed after the Parameters. The updateEvent property must be used to apply an action to the button click event, else nothing will happen.' type: 'boolean' default: false required: false order: 2 updateButtonLabel: label: 'Update Button Label' description: 'Customizes the label for the Update button, if shown.' type: 'string' default: 'Update' defaultHidden: true required: false order: 2 updateEvent: label: 'Update Button Click Event' description: 'This event occurs when the Update button is clicked, if shown.' type: 'editor' editorMode: 'javascript' required: false order: 10 parametersIncluded: label: 'Included Parameters' description: 'Optionally specifies an array of Parameter names, limiting the Header to only displaying the specified Parameters. This does not override the editInHeader property of each Parameter, which needs to be set true to appear in the Header.' type: 'string[]' required: false defaultHidden: true order: 11 customHtml: label: 'HTML Content' description: 'Provides additional HTML content to be displayed in the header. This can be used to customize the header display.' type: 'editor' editorMode: 'html' required: false inlineJs: true order: 30 html: name: 'html' label: 'HTML' icon: 'fa-html5' properties: dataSource: label: 'Data Source' description: 'Optional; the name of the Data Source providing data for this Widget. If set, the `html` property will be used as a repeater and rendered once for each row.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions order: 10 html: label: 'HTML' description: 'Contains HTML markup to be displayed. If dataSource is set, this HTML will be repeated for each row in the result.' type: 'editor' editorMode: 'html' required: false default: '' order: 11 preHtml: label: 'Pre-HTML' description: 'Optional, contains HTML markup which is displayed before the main body of HTML.' type: 'editor' editorMode: 'html' required: false default: '' order: 12 postHtml: label: 'Post-HTML' description: 'Optional, contains HTML markup which is displayed after the main body of HTML.' type: 'editor' editorMode: 'html' required: false default: '' order: 13 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 14 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' placeholder: 'Column name' type: 'string[]' inlineJs: true required: false order: 15 iframe: name: 'iframe' label: 'iFrame' icon: 'fa-desktop' properties: url: label: 'Url' description: 'Specifies the URL to be loaded within the Widget.' type: 'string' placeholder: 'Url' required: true default: 'http://www.expedia.com' order: 10 refresh: label: 'Refresh' description: 'Optional number of seconds; enables reloading the iframe contents periodically every N seconds.' placeholder: 'Seconds' type: 'integer' required: false order: 11 image: name: 'image' label: 'Image' icon: 'fa-image-o' properties: images: label: 'Images' singleLabel: 'Image' description: 'One or more Images to display in this widget.' type: 'propertyset[]' required: true default: [] order: 10 properties: url: label: 'URL' description: 'URL to the image to be displayed.' placeholder: 'Url' inlineJs: true required: true type: 'string' order: 1 link: label: 'Link' description: 'Optional, specifies a URL that will be opened if the image is clicked on.' placeholder: 'URL' type: 'url' inlineJs: true required: false order: 13 tooltip: label: 'Tooltip' description: 'Sets the tooltip of the image.' placeholder: 'Tooltip' type: 'string' inlineJs: true required: false defaultHidden: true order: 2 backgroundSize: label: 'Background-Size' description: 'Specifies the CSS property background-size, which determines how the image is fit into the Widget.' type: 'string' inlineJs: true required: false defaultHidden: true options: auto: value: 'auto' contain: value: 'contain' cover: value: 'cover' '100%': value: '100%' order: 3 backgroundPosition: label: 'Background Position' description: 'Specifies the CSS property background-position, which determines where the image is positioned in the Widget.' type: 'string' inlineJs: true required: false default: 'center' defaultHidden: true options: center: value: 'center' top: value: 'top' bottom: value: 'bottom' left: value: 'left' right: value: 'right' order: 4 backgroundColor: label: 'Background Color' description: 'Optionally specifies the CSS property background-color, which is drawn behind this image. It may appear if the image does not cover the Widget, or if the image is not opaque.' type: 'string' inlineJs: true required: false defaultHidden: true order: 5 backgroundRepeat: label: 'Background Repeat' description: 'Optionally specifies the CSS property background-repeat, which determiens if or how the image is repeated within the Widget.' type: 'string' inlineJs: true required: false default: 'no-repeat' defaultHidden: true options: 'no-repeat': value: 'no-repeat' 'repeat': value: 'repeat' 'repeat-x': value: 'repeat-x' 'repeat-y': value: 'repeat-y' 'space': value: 'space' 'round': value: 'round' order: 6 filters: label: 'Filters' description: 'Optionally applies one or more CSS filters to the image. If provided, it should be a string containing one or more filters, separated by spaces.' type: 'string' inlineJs: true required: false defaultHidden: true order: 7 duration: label: 'Auto-Rotate Duration' description: 'Optional number of seconds; enables rotating among a set of images periodically.' placeholder: 'Seconds' type: 'integer' default: 0 required: false order: 11 javascript: name: 'javascript' label: 'JavaScript' icon: 'fa-cogs' properties: dataSource: label: 'Data Source' description: 'Optional; the name of the Data Source providing data for this Widget. If set, the data source will be called and the result will be passed to the JavaScript function.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions order: 10 functionName: label: 'Function Name' description: 'JavaScript function name used to create a controller instance. Supports namespaces/drilldown using periods, e.g. Cyclotron.functions.scatterPlot' placeholder: 'Function Name' type: 'string' required: true order: 11 refresh: label: 'Refresh' description: 'Optional; enables re-invoking the javascript object periodically every N seconds.' placeholder: 'Seconds' type: 'integer' required: false order: 12 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 13 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' placeholder: 'Column name' type: 'string[]' inlineJs: true required: false order: 14 linkedWidget: name: 'linkedWidget' label: 'Linked Widget' icon: 'fa-link' properties: linkedWidget: label: 'Linked Widget' description: 'Selects another Widget in this Dashboard to link.' type: 'string' required: true options: linkedWidgetOptions order: 10 number: name: 'number' label: 'Number' icon: 'fa-cog' properties: dataSource: label: 'Data Source' description: 'Optional, but required to use data expressions e.g. "#{columnName}". The name of the Data Source providing data for this Widget.' placeholder: 'Data Source Name' type: 'string' required: false options: datasourceOptions order: 10 numbers: label: 'Numbers' singleLabel: 'number' description: 'One or more Numbers to display in this widget.' type: 'propertyset[]' required: true default: [] order: 11 properties: number: label: 'Number' description: 'Number value or expression.' placeholder: 'Value' inlineJs: true required: false type: 'string' order: 1 prefix: label: 'Prefix' description: 'Optional; specifies a prefix to append to the number.' placeholder: 'Prefix' type: 'string' inlineJs: true order: 2 suffix: label: 'Suffix' description: 'Optional; specifies a suffix to append to the number.' placeholder: 'Suffix' type: 'string' inlineJs: true order: 3 color: label: 'Color' description: 'Sets the color of the number.' placeholder: 'Color' type: 'string' inlineJs: true required: false defaultHidden: true order: 4 tooltip: label: 'Tooltip' description: 'Sets the tooltip of the number.' placeholder: 'Tooltip' type: 'string' inlineJs: true required: false defaultHidden: true order: 5 icon: label: 'Icon' description: 'Optional Font Awesome icon class to be displayed with the number.' placeholder: 'Icon Class' inlineJs: true type: 'string' defaultHidden: true order: 6 iconColor: label: 'Icon Color' description: 'Optionally specifies a color for the icon if the icon property is also set. The value can be a named color (e.g. "red"), a hex color (e.g. "#AA0088") or a data source column/inline javascript (e.g. "#{statusColor}").' type: 'string' inlineJs: true defaultHidden: true order: 7 iconTooltip: label: 'IconTooltip' description: 'Sets the tooltip of the icon.' placeholder: 'Icon Tooltip' type: 'string' inlineJs: true required: false defaultHidden: true order: 8 onClick: label: 'Click Event' description: 'This event occurs when the user clicks on the number. If this property is set with a JavaScript function, the function will be called as an event handler.' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 9 orientation: label: 'Orientation' description: 'Controls the direction in which the numbers are arranged.' type: 'string' required: false default: 'vertical' options: vertical: value: 'vertical' horizontal: value: 'horizontal' order: 12 autoSize: label: 'Auto-Size Numbers' description: 'If true, up to 4 numbers will be automatically sized-to-fit in the Widget. If false, or if there are more than four numbers, all numbers will be listed sequentially.' type: 'boolean' required: false default: true order: 13 link: label: 'Link' description: 'Optional, specifies a URL that will be displayed at the bottom of the widget as a link.' placeholder: 'URL' type: 'url' required: false order: 14 filters: label: 'Filters' description: "Optional, but if provided, specifies name-value pairs used to filter the data source's result set. This has no effect if the dataSource property is not set.\nOnly the first row of the data source is used to get data, so this property can be used to narrow down on the correct row" type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 15 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.\nOnly the first row of the data source is used to get data, so this property can be used to sort the data and ensure the correct row comes first.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' order: 16 openLayersMap: name: 'openLayersMap' label: 'OpenLayers Map' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for the overlays.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions order: 10 center: label: 'Center' description: 'X and Y coordinates to center the map on' type: 'propertyset' required: true properties: x: label: 'X' type: 'string' required: true order: 1 y: label: 'Y' type: 'string' required: true order: 2 order: 11 zoom: label: 'Zoom' description: 'Zoom level (0 is zoomed out)' type: 'integer' required: true order: 12 layers: label: 'Layers' singleLabel: 'layer' description: 'An array of layers that will be added to the map. Default is a single OpenStreetMap (OSM) layer.' type: 'propertyset[]' inlineJs: true properties: type: label: 'Type' description: 'The type of layer that will be added to the map. Specifying a source is mandatory except for VectorTile layers. Heatmap layer also requires Weight to be specified. If no type nor source are specified, Tile and OSM are used.' type: 'string' required: false default: 'Tile' options: image: value: 'Image' tile: value: 'Tile' heatmap: value: 'Heatmap' vector: value: 'Vector' vectortile: value: 'VectorTile' order: 1 source: label: 'Source' description: 'Source for the layer. Please refer to the help page if you do not know which one you need. Note that depending on the layer type (Image, Tile, Heatmap or VectorTile) only a subset of these sources is accepted.' type: 'propertyset' properties: name: label: 'Name' type: 'string' required: false default: 'OSM' options: BingMaps: value: 'BingMaps' CartoDB: value: 'CartoDB' Cluster: value: 'Cluster' ImageArcGISRest: value: 'ImageArcGISRest' ImageCanvas: value: 'ImageCanvas' ImageMapGuide: value: 'ImageMapGuide' ImageStatic: value: 'ImageStatic' ImageWMS: value: 'ImageWMS' OSM: value: 'OSM' Raster: value: 'Raster' Stamen: value: 'Stamen' TileArcGISRest: value: 'TileArcGISRest' TileDebug: value: 'TileDebug' TileJSON: value: 'TileJSON' TileUTFGrid: value: 'TileUTFGrid' TileWMS: value: 'TileWMS' Vector: value: 'Vector' VectorTile: value: 'VectorTile' WMTS: value: 'WMTS' XYZ: value: 'XYZ' Zoomify: value: 'Zoomify' order: 1 configuration: label: 'Configuration' description: 'Configuration object. Please refer to the widget help page to know how to configure each source.' type: 'editor' editorMode: 'javascript' required: false order: 2 order: 2 weight: label: 'Weight (for heatmap)' description: '' type: 'string' required: false order: 3 styleFunction: label: 'Style function' description: 'Style function (for vector layers, see https://openlayers.org/en/v4.6.5/apidoc/ol.html#.StyleFunction). You can specify a style function to be applied when selecting a feature by defining it as "Cyclotron.featureSelectStyleFunction" in the Scripts section, otherwise the default select style will be applied.' type: 'editor' editorMode: 'javascript' required: false order: 4 order: 13 overlayGroups: label: 'Overlay Groups' singleLabel: 'group' description: 'Groups of overlays that will be added to the map, i.e., elements that will be displayed over the map and attached to a given position. Each group of overlays can have one overlay selected at a time.' type: 'propertyset[]' inlineJs: true properties: name: label: 'Name' type: 'string' required: true order: 1 initiallySelected: label: 'Overlay Initially Selected' description: 'Name of the overlay that will be assigned the CSS class on selection when the page is loaded. If not provided, all overlays will have the regular CSS class until one is clicked. Note that to use this field you must provide names for the overlays.' type: 'string' required: false order: 2 overlays: label: 'Overlays' singleLabel: 'overlay' description: '' type: 'propertyset[]' inlineJs: true required: true properties: name: label: 'Name' description: 'Unique identifier for the overlay' type: 'string' required: false order: 1 cssClass: label: 'CSS Class' description: 'CSS class name (defined beforehand in the Styles section of the dashboard) for the overlay' type: 'string' required: true order: 2 cssClassSelected: label: 'CSS Class On Selection' description: 'Optional CSS class name (defined beforehand in the Styles section of the dashboard) for the selected overlay' type: 'string' required: false order: 3 position: label: 'Position' description: 'X and Y coordinates of the location where the overlay will be attached' type: 'propertyset' properties: x: label: 'X' type: 'string' required: false order: 1 y: label: 'Y' type: 'string' required: false order: 2 order: 4 positioning: label: 'Positioning' description: 'Where the overlay is placed with respect to Position. Default is top-left.' type: 'string' required: false default: 'top-left' options: bottomLeft: value: 'bottom-left' bottomCenter: value: 'bottom-center' bottomRight: value: 'bottom-right' centerLeft: value: 'center-left' centerCenter: value: 'center-center' centerRight: value: 'center-right' topLeft: value: 'top-left' topCenter: value: 'top-center' topRight: value: 'top-right' order: 5 template: label: 'Template' description: 'HTML template for overlay content.' type: 'editor' editorMode: 'html' required: false default: '' order: 6 order: 3 order: 15 controls: label: 'Controls' singleLabel: 'control' description: 'An array of controls that will be added to the map.' type: 'propertyset[]' inlineJs: true defaultHidden: true default: [] properties: control: label: 'Control' type: 'string' required: false options: Attribution: value: 'Attribution' MousePosition: value: 'MousePosition' OverviewMap: value: 'OverviewMap' ScaleLine: value: 'ScaleLine' Zoom: value: 'Zoom' ZoomSlider: value: 'ZoomSlider' ZoomToExtent: value: 'ZoomToExtent' order: 1 order: 16 dataSourceMapping: label: 'DataSource Mapping' description: 'Overlay properties must be mapped to datasource fields. The datasource is required to have at least fields for CSS class and the list of overlays.' type: 'propertyset' defaultHidden: true properties: identifierField: label: 'Identifier Field' description: 'Datasource field with a unique identifier for the overlay group. If it is not specified and the datasource provides more that one object (i.e. overlay group), each group will be assigned a random ID.' type: 'string' required: false order: 1 initiallySelectedField: label: 'Overlay Initially Selected Field' description: 'Optional datasource field with the ID of the overlay that will be assigned the CSS class on selection when the page is loaded. If not provided, all overlays will have the regular CSS class until one is clicked.' type: 'string' required: false defaultHidden: true order: 2 overlayListField: label: 'Overlay List Field' description: 'Datasource field containing the list of overlays for the group' type: 'string' required: true order: 3 cssClassField: label: 'CSS Class Field' description: 'Datasource field with the style for each overlay in the group as name of a CSS class defined in the Styles section of the editor.' type: 'string' required: true order: 4 cssClassOnSelectionField: label: 'CSS Class On Selection Field' description: 'Optional datasource field with the CSS class for each overlay after it has been clicked. It must be the name of a CSS class defined in the Styles section of the editor.' type: 'string' required: false defaultHidden: true order: 5 overlayIdField: label: 'Overlay Identifier Field' description: 'Datasource field with a unique identifier for each overlay in the group list. If it is missing, a random ID will be generated.' type: 'string' required: false order: 6 positionField: label: 'Position Field' description: 'Datasource field with an array of coordinates (i.e. [x_coord, y_coord]) for each overlay in the group list. Alternatively, single fields for X and Y can be specified.' type: 'string' required: false order: 7 xField: label: 'X Coordinate Field' description: 'Datasource field with X coordinate for each overlay in the group list.' type: 'string' required: false defaultHidden: true order: 8 yField: label: 'Y Coordinate Field' description: 'Datasource field with Y coordinate for each overlay in the group list.' type: 'string' required: false defaultHidden: true order: 9 positioningField: label: 'Positioning Field' description: 'Datasource field with the positioning (e.g. "center-center") of each overlay.' type: 'string' required: false defaultHidden: true order: 10 templateField: label: 'Template Field' description: 'Datasource field with the HTML template for the content of each overlay.' type: 'string' required: false defaultHidden: true order: 11 order: 14 specificEvents: label: 'Specific Events' singleLabel: 'param-event' description: 'Array of parameters (defined beforehand in the Parameters section of the dashboard) and widget events that can trigger their change.' type: 'propertyset[]' inlineJs: true defaultHidden: true default: [] properties: paramName: label: 'Parameter Name' type: 'string' required: true order: 1 event: label: 'Event' type: 'string' required: true options: clickOnOverlay: value: 'clickOnOverlay' clickOnWMSLayer: value: 'clickOnWMSLayer' selectVectorFeature: value: 'selectVectorFeature' order: 2 section: label: 'Section' description: 'Name of the overlay group that triggers the event, for the event "clickOnOverlay". Name of the WMS layer that triggers the event (e.g. "topp:states"), for the event "clickOnWMSLayer". For other events, you can leave this option empty. For the event "selectVectorFeature", you can set the index (zero-based) of the layer the features should be selected from, so that features of the specified layer will be stored in the parameter, otherwise features of any layer will be stored in the same parameter. Some widgets (e.g. slider) have one section only, i.e. the whole widget triggers the event, while others may have some sections that trigger the same kind of event (e.g. in OpenLayers maps, any overlay group can trigger clickOnOverlay event).' type: 'string' required: false order: 3 order: 17 projection: label: 'Projection' description: 'Projection. Default is EPSG:3857 (Spherical Mercator).' type: 'string' required: false default: 'EPSG:3857' options: 'EPSG:3857': value: 'EPSG:3857' 'EPSG:4326': value: 'EPSG:4326' order: 18 qrcode: name: 'qrcode' label: 'QRcode' icon: 'fa-cogs' properties: text: label: 'Text' description: 'Text content of the generated QR code.' placeholder: 'QR Code Contents' type: 'string' required: false order: 10 maxSize: label: 'Max Size' description: 'Maximum height/width of the QR code.' type: 'integer' required: false order: 11 useUrl: label: 'Use URL' description: 'Overrides the text property and generates a QR code with the current Dashboard\'s URL.' type: 'boolean' default: false required: false order: 12 dataSource: label: 'Data Source' description: 'Optional; specifies the name of a Dashboard data source. If set, the data source will be called and the result will be available for the QR code generation.' placeholder: 'Data Source name' type: 'string' required: false options: datasourceOptions defaultHidden: true order: 13 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false defaultHidden: true order: 14 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' placeholder: 'Column name' type: 'string[]' inlineJs: true required: false defaultHidden: true order: 15 colorDark: label: 'Dark Color' description: 'CSS color name or hex color code, used to draw the dark portions of the QR code.' placeholder: 'CSS color or hex color code' type: 'string' default: '#000000' required: false defaultHidden: true order: 16 colorLight: label: 'Light Color' description: 'CSS color name or hex color code, used to draw the dark portions of the QR code.' placeholder: 'CSS color or hex color code' type: 'string' default: '#ffffff' required: false defaultHidden: true order: 17 sample: text: 'hello' slider: name: 'slider' label: 'Slider' icon: 'fa-bar-chart-o' properties: minValue: label: 'Minimum date-time' description: 'Starting value of the slider' type: 'string' placeholder: 'YYYY-MM-DD HH:mm' required: true order: 10 maxValue: label: 'Maximum date-time' description: 'Ending value of the slider' type: 'string' placeholder: 'YYYY-MM-DD HH:mm' required: true order: 11 momentFormat: label: 'Date-time Format' description: 'Any valid moment() format. Default is YYYY-MM-DD HH:mm.' type: 'string' default: 'YYYY-MM-DD HH:mm' required: false order: 12 step: label: 'Step' description: 'Number of time units (e.g. days) between slider values (default is 1)' type: 'integer' required: false default: 1 order: 13 direction: label: 'Direction' description: 'Left-to-right or right-to-left. Default is left-to-right.' type: 'string' required: false defaultHidden: true default: 'ltr' options: ltr: value: 'ltr' rtl: value: 'rtl' order: 14 orientation: label: 'Orientation' description: 'Horizontal or vertical. Default is horizontal.' type: 'string' required: false defaultHidden: true default: 'horizontal' options: horizontal: value: 'horizontal' vertical: value: 'vertical' order: 15 player: label: 'Player' description: 'Play/pause button for automatic sliding' type: 'propertyset' properties: showPlayer: label: 'Show Player' description: 'Show player. Default is false.' type: 'boolean' required: false default: false order: 1 interval: label: 'Interval' description: 'Seconds between each sliding. Default is 1.' type: 'integer' required: false default: 1 order: 2 startOnPageReady: label: 'Start On Page Ready' description: 'Start the player automatically when the page is loaded' type: 'boolean' required: false default: false order: 3 order: 16 timeUnit: label: 'Time Unit' description: 'Each slider value corresponds to a minute, hour, day or month. Default is days.' type: 'string' required: false defaultHidden: true default: 'days' options: minutes: value: 'minutes' hours: value: 'hours' days: value: 'days' months: value: 'months' order: 17 pips: label: 'Pips' description: 'Scale/points shown near the slider' type: 'propertyset' properties: mode: label: 'Mode' description: 'Determines where to place pips.' type: 'string' required: false default: 'steps' options: range: value: 'range' steps: value: 'steps' positions: value: 'positions' count: value: 'count' values: value: 'values' order: 1 values: label: 'Values' description: 'Additional options for Positions, Count and Values mode. For Count mode provide an integer. For Positions and Values mode provide comma-separated integers.' type: 'string' required: false order: 2 stepped: label: 'Stepped' description: 'Match pips with slider values (default is false)' required: false default: false type: 'boolean' order: 3 density: label: 'Density' description: 'Number of pips in one percent of the slider range (default is 1)' type: 'integer' required: false default: 1 order: 4 format: label: 'Format' description: 'Show pip values in the same format as slider format (default is true)' type: 'boolean' required: false default: true order: 5 order: 18 tooltips: label: 'Tooltips' description: 'Show tooltips (default is false)' type: 'boolean' required: false defaultHidden: true default: false order: 19 twoHandles: label: 'Show Two Handles' description: 'Show two handles instead of one (default is false). In this case automatic sliding cannot be used. The handles will be placed at the first and last steps unless you specify a different position with Initial Handle Position.' type: 'boolean' required: false defaultHidden: true default: false order: 20 handlePosition: label: 'Initial Handle Position' description: 'Initial position of the handle, as a date-time in the same format used for Minimum and Maximum date-time. If the slider has two handles, enter two comma-separated date-times. Inline JavaScript can also be used, e.g. "${Cyclotron.parameters.handlePos}". By default the handle(s) will be positioned at the first (and last) value.' type: 'string' required: false defaultHidden: true order: 21 specificEvents: label: 'Specific Events' singleLabel: 'param-event' description: 'Array of parameters (defined beforehand in the Parameters section of the dashboard) and widget events that can trigger their change.' type: 'propertyset[]' inlineJs: true defaultHidden: true default: [] properties: paramName: label: 'Parameter Name' type: 'string' required: true order: 1 event: label: 'Event' type: 'string' required: true options: dateTimeChange: value: 'dateTimeChange' order: 2 section: label: 'Section' description: 'Specify which handle generates this event. If the slider has only one handle, you can leave this option empty.' type: 'string' default: 'first' required: false options: firstHandle: value: 'first' secondHandle: value: 'second' order: 3 order: 22 stoplight: name: 'stoplight' label: 'Stoplight' icon: 'fa-cog' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for this Widget.' placeholder: 'Data Source Name' type: 'string' required: false options: datasourceOptions order: 10 rules: label: 'Rules' description: 'Contains rule expressions for the different states of the Stoplight. The rules will be evaluated from red to green, and only the first rule that returns true will be enabled' type: 'propertyset' required: true order: 11 properties: green: label: 'Green' description: 'The rule expression evaluated to determine if the green light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.' type: 'string' placeholder: 'Rule Expression' inlineJs: true order: 3 yellow: label: 'Yellow' description: 'The rule expression evaluated to determine if the yellow light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.' type: 'string' placeholder: 'Rule Expression' inlineJs: true order: 2 red: label: 'Red' description: 'The rule expression evaluated to determine if the red light is active. It should be an inline JavaScript expression, e.g. ${true}. It can contain column values using #{name} notation, which will be replaced before executing the JavaScript. It should return true or false, and any non-true value will be treated as false.' type: 'string' placeholder: 'Rule Expression' inlineJs: true order: 1 tooltip: label: 'Tooltip' description: 'Sets the tooltip of the stoplight.' placeholder: 'Tooltip' type: 'string' inlineJs: true required: false defaultHidden: true order: 12 filters: label: 'Filters' description: "Optional, but if provided, specifies name-value pairs used to filter the data source's result set. This has no effect if the dataSource property is not set.\nOnly the first row of the data source is used to get data, so this property can be used to narrow down on the correct row" type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 15 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.\nOnly the first row of the data source is used to get data, so this property can be used to sort the data and ensure the correct row comes first.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' order: 16 table: name: 'table' label: 'Table' icon: 'fa-table' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for this Widget.' placeholder: 'Data Source name' type: 'string' required: true options: datasourceOptions order: 10 columns: label: 'Columns' singleLabel: 'column' description: 'Specifies the columns to display in the table, and their properties. If omitted, the columns will be automatically determined, either using a list of fields provided by the data source, or by looking at the first row.' type: 'propertyset[]' inlineJs: true properties: name: label: 'Name' description: 'Indicates the name of the data source field to use for this column.' type: 'string' inlineJs: true order: 1 label: label: 'Label' description: 'If provided, sets the header text for the column. If omitted, the name will be used. "#value" can be used to reference the "name" property of the column.' type: 'string' inlineJs: true order: 2 text: label: 'Text' description: 'Overrides the text in the cell using this value as an expression.' type: 'string' inlineJs: true defaultHidden: true order: 3 tooltip: label: 'Tooltip' description: 'Optionally specifies a tooltip to display for each cell in the column.' type: 'string' inlineJs: true defaultHidden: true headerTooltip: label: 'Header Tooltip' description: 'Optionally specifies a tooltip to display for the column header. "#value" can be used to reference the "name" property of the column.' type: 'string' inlineJs: true defaultHidden: true onClick: label: 'Click Event' description: 'This event occurs when the user clicks on a cell in this column. If this property is set with a JavaScript function, the function will be called as an event handler.' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true link: label: 'Link' description: 'If provided, the cell text will be made into a link rather than plain text.' type: 'url' inlineJs: true defaultHidden: true openLinksInNewWindow: label: 'Open Links in New Window' description: 'If true, links will open in a new browser window; this is the default.' type: 'boolean' default: true defaultHidden: true numeralformat: label: 'Numeral Format' description: 'Optionally specifies a Numeral.js-compatible format string, used to reformat the column value for display.' type: 'string' inlineJs: true defaultHidden: true image: label: 'Image' description: 'Optionally specifies a URL to an image to display in the column. The URL can be parameterized using any column values.' type: 'url' inlineJs: true defaultHidden: true imageHeight: label: 'Image Height' description: 'Optionally sets the height for the images displayed using the image property. If omitted, each image will be displayed at "1em" (the same height as text in the cell). Any valid CSS value string can be used, e.g. "110%", "20px", etc.' type: 'string' inlineJs: true defaultHidden: true icon: label: 'Icon' description: 'Optionally specifies a Font Awesome icon class to be displayed in the cell.' type: 'string' inlineJs: true defaultHidden: true iconColor: label: 'Icon Color' description: 'Optionally specifies a color for the icon if the icon property is also set. The value can be a named color (e.g. "red"), a hex color (e.g. "#AA0088") or a data source column/inline javascript (e.g. "#{statusColor}").' type: 'string' inlineJs: true defaultHidden: true border: label: 'Border' description: 'Optionally draws a border on either or both sides of the column. If set, this value should be either "left", "right", or "left,right" to indicate on which sides of the column to draw the borders.' type: 'string' inlineJs: true defaultHidden: true group: label: 'Column Group' description: 'Optionally puts the column in a column group. The value must be a string, which will be displayed above all consecutive columns with the same group property. The column group row will not appear unless at least one column has a group specified.' type: 'string' inlineJs: true defaultHidden: true groupRows: label: 'Group Rows' description: 'Optionally combines identical, consecutive values within a column. If set to true, and depending on the sort, repeated values in a column will be combined into a single cell with its rowspan value set. If the rows are separated by a resort, the combined cells will be split apart again. This property can be applied to any column(s) in the table. The default value is false.' type: 'boolean' default: false defaultHidden: true columnSortFunction: label: 'Column Sort Function' description: 'When using wildcard or regex expression in the `name` field, this property optionally provides a sort function used to order the generated columns. This function takes an array of column names and can return a sorted (or modified) array. Example: "${function(columns){return _.sortBy(columns);}}".' type: 'string' inlineJs: true defaultHidden: true columnsIgnored: label: 'Columns Ignored' description: 'When using wildcard or regex expression in the `name` field, this can contain a list of one or more column names that should not be matched.' type: 'string[]' required: false inlineJs: false defaultHidden: true order: 10 sample: name: '' rules: label: 'Rules' singleLabel: 'rule' description: 'Specifies an array of rules that will be run on each row in the table. Style properties can be set for every matching rule, on either the entire row or a subset of columns.' type: 'propertyset[]' inlineJs: true properties: rule: label: 'Rule' description: 'The rule expression evaluated to determine if this rule applies to a row. It can contain column values using #{name} notation. It will be evaluated as javascript, and should return true or false.' type: 'string' required: true inlineJs: true order: 1 columns: label: 'Columns Affected' description: 'Optionally specifies an array of column names, limiting the rule\'s effect to only the cells specified, rather than the entire row.' type: 'string[]' required: false order: 2 columnsIgnored: label: 'Columns Ignored' description: 'Optionally specifies an array of column names that the rule does NOT apply to.' type: 'string[]' required: false order: 3 name: label: 'Name' description: 'Indicates the name of the data source field to use for this column.' type: 'string' inlineJs: true defaultHidden: true 'font-weight': label: 'Font-Weight (CSS)' description: 'CSS setting for `font-weight`' type: 'string' inlineJs: true defaultHidden: true color: label: 'Color (CSS)' description: 'CSS setting for `color`' type: 'string' inlineJs: true defaultHidden: true 'background-color': label: 'Background Color (CSS)' description: 'CSS setting for `background-color`' type: 'string' inlineJs: true defaultHidden: true order: 11 sample: rule: 'true' freezeHeaders: label: 'Freeze Headers' description: 'Enables frozen headers at the top of the widget when scrolling' type: 'boolean' default: false required: false order: 12 omitHeaders: label: 'Omit Headers' description: 'Disables the table header row' type: 'boolean' default: false required: false order: 13 enableSort: label: 'Enable Sort' description: 'Enable or disable user sort controls' type: 'boolean' default: true required: false order: 14 rowHeight: label: 'Minimum Row Height' description: 'Specifies the (minimum) height in pixels of all rows (including the header row). The actual height of a row may be greater than this value, depending on the contents. If this is not set, each row will automatically size to its contents.' type: 'integer' required: false order: 15 pagination: label: 'Pagination' description: 'Controls pagination of the Table.' type: 'propertyset' required: false defaultHidden: true order: 16 properties: enabled: label: 'Enable Pagination' description: 'Enables or disables pagination for this Table Widget.' type: 'boolean' default: false required: false order: 1 autoItemsPerPage: label: 'Auto Items Per Page' description: 'Enables automatic detection of the number of rows to display in order to fit in the widget dimensions. Requires rowHeight property to be configured to work accurately. To manually size, set false and configure itemsPerPage instead.' type: 'boolean' default: true required: false order: 2 itemsPerPage: label: 'Items Per Page' description: 'Controls how many row are displayed on each page. If autoItemsPerPage is true, this is ignored.' type: 'integer' required: false order: 3 belowPagerMessage: label: 'Below Pager Message' description: 'If set, displays a message below the pager at the bottom of the Widget. The following variables can be used: #{itemsPerPage}, #{totalItems}, #{currentPage}.' type: 'string' required: false order: 4 filters: label: 'Filters' description: 'Optional, but if provided, specifies name-value pairs used to filter the data source\'s result set. Each key specifies a column in the data source, and the value specifies either a single value (string) or a set of values (array of strings). Only rows which have the specifies value(s) will be permitted.' type: 'hash' inlineJsKey: true inlineJsValue: true required: false order: 17 sortBy: label: 'Sort By' description: 'Optional, specifies the field(s) to sort the data by. If the value is a string, it will sort by that single field. If it is an array of strings, multiple fields will be used to sort, with left-to-right priority. The column name can be prefixed with a + or a - sign to indicate the direction or sort. + is ascending, while - is descending. The default sort direction is ascending, so the + sign does not need to be used. If this property is omitted, the original sort order of the data will be used.' type: 'string[]' inlineJs: true required: false placeholder: 'Column name' order: 18 sortFunction: label: 'Sort Function' description: 'Optional, specifies an alternative function to the default sort implementation.' placeholder: 'JavaScript Function' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 19 onSort: label: 'Sort Event' description: 'This event occurs when the user changes the sort order of a column. If this property is set with a JavaScript function, the function will be called as an event handler. Return false from the function to prevent the default sort implementation from being applied.' type: 'editor' editorMode: 'javascript' required: false defaultHidden: true order: 20 tableau: name: 'tableau' label: 'Tableau' icon: 'fa-cog' properties: params: label: 'Parameters' description: 'An object of key-value pairs that Tableau uses to render the report. These parameters are specific to Tableau and will be passed-through to the view.' type: 'hash' required: true editorMode: 'json' order: 10 treemap: name: 'treemap' label: 'Treemap' icon: 'fa-tree' properties: dataSource: label: 'Data Source' description: 'The name of the Data Source providing data for this Widget.' placeholder: 'Data Source name' type: 'string' required: true options: datasourceOptions order: 10 labelProperty: label: 'Label Property' description: 'The name of the property to use as the label of each item.' type: 'string' inlineJs: true required: false default: 'name' defaultHidden: true order: 11 valueProperty: label: 'Value Property' description: 'The name of the property to use to calculate the size of each item.' type: 'string' inlineJs: true required: false default: 'value' defaultHidden: true order: 12 valueDescription: label: 'Value Description' description: 'A short description of the property used to calculate the size of each item. Used in tooltips.' type: 'string' inlineJs: true required: false defaultHidden: true order: 13 valueFormat: label: 'Value Format' description: 'Specifies a Numeral.js-compatible format string used to format the label of the size value.' type: 'string' default: ',.2f' required: false defaultHidden: true inlineJs: true options: default: value: '0,0.[0]' percent: value: '0,0%' integer: value: '0,0' currency: value: '$0,0' order: 14 colorProperty: label: 'Color Property' description: 'The name of the property to use to calculate the color of each item. If omitted, the TreeMap will not be colored.' type: 'string' inlineJs: true required: false default: 'color' order: 15 colorDescription: label: 'Color Description' description: 'A short description of the property used to calculate the color of each item. Used in tooltips.' type: 'string' inlineJs: true required: false defaultHidden: true order: 16 colorFormat: label: 'Color Format' description: 'Specifies a Numeral.js-compatible format string used to format the label of the color value.' type: 'string' default: ',.2f' required: false defaultHidden: true inlineJs: true options: default: value: '0,0.[0]' percent: value: '0,0%' integer: value: '0,0' currency: value: '$0,0' large: value: '0a' order: 17 colorStops: label: 'Color Stops' singleLabel: 'color' description: 'Specifies a list of color stops used to build a gradient.' type: 'propertyset[]' inlineJs: true properties: value: label: 'Value' description: 'The numerical value assigned to this color stop.' type: 'number' required: true inlineJs: true order: 1 color: label: 'Color' description: 'The color to display at this color stop. Hex codes or CSS colors are permitted.' type: 'string' required: false inlineJs: true order: 2 order: 18 showLegend: label: 'Show Legend' description: 'Enables or disables the color legend.' type: 'boolean' default: true required: false order: 19 legendHeight: label: 'Legend Height' description: 'Specifies the height of the legend in pixels.' type: 'number' default: 30 required: false defaultHidden: true order: 20 widgetContainer: name: 'widgetContainer' label: 'Widget Container' icon: 'fa-desktop' properties: layout: label: 'Layout' description: 'Contains properties for configuring the Container layout and dimensions.' type: 'propertyset' default: {} required: false properties: gridColumns: label: 'Grid Columns' description: 'Specifies the total number of horizonal grid squares available in the grid. The grid squares will be scaled to fit the container. If omitted, the number of columns will be calculated dynamically.' type: 'integer' required: false order: 0 gridRows: label: 'Grid Rows' description: 'Specifies the total number of vertical grid squares available in the grid. The grid squares will be scaled vertically to fit the container. If omitted, the grid squares will be literally square, e.g. the height and width will be the same. When omitted, the widgets may not fill the entire container, or they may scroll vertically. Use this property to make widgets scale vertically to fit the container.' type: 'integer' required: false order: 1 gridWidthAdjustment: label: 'Grid Container Width Adjustment' description: 'Specifies an adjustment (in pixels) to the width of the container when calculating the grid layout. If the value is positive, the container width will have the adjustment added to it (making each column wider), whereas if it is negative, the container width will be reduced (making each column skinnier).' type: 'integer' default: 0 required: false defaultHidden: true order: 2 gridHeightAdjustment: label: 'Grid Container Height Adjustment' description: 'Specifies an adjustment (in pixels) to the height of the container when calculating the grid layout. If the value is positive, the container height will have the adjustment added to it (making each row taller), whereas if it is negative, the container height will be reduced (making each row shorter).' type: 'integer' default: 0 required: false order: 3 gutter: label: 'Gutter' description: 'Controls the space (in pixels) between widgets positioned in the grid. The default value is 10.' type: 'integer' default: 10 required: false defaultHidden: true order: 5 borderWidth: label: 'Border Width' description: 'Specifies the pixel width of the border around each widget. Can be set to 0 to remove the border. If omitted, the theme default will be used.' type: 'integer' default: null required: false defaultHidden: true order: 6 margin: label: 'Margin' description: 'Controls the empty margin width (in pixels) around the outer edge of the container. Can be set to 0 to remove the margin.' type: 'integer' default: 10 required: false defaultHidden: true order: 7 scrolling: label: 'Scrolling Enabled' description: 'Enables vertical scrolling of the container to display content longer than the current size.' type: 'boolean' default: true required: false defaultHidden: true order: 8 order: 10 sample: layout: gridColumns: 2 gridRows: 2 youtube: name: 'youtube' label: 'YouTube' icon: 'fa-youtube' properties: videoId: label: 'Video / Playlist ID' description: 'A YouTube video ID or Playlist ID. Multiple video IDs can be separated by commas.' type: 'string' inlineJs: true placeholder: 'ID' required: true order: 10 autoplay: label: 'Auto-Play' description: 'If true, automatically plays the video when the Widget is loaded.' type: 'boolean' inlineJs: true default: true required: false order: 13 loop: label: 'Loop' description: 'If true, automatically loops the video when it completes.' type: 'boolean' inlineJs: true default: true required: false order: 14 enableKeyboard: label: 'Enable Keyboard' description: 'If true, enables keyboard controls which are disabled by default.' type: 'boolean' inlineJs: true default: false required: false defaultHidden: true order: 15 enableControls: label: 'Enable Controls' description: 'If true, enables on-screen video controls which are disabled by default.' type: 'boolean' inlineJs: true default: false required: false defaultHidden: true order: 16 showAnnotations: label: 'Show Annotations' description: 'If true, displays available annotations over the video.' type: 'boolean' inlineJs: true default: false required: false defaultHidden: true order: 17 showRelated: label: 'Show Related' description: 'If true, displays related videos at the end of this video.' type: 'boolean' inlineJs: true default: false required: false defaultHidden: true order: 18 } # Copy Theme options to inherited locations exports.dashboard.properties.pages.properties.theme.options = exports.dashboard.properties.theme.options exports.dashboard.properties.pages.properties.widgets.properties.theme.options = exports.dashboard.properties.theme.options exports.dashboard.properties.pages.properties.themeVariant.options = exports.dashboard.properties.themeVariant.options exports.dashboard.properties.pages.properties.widgets.properties.themeVariant.options = exports.dashboard.properties.themeVariant.options # Copy Style options to inherited locations exports.dashboard.properties.pages.properties.style.options = exports.dashboard.properties.style.options # Table Widget: Column properties duplicated in Rules: tableProperties = exports.widgets.table.properties _.defaults tableProperties.rules.properties, _.omit(tableProperties.columns.properties, 'label') # Copy some chart themes #exports.widgets.chart.themes.lightborderless = exports.widgets.chart.themes.light # Populate Help tags with properties helpDashboards = _.find(exports.help, { name: 'Dashboards' }) helpDashboards.tags = _.union helpDashboards.tags, _.map exports.dashboard.properties, (value, name) -> name helpDataSources = _.find(exports.help, { name: 'Data Sources' }) helpDataSources.tags = _.union helpDataSources.tags, _.map exports.dashboard.properties.dataSources.properties, (value, name) -> name helpWidgets = _.find(exports.help, { name: 'Widgets' }) helpWidgets.tags = _.union helpWidgets.tags, _.map exports.dashboard.properties.pages.properties.widgets.properties, (value, name) -> name propertyMapHelper = (value, name) -> v = _.cloneDeep value v.name = name v # Add Widget and Data Source help pages helpDataSources.children = _.map _.sortBy(exports.dashboard.properties.dataSources.options, 'name'), (dataSource) -> { name: dataSource.label || dataSource.value path: '/partials/help/datasources/' + dataSource.value + '.html' tags: _.map dataSource.properties, propertyMapHelper } helpWidgets.children = _.map _.sortBy(exports.widgets, 'name'), (widget) -> { name: widget.label || widget.name path: '/widgets/' + widget.name + '/help.html' tags: _.map widget.properties, propertyMapHelper } return exports
[ { "context": "\n\ninit = ->\n localCheckKeys = [0..3].map (i) -> \"localCheck#{i}\"\n sessionCheckKeys = [0..3].map (i) -> \"sessio", "end": 143, "score": 0.8209242224693298, "start": 131, "tag": "KEY", "value": "localCheck#{" }, { "context": "heck#{i}\"\n sessionCheckKeys = [0..3].map (i) -> \"sessionCheck#{i}\"\n\n $('body').append R.div [\n R.h1 \"Local Ch", "end": 201, "score": 0.8320443630218506, "start": 187, "tag": "KEY", "value": "sessionCheck#{" } ]
src/sample.coffee
rmehlinger/bobtail-storage
1
{rx, rxStorage} = window {bind} = rx {local, session} = rxStorage R = rx.rxt.tags init = -> localCheckKeys = [0..3].map (i) -> "localCheck#{i}" sessionCheckKeys = [0..3].map (i) -> "sessionCheck#{i}" $('body').append R.div [ R.h1 "Local Checks" R.div localCheckKeys.map (key) -> R.div [ R.label [ key " " R.input { type: 'checkbox' change: -> local.setItem(key, not local.getItem(key)) checked: bind -> !!local.getItemBind(key).get() } ] ] R.button {type: 'button', click: -> local.clear()}, "Clear" R.h1 "Session Checks" R.div sessionCheckKeys.map (key) -> R.div [ R.label rx.flatten [ key " " R.input { type: 'checkbox' click: -> session.setItem(key, not session.getItem(key)) checked: bind -> !!session.getItemBind(key).get() } " " R.span bind -> "#{session.getItemBind(key).get()}" ] ] R.button {type: 'button', click: -> session.clear()}, "Clear" ] init()
39565
{rx, rxStorage} = window {bind} = rx {local, session} = rxStorage R = rx.rxt.tags init = -> localCheckKeys = [0..3].map (i) -> "<KEY>i}" sessionCheckKeys = [0..3].map (i) -> "<KEY>i}" $('body').append R.div [ R.h1 "Local Checks" R.div localCheckKeys.map (key) -> R.div [ R.label [ key " " R.input { type: 'checkbox' change: -> local.setItem(key, not local.getItem(key)) checked: bind -> !!local.getItemBind(key).get() } ] ] R.button {type: 'button', click: -> local.clear()}, "Clear" R.h1 "Session Checks" R.div sessionCheckKeys.map (key) -> R.div [ R.label rx.flatten [ key " " R.input { type: 'checkbox' click: -> session.setItem(key, not session.getItem(key)) checked: bind -> !!session.getItemBind(key).get() } " " R.span bind -> "#{session.getItemBind(key).get()}" ] ] R.button {type: 'button', click: -> session.clear()}, "Clear" ] init()
true
{rx, rxStorage} = window {bind} = rx {local, session} = rxStorage R = rx.rxt.tags init = -> localCheckKeys = [0..3].map (i) -> "PI:KEY:<KEY>END_PIi}" sessionCheckKeys = [0..3].map (i) -> "PI:KEY:<KEY>END_PIi}" $('body').append R.div [ R.h1 "Local Checks" R.div localCheckKeys.map (key) -> R.div [ R.label [ key " " R.input { type: 'checkbox' change: -> local.setItem(key, not local.getItem(key)) checked: bind -> !!local.getItemBind(key).get() } ] ] R.button {type: 'button', click: -> local.clear()}, "Clear" R.h1 "Session Checks" R.div sessionCheckKeys.map (key) -> R.div [ R.label rx.flatten [ key " " R.input { type: 'checkbox' click: -> session.setItem(key, not session.getItem(key)) checked: bind -> !!session.getItemBind(key).get() } " " R.span bind -> "#{session.getItemBind(key).get()}" ] ] R.button {type: 'button', click: -> session.clear()}, "Clear" ] init()
[ { "context": "#\n# grunt-xml-validator\n# https://github.com/panzic/grunt-xml-validator\n#\n# Copyright (c) 2014 Carlo ", "end": 51, "score": 0.9995267987251282, "start": 45, "tag": "USERNAME", "value": "panzic" }, { "context": "/panzic/grunt-xml-validator\n#\n# Copyright (c) 2014 Carlo 'kj'\n# Licensed under the MIT license.\n#\n\nmodule.", "end": 100, "score": 0.9996388554573059, "start": 95, "tag": "NAME", "value": "Carlo" }, { "context": "grunt-xml-validator\n#\n# Copyright (c) 2014 Carlo 'kj'\n# Licensed under the MIT license.\n#\n\nmodule.expo", "end": 104, "score": 0.9988921880722046, "start": 102, "tag": "USERNAME", "value": "kj" } ]
tasks/xml_validator.coffee
gruntjs-updater/grunt-xml-validator
0
# # grunt-xml-validator # https://github.com/panzic/grunt-xml-validator # # Copyright (c) 2014 Carlo 'kj' # Licensed under the MIT license. # module.exports = (grunt) -> grunt.registerMultiTask('xml_validator', 'Grunt plugin to validate XML files', () -> DOMParser = require('xmldom').DOMParser valid = 0 fail = false this.filesSrc.forEach( (f) -> xml = grunt.file.read(f) doc = new DOMParser({ locator:{}, errorHandler: (level, msg) -> fail = true grunt.log.error f + "\tnot valid" }).parseFromString(xml,'text/xml') ) if fail grunt.fail.warn 'Some files are not valid' else grunt.log.ok this.filesSrc.length + ' files valid' )
40054
# # grunt-xml-validator # https://github.com/panzic/grunt-xml-validator # # Copyright (c) 2014 <NAME> 'kj' # Licensed under the MIT license. # module.exports = (grunt) -> grunt.registerMultiTask('xml_validator', 'Grunt plugin to validate XML files', () -> DOMParser = require('xmldom').DOMParser valid = 0 fail = false this.filesSrc.forEach( (f) -> xml = grunt.file.read(f) doc = new DOMParser({ locator:{}, errorHandler: (level, msg) -> fail = true grunt.log.error f + "\tnot valid" }).parseFromString(xml,'text/xml') ) if fail grunt.fail.warn 'Some files are not valid' else grunt.log.ok this.filesSrc.length + ' files valid' )
true
# # grunt-xml-validator # https://github.com/panzic/grunt-xml-validator # # Copyright (c) 2014 PI:NAME:<NAME>END_PI 'kj' # Licensed under the MIT license. # module.exports = (grunt) -> grunt.registerMultiTask('xml_validator', 'Grunt plugin to validate XML files', () -> DOMParser = require('xmldom').DOMParser valid = 0 fail = false this.filesSrc.forEach( (f) -> xml = grunt.file.read(f) doc = new DOMParser({ locator:{}, errorHandler: (level, msg) -> fail = true grunt.log.error f + "\tnot valid" }).parseFromString(xml,'text/xml') ) if fail grunt.fail.warn 'Some files are not valid' else grunt.log.ok this.filesSrc.length + ' files valid' )
[ { "context": "s\",\"Prov\",\"Eccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"", "end": 505, "score": 0.7875741124153137, "start": 502, "tag": "NAME", "value": "Dan" }, { "context": "ov\",\"Eccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"", "end": 511, "score": 0.6822482347488403, "start": 508, "tag": "NAME", "value": "Hos" }, { "context": "ccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"", "end": 518, "score": 0.8667248487472534, "start": 514, "tag": "NAME", "value": "Joel" }, { "context": "ong\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\"", "end": 522, "score": 0.5914613604545593, "start": 521, "tag": "NAME", "value": "A" }, { "context": "sa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",", "end": 530, "score": 0.5909179449081421, "start": 528, "tag": "NAME", "value": "Ob" }, { "context": "r\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Mat", "end": 540, "score": 0.867041826248169, "start": 535, "tag": "NAME", "value": "Jonah" }, { "context": ",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Ma", "end": 546, "score": 0.8278610110282898, "start": 543, "tag": "NAME", "value": "Mic" }, { "context": "\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",", "end": 550, "score": 0.6545009016990662, "start": 549, "tag": "NAME", "value": "N" }, { "context": "d\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",", "end": 584, "score": 0.6286935210227966, "start": 581, "tag": "NAME", "value": "Mal" }, { "context": "nah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",", "end": 591, "score": 0.933052659034729, "start": 587, "tag": "NAME", "value": "Matt" }, { "context": "ic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",\"Gal\",\"", "end": 598, "score": 0.9536579251289368, "start": 594, "tag": "NAME", "value": "Mark" }, { "context": "h\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",\"Gal\",\"Eph\",\"P", "end": 605, "score": 0.8748087882995605, "start": 601, "tag": "NAME", "value": "Luke" }, { "context": "\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",\"2Cor\",\"Gal\",\"Eph\",\"Phil\",\"C", "end": 612, "score": 0.7192676663398743, "start": 608, "tag": "NAME", "value": "John" }, { "context": "\").osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse(\"1. Mosebok 1:1\").osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse", "end": 2992, "score": 0.6806564927101135, "start": 2985, "tag": "NAME", "value": "Mosebok" }, { "context": ".osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse(\"1. Mosebók 1:1\").osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse", "end": 3054, "score": 0.7303563356399536, "start": 3048, "tag": "NAME", "value": "osebók" }, { "context": ".osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse(\"1. Mósebok 1:1\").osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse", "end": 3116, "score": 0.7420722842216492, "start": 3110, "tag": "NAME", "value": "ósebok" }, { "context": ".osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse(\"1. Mósebók 1:1\").osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.", "end": 3173, "score": 0.5536195635795593, "start": 3172, "tag": "NAME", "value": "ó" }, { "context": "s()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse(\"1. Mósebók 1:1\").osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse", "end": 3178, "score": 0.5458160638809204, "start": 3176, "tag": "NAME", "value": "ók" }, { "context": "\").osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse(\"I. Mosebok 1:1\").osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse", "end": 3240, "score": 0.7670890688896179, "start": 3233, "tag": "NAME", "value": "Mosebok" }, { "context": ".osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse(\"I. Mosebók 1:1\").osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.pa", "end": 3299, "score": 0.5615007877349854, "start": 3296, "tag": "NAME", "value": "ose" }, { "context": "s()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse(\"I. Mosebók 1:1\").osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse", "end": 3302, "score": 0.5187076330184937, "start": 3300, "tag": "NAME", "value": "ók" }, { "context": "\").osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse(\"I. Mósebok 1:1\").osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse", "end": 3364, "score": 0.6457633972167969, "start": 3357, "tag": "NAME", "value": "Mósebok" }, { "context": ".osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.parse(\"I. Mósebók 1:1\").osis()).toEqual(\"Gen.1.1\")\n\t\texpect(p.", "end": 3421, "score": 0.6068214774131775, "start": 3420, "tag": "NAME", "value": "ó" }, { "context": "andle book: Rev (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Opinberunarbok Johannesar 1:1\").osis()).toEqual(\"Rev.1", "end": 26428, "score": 0.5688631534576416, "start": 26426, "tag": "NAME", "value": "in" }, { "context": "1\").osis()).toEqual(\"Deut.1.1\")\n\t\texpect(p.parse(\"V. Mosebok 1:1\").osis()).toEqual(\"Deut.1.1\")\n\t\texpect(p.pars", "end": 29528, "score": 0.8840125203132629, "start": 29518, "tag": "NAME", "value": "V. Mosebok" }, { "context": "1\").osis()).toEqual(\"Deut.1.1\")\n\t\texpect(p.parse(\"V. Mosebók 1:1\").osis()).toEqual(\"Deut.1.1\")\n\t\texpect(p.pars", "end": 29591, "score": 0.8118930459022522, "start": 29581, "tag": "NAME", "value": "V. Mosebók" }, { "context": "1\").osis()).toEqual(\"Deut.1.1\")\n\t\texpect(p.parse(\"V. Mósebok 1:1\").osis()).toEqual(\"Deut.1.1\")\n\t\texpect(p.pars", "end": 29654, "score": 0.8825973868370056, "start": 29644, "tag": "NAME", "value": "V. Mósebok" }, { "context": "1\").osis()).toEqual(\"Deut.1.1\")\n\t\texpect(p.parse(\"V. Mósebók 1:1\").osis()).toEqual(\"Deut.1.1\")\n\t\texpect(p.pars", "end": 29717, "score": 0.8812154531478882, "start": 29707, "tag": "NAME", "value": "V. Mósebók" }, { "context": "al(\"Deut.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Josh (is)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_pa", "end": 33087, "score": 0.9691672325134277, "start": 33083, "tag": "NAME", "value": "Josh" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Josh (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Josuabok 1:1\").os", "end": 33346, "score": 0.9673791527748108, "start": 33342, "tag": "NAME", "value": "Josh" }, { "context": "handle book: 1Sam (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Fyrri Samuelsbok 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars", "end": 41022, "score": 0.966768205165863, "start": 41006, "tag": "NAME", "value": "Fyrri Samuelsbok" }, { "context": "1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"Fyrri Samuelsbók 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars", "end": 41091, "score": 0.9198604822158813, "start": 41075, "tag": "NAME", "value": "Fyrri Samuelsbók" }, { "context": "1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"Fyrri Samúelsbok 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars", "end": 41160, "score": 0.9636103510856628, "start": 41144, "tag": "NAME", "value": "Fyrri Samúelsbok" }, { "context": "1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"Fyrri Samúelsbók 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars", "end": 41229, "score": 0.8769396543502808, "start": 41213, "tag": "NAME", "value": "Fyrri Samúelsbók" }, { "context": ").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"1. Sam 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars", "end": 41288, "score": 0.670917272567749, "start": 41285, "tag": "NAME", "value": "Sam" }, { "context": ").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"I. Sam 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars", "end": 41347, "score": 0.7411487698554993, "start": 41344, "tag": "NAME", "value": "Sam" }, { "context": "al(\"Ezek.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Dan (is)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_pa", "end": 59802, "score": 0.8253827095031738, "start": 59799, "tag": "NAME", "value": "Dan" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Dan (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Daniel 1:1\").osis", "end": 60060, "score": 0.9658844470977783, "start": 60057, "tag": "NAME", "value": "Dan" }, { "context": " handle book: Dan (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Daniel 1:1\").osis()).toEqual(\"Dan.1.1\")\n\t\texpect(p.parse", "end": 60099, "score": 0.6390831470489502, "start": 60093, "tag": "NAME", "value": "Daniel" }, { "context": "al(\"Obad.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Jonah (is)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_pa", "end": 63673, "score": 0.9493441581726074, "start": 63668, "tag": "NAME", "value": "Jonah" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Jonah (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Jonah 1:1\").osis(", "end": 63933, "score": 0.9184558987617493, "start": 63928, "tag": "NAME", "value": "Jonah" }, { "context": "andle book: Jonah (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Jonah 1:1\").osis()).toEqual(\"Jonah.1.1\")\n\t\texpect(p.par", "end": 63971, "score": 0.9267195463180542, "start": 63966, "tag": "NAME", "value": "Jonah" }, { "context": "\").osis()).toEqual(\"Jonah.1.1\")\n\t\texpect(p.parse(\"Jonas 1:1\").osis()).toEqual(\"Jonah.1.1\")\n\t\texpect(p.par", "end": 64030, "score": 0.807546854019165, "start": 64025, "tag": "NAME", "value": "Jonas" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Mic (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Mika 1:1\").osis", "end": 64854, "score": 0.5766881704330444, "start": 64853, "tag": "NAME", "value": "M" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Mal (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Malaki 1:1\").osis", "end": 69302, "score": 0.8713130354881287, "start": 69299, "tag": "NAME", "value": "Mal" }, { "context": "ual(\"Mal.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Matt (is)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_pa", "end": 69728, "score": 0.7979542016983032, "start": 69724, "tag": "NAME", "value": "Matt" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Matt (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Matteusarguðspjal", "end": 69987, "score": 0.8505967855453491, "start": 69983, "tag": "NAME", "value": "Matt" }, { "context": "al(\"Mark.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Luke (is)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv", "end": 71173, "score": 0.8623789548873901, "start": 71172, "tag": "NAME", "value": "L" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Luke (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Lukasarguðspja", "end": 71432, "score": 0.7237085700035095, "start": 71431, "tag": "NAME", "value": "L" }, { "context": "p.include_apocrypha true\n\tit \"should handle book: 1John (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Fyrsta bref J", "end": 72390, "score": 0.5218369960784912, "start": 72389, "tag": "NAME", "value": "1" }, { "context": "is()).toEqual(\"2John.1.1\")\n\t\texpect(p.parse(\"Annað Jóhannesarbréf 1:1\").osis()).toEqual(\"2John.1.1\")\n\t\texpect(p", "end": 76292, "score": 0.6852244734764099, "start": 76282, "tag": "NAME", "value": "Jóhannesar" }, { "context": "ual(\"Eph.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Phil (is)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_pa", "end": 94609, "score": 0.895246684551239, "start": 94605, "tag": "NAME", "value": "Phil" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Phil (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Bref Pals til Fil", "end": 94868, "score": 0.9502260088920593, "start": 94864, "tag": "NAME", "value": "Phil" }, { "context": "p.include_apocrypha true\n\tit \"should handle book: 2Tim (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Siðara bref Pa", "end": 112751, "score": 0.522252082824707, "start": 112750, "tag": "NAME", "value": "2" }, { "context": "s (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Hið almenna bref Jakobs 1:1\").osis()).toEqual(\"Jas.1.1\")\n\t\texpect(p.", "end": 141004, "score": 0.7412934899330139, "start": 141003, "tag": "NAME", "value": "J" }, { "context": "qual(\"Jas.1.1\")\n\t\texpect(p.parse(\"Hið almenna bréf Jakobs 1:1\").osis()).toEqual(\"Jas.1.1\")\n\t\texpect(p.pa", "end": 141081, "score": 0.6929947137832642, "start": 141078, "tag": "NAME", "value": "Jak" }, { "context": "pocrypha(false)\n\t\texpect(p.parse(\"HIÐ ALMENNA BREF JAKOBS 1:1\").osis()).toEqual(\"Jas.1.1\")\n\t\texpect(p.", "end": 141421, "score": 0.8057407140731812, "start": 141420, "tag": "NAME", "value": "J" }, { "context": "al(\"1Pet.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Jude (is)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_pa", "end": 148167, "score": 0.9834105372428894, "start": 148163, "tag": "NAME", "value": "Jude" }, { "context": "\tp.include_apocrypha true\n\tit \"should handle book: Jude (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Hið almenna bref ", "end": 148426, "score": 0.9822412729263306, "start": 148422, "tag": "NAME", "value": "Jude" }, { "context": " handle book: Sus (is)\", ->\n\t\t`\n\t\texpect(p.parse(\"Susanna 1:1\").osis()).toEqual(\"Sus.1.1\")\n\t\texpect(p.parse", "end": 153242, "score": 0.9545036554336548, "start": 153235, "tag": "NAME", "value": "Susanna" }, { "context": ":1\").osis()).toEqual(\"Sus.1.1\")\n\t\texpect(p.parse(\"Súsanna 1:1\").osis()).toEqual(\"Sus.1.1\")\n\t\texpect(p.parse", "end": 153301, "score": 0.9281508326530457, "start": 153294, "tag": "NAME", "value": "Súsanna" } ]
lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/is/spec.coffee
saiba-mais/bible-lessons
149
bcv_parser = require("../../js/is_bcv_parser.js").bcv_parser describe "Parsing", -> p = {} beforeEach -> p = new bcv_parser p.options.osis_compaction_strategy = "b" p.options.sequence_combination_strategy = "combine" it "should round-trip OSIS references", -> p.set_options osis_compaction_strategy: "bc" books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","Dan","Hos","Joel","Amos","Obad","Jonah","Mic","Nah","Hab","Zeph","Hag","Zech","Mal","Matt","Mark","Luke","John","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range it "should round-trip OSIS Apocrypha references", -> p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b" p.include_apocrypha true books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range p.set_options ps151_strategy: "bc" expect(p.parse("Ps151.1").osis()).toEqual "Ps.151" expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1" expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2" p.include_apocrypha false for book in books bc = book + ".1" expect(p.parse(bc).osis()).toEqual "" it "should handle a preceding character", -> expect(p.parse(" Gen 1").osis()).toEqual "Gen.1" expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3" expect(p.parse("1Ps 1").osis()).toEqual "" expect(p.parse("11Sam 1").osis()).toEqual "" describe "Localized book Gen (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gen (is)", -> ` expect(p.parse("Fyrsta bok Mose 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta bok Móse 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta bók Mose 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta bók Móse 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta Mosebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta Mosebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta Mósebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta Mósebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. Mosebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. Mosebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. Mósebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. Mósebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. Mosebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. Mosebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. Mósebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. Mósebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mosebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mosebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mósebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mósebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mosebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mosebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mósebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mósebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Genesis 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. Mos 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. Mós 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. Mos 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. Mós 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mos 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mós 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mos 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mós 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1Mós 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1") p.include_apocrypha(false) expect(p.parse("FYRSTA BOK MOSE 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA BOK MÓSE 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA BÓK MOSE 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA BÓK MÓSE 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA MOSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA MOSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA MÓSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA MÓSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MOSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MOSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MÓSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MÓSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MOSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MOSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MÓSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MÓSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MOSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MOSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MÓSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MÓSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MOSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MOSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MÓSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MÓSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GENESIS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MÓS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MÓS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MÓS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MÓS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1MÓS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1") ` true describe "Localized book Exod (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Exod (is)", -> ` expect(p.parse("Onnur bok Mose 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur bok Móse 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur bók Mose 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur bók Móse 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur bok Mose 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur bok Móse 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur bók Mose 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur bók Móse 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mos 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mós 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mos 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mós 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exodus 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mos 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mós 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mos 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mós 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2Mós 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1") p.include_apocrypha(false) expect(p.parse("ONNUR BOK MOSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR BOK MÓSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR BÓK MOSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR BÓK MÓSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR BOK MOSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR BOK MÓSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR BÓK MOSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR BÓK MÓSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MOS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MÓS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MOS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MÓS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXODUS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MOS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MÓS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MOS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MÓS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2MÓS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1") ` true describe "Localized book Bel (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bel (is)", -> ` expect(p.parse("Bel og drekinn 1:1").osis()).toEqual("Bel.1.1") expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1") ` true describe "Localized book Lev (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lev (is)", -> ` expect(p.parse("Þriðja bok Mose 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja bok Móse 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja bók Mose 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja bók Móse 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja Mosebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja Mosebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja Mósebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja Mósebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mosebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mosebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mósebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mósebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mosebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mosebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mósebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mósebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mosebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mosebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mósebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mósebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mosebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mosebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mósebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mósebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Leviticus 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mos 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mós 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mos 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mós 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mos 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mós 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mos 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mós 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3Mós 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1") p.include_apocrypha(false) expect(p.parse("ÞRIÐJA BOK MOSE 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA BOK MÓSE 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA BÓK MOSE 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA BÓK MÓSE 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA MOSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA MOSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA MÓSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA MÓSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MOSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MOSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MÓSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MÓSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MOSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MOSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MÓSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MÓSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MOSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MOSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MÓSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MÓSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MOSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MOSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MÓSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MÓSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEVITICUS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MOS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MÓS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MOS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MÓS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MOS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MÓS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MOS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MÓS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3MÓS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1") ` true describe "Localized book Num (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Num (is)", -> ` expect(p.parse("Fjorða bok Mose 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða bok Móse 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða bók Mose 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða bók Móse 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða bok Mose 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða bok Móse 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða bók Mose 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða bók Móse 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mos 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mós 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mos 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mós 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mos 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mós 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Numeri 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mos 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mós 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4Mós 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1") p.include_apocrypha(false) expect(p.parse("FJORÐA BOK MOSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA BOK MÓSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA BÓK MOSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA BÓK MÓSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA BOK MOSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA BOK MÓSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA BÓK MOSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA BÓK MÓSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MOS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MÓS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MOS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MÓS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MOS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MÓS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUMERI 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MOS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MÓS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4MÓS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1") ` true describe "Localized book Sir (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sir (is)", -> ` expect(p.parse("Siraksbok 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Siraksbók 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Síraksbok 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Síraksbók 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Sír 1:1").osis()).toEqual("Sir.1.1") ` true describe "Localized book Wis (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Wis (is)", -> ` expect(p.parse("Speki Salomons 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("Speki Salómons 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("SSal 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1") ` true describe "Localized book Lam (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lam (is)", -> ` expect(p.parse("Harmljoðin 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Harmljóðin 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Hlj 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1") p.include_apocrypha(false) expect(p.parse("HARMLJOÐIN 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("HARMLJÓÐIN 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("HLJ 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1") ` true describe "Localized book EpJer (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: EpJer (is)", -> ` expect(p.parse("Bref Jeremia 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("Bref Jeremía 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("Bréf Jeremia 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("Bréf Jeremía 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("BJer 1:1").osis()).toEqual("EpJer.1.1") ` true describe "Localized book Rev (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rev (is)", -> ` expect(p.parse("Opinberunarbok Johannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberunarbok Jóhannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberunarbók Johannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberunarbók Jóhannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberun Johannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberun Jóhannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberunarbokin 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberunarbókin 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opb 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1") p.include_apocrypha(false) expect(p.parse("OPINBERUNARBOK JOHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUNARBOK JÓHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUNARBÓK JOHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUNARBÓK JÓHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUN JOHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUN JÓHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUNARBOKIN 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUNARBÓKIN 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPB 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1") ` true describe "Localized book PrMan (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrMan (is)", -> ` expect(p.parse("Bæn Manasse 1:1").osis()).toEqual("PrMan.1.1") expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1") expect(p.parse("BMn 1:1").osis()).toEqual("PrMan.1.1") ` true describe "Localized book Deut (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Deut (is)", -> ` expect(p.parse("Fimmta bok Mose 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta bok Móse 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta bók Mose 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta bók Móse 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta Mosebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta Mosebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta Mósebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta Mósebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deuteronomium 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mosebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mosebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mósebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mósebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. Mosebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. Mosebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. Mósebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. Mósebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mosebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mosebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mósebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mósebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mosebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mosebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mósebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mósebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mos 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mós 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. Mos 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. Mós 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mos 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mós 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mos 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mós 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5Mós 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1") p.include_apocrypha(false) expect(p.parse("FIMMTA BOK MOSE 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA BOK MÓSE 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA BÓK MOSE 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA BÓK MÓSE 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA MOSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA MOSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA MÓSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA MÓSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUTERONOMIUM 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MOSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MOSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MÓSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MÓSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MOSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MOSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MÓSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MÓSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MOSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MOSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MÓSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MÓSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MOSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MOSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MÓSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MÓSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MOS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MÓS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MOS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MÓS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MOS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MÓS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MOS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MÓS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5MÓS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1") ` true describe "Localized book Josh (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Josh (is)", -> ` expect(p.parse("Josuabok 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josuabók 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josúabok 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josúabók 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jósuabok 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jósuabók 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jósúabok 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jósúabók 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jos 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jós 1:1").osis()).toEqual("Josh.1.1") p.include_apocrypha(false) expect(p.parse("JOSUABOK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSUABÓK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSÚABOK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSÚABÓK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JÓSUABOK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JÓSUABÓK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JÓSÚABOK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JÓSÚABÓK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOS 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JÓS 1:1").osis()).toEqual("Josh.1.1") ` true describe "Localized book Judg (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Judg (is)", -> ` expect(p.parse("Domarabokin 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Domarabókin 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dómarabokin 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dómarabókin 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Domarabok 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Domarabók 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dómarabok 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dómarabók 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dom 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dóm 1:1").osis()).toEqual("Judg.1.1") p.include_apocrypha(false) expect(p.parse("DOMARABOKIN 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DOMARABÓKIN 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DÓMARABOKIN 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DÓMARABÓKIN 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DOMARABOK 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DOMARABÓK 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DÓMARABOK 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DÓMARABÓK 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DOM 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DÓM 1:1").osis()).toEqual("Judg.1.1") ` true describe "Localized book Ruth (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ruth (is)", -> ` expect(p.parse("Rutarbok 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rutarbók 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rut 1:1").osis()).toEqual("Ruth.1.1") p.include_apocrypha(false) expect(p.parse("RUTARBOK 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTARBÓK 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUT 1:1").osis()).toEqual("Ruth.1.1") ` true describe "Localized book 1Esd (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Esd (is)", -> ` expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1") ` true describe "Localized book 2Esd (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Esd (is)", -> ` expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1") ` true describe "Localized book Isa (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Isa (is)", -> ` expect(p.parse("Jesaja 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Jes 1:1").osis()).toEqual("Isa.1.1") p.include_apocrypha(false) expect(p.parse("JESAJA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("JES 1:1").osis()).toEqual("Isa.1.1") ` true describe "Localized book 2Sam (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Sam (is)", -> ` expect(p.parse("Siðari Samuelsbok 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Siðari Samuelsbók 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Siðari Samúelsbok 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Siðari Samúelsbók 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Síðari Samuelsbok 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Síðari Samuelsbók 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Síðari Samúelsbok 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Síðari Samúelsbók 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARI SAMUELSBOK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SIÐARI SAMUELSBÓK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SIÐARI SAMÚELSBOK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SIÐARI SAMÚELSBÓK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SÍÐARI SAMUELSBOK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SÍÐARI SAMUELSBÓK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SÍÐARI SAMÚELSBOK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SÍÐARI SAMÚELSBÓK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1") ` true describe "Localized book 1Sam (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Sam (is)", -> ` expect(p.parse("Fyrri Samuelsbok 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Fyrri Samuelsbók 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Fyrri Samúelsbok 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Fyrri Samúelsbók 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1") p.include_apocrypha(false) expect(p.parse("FYRRI SAMUELSBOK 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("FYRRI SAMUELSBÓK 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("FYRRI SAMÚELSBOK 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("FYRRI SAMÚELSBÓK 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1") ` true describe "Localized book 2Kgs (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Kgs (is)", -> ` expect(p.parse("Siðari bok konunganna 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Siðari bók konunganna 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Síðari bok konunganna 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Síðari bók konunganna 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Siðari Konungabok 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Siðari Konungabók 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Síðari Konungabok 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Síðari Konungabók 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Síðari konungabók 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. Kon 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. Kon 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II Kon 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Kon 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARI BOK KONUNGANNA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SIÐARI BÓK KONUNGANNA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SÍÐARI BOK KONUNGANNA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SÍÐARI BÓK KONUNGANNA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SIÐARI KONUNGABOK 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SIÐARI KONUNGABÓK 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SÍÐARI KONUNGABOK 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SÍÐARI KONUNGABÓK 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SÍÐARI KONUNGABÓK 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. KON 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. KON 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II KON 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 KON 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1") ` true describe "Localized book 1Kgs (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Kgs (is)", -> ` expect(p.parse("Fyrri bok konunganna 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Fyrri bók konunganna 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Fyrri Konungabok 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Fyrri Konungabók 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Fyrri konungabók 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. Kon 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. Kon 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Kon 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I Kon 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1") p.include_apocrypha(false) expect(p.parse("FYRRI BOK KONUNGANNA 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("FYRRI BÓK KONUNGANNA 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("FYRRI KONUNGABOK 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("FYRRI KONUNGABÓK 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("FYRRI KONUNGABÓK 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. KON 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. KON 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 KON 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I KON 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1") ` true describe "Localized book 2Chr (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Chr (is)", -> ` expect(p.parse("Siðari Kronikubok 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Siðari Kronikubók 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Siðari Kroníkubok 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Siðari Kroníkubók 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Síðari Kronikubok 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Síðari Kronikubók 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Síðari Kroníkubok 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Síðari Kroníkubók 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Síðari kroníkubók 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. Kro 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. Kro 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II Kro 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Kro 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARI KRONIKUBOK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SIÐARI KRONIKUBÓK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SIÐARI KRONÍKUBOK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SIÐARI KRONÍKUBÓK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SÍÐARI KRONIKUBOK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SÍÐARI KRONIKUBÓK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SÍÐARI KRONÍKUBOK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SÍÐARI KRONÍKUBÓK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SÍÐARI KRONÍKUBÓK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. KRO 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. KRO 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II KRO 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 KRO 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1") ` true describe "Localized book 1Chr (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Chr (is)", -> ` expect(p.parse("Fyrri Kronikubok 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Fyrri Kronikubók 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Fyrri Kroníkubok 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Fyrri Kroníkubók 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Fyrri kroníkubók 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. Kro 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. Kro 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Kro 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I Kro 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1") p.include_apocrypha(false) expect(p.parse("FYRRI KRONIKUBOK 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("FYRRI KRONIKUBÓK 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("FYRRI KRONÍKUBOK 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("FYRRI KRONÍKUBÓK 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("FYRRI KRONÍKUBÓK 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. KRO 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. KRO 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 KRO 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I KRO 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1") ` true describe "Localized book Ezra (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezra (is)", -> ` expect(p.parse("Esrabok 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Esrabók 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Esr 1:1").osis()).toEqual("Ezra.1.1") p.include_apocrypha(false) expect(p.parse("ESRABOK 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("ESRABÓK 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("ESR 1:1").osis()).toEqual("Ezra.1.1") ` true describe "Localized book Neh (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Neh (is)", -> ` expect(p.parse("Nehemiabok 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Nehemiabók 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Nehemíabok 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Nehemíabók 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1") p.include_apocrypha(false) expect(p.parse("NEHEMIABOK 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEHEMIABÓK 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEHEMÍABOK 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEHEMÍABÓK 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1") ` true describe "Localized book GkEsth (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: GkEsth (is)", -> ` expect(p.parse("Esterarbok hin griska 1:1").osis()).toEqual("GkEsth.1.1") expect(p.parse("Esterarbok hin gríska 1:1").osis()).toEqual("GkEsth.1.1") expect(p.parse("Esterarbók hin griska 1:1").osis()).toEqual("GkEsth.1.1") expect(p.parse("Esterarbók hin gríska 1:1").osis()).toEqual("GkEsth.1.1") expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1") ` true describe "Localized book Esth (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Esth (is)", -> ` expect(p.parse("Esterarbok 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esterarbók 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1") p.include_apocrypha(false) expect(p.parse("ESTERARBOK 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTERARBÓK 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1") ` true describe "Localized book Job (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Job (is)", -> ` expect(p.parse("Jobsbok 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Jobsbók 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1") p.include_apocrypha(false) expect(p.parse("JOBSBOK 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOBSBÓK 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1") ` true describe "Localized book Ps (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ps (is)", -> ` expect(p.parse("Salmarnir 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Sálmarnir 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Slm 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1") p.include_apocrypha(false) expect(p.parse("SALMARNIR 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("SÁLMARNIR 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("SLM 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1") ` true describe "Localized book PrAzar (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrAzar (is)", -> ` expect(p.parse("Bæn Asarja 1:1").osis()).toEqual("PrAzar.1.1") expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1") ` true describe "Localized book Prov (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Prov (is)", -> ` expect(p.parse("Orðskviðirnir 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Okv 1:1").osis()).toEqual("Prov.1.1") p.include_apocrypha(false) expect(p.parse("ORÐSKVIÐIRNIR 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("OKV 1:1").osis()).toEqual("Prov.1.1") ` true describe "Localized book Eccl (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eccl (is)", -> ` expect(p.parse("Predikarinn 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Prédikarinn 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Pred 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Préd 1:1").osis()).toEqual("Eccl.1.1") p.include_apocrypha(false) expect(p.parse("PREDIKARINN 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("PRÉDIKARINN 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("PRED 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("PRÉD 1:1").osis()).toEqual("Eccl.1.1") ` true describe "Localized book SgThree (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: SgThree (is)", -> ` expect(p.parse("Lofsongur ungmennanna þriggja 1:1").osis()).toEqual("SgThree.1.1") expect(p.parse("Lofsöngur ungmennanna þriggja 1:1").osis()).toEqual("SgThree.1.1") expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1") ` true describe "Localized book Song (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Song (is)", -> ` expect(p.parse("Ljoðaljoðin 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ljoðaljóðin 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ljóðaljoðin 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ljóðaljóðin 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ljl 1:1").osis()).toEqual("Song.1.1") p.include_apocrypha(false) expect(p.parse("LJOÐALJOÐIN 1:1").osis()).toEqual("Song.1.1") expect(p.parse("LJOÐALJÓÐIN 1:1").osis()).toEqual("Song.1.1") expect(p.parse("LJÓÐALJOÐIN 1:1").osis()).toEqual("Song.1.1") expect(p.parse("LJÓÐALJÓÐIN 1:1").osis()).toEqual("Song.1.1") expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1") expect(p.parse("LJL 1:1").osis()).toEqual("Song.1.1") ` true describe "Localized book Jer (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jer (is)", -> ` expect(p.parse("Jeremia 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jeremía 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1") p.include_apocrypha(false) expect(p.parse("JEREMIA 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JEREMÍA 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1") ` true describe "Localized book Ezek (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezek (is)", -> ` expect(p.parse("Esekiel 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Esekíel 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Esk 1:1").osis()).toEqual("Ezek.1.1") p.include_apocrypha(false) expect(p.parse("ESEKIEL 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("ESEKÍEL 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("ESK 1:1").osis()).toEqual("Ezek.1.1") ` true describe "Localized book Dan (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Dan (is)", -> ` expect(p.parse("Daniel 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Daníel 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1") p.include_apocrypha(false) expect(p.parse("DANIEL 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DANÍEL 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1") ` true describe "Localized book Hos (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hos (is)", -> ` expect(p.parse("Hosea 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hósea 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hós 1:1").osis()).toEqual("Hos.1.1") p.include_apocrypha(false) expect(p.parse("HOSEA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HÓSEA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HÓS 1:1").osis()).toEqual("Hos.1.1") ` true describe "Localized book Joel (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Joel (is)", -> ` expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Jóel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Jl 1:1").osis()).toEqual("Joel.1.1") p.include_apocrypha(false) expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JÓEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JL 1:1").osis()).toEqual("Joel.1.1") ` true describe "Localized book Amos (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Amos (is)", -> ` expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Am 1:1").osis()).toEqual("Amos.1.1") p.include_apocrypha(false) expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AM 1:1").osis()).toEqual("Amos.1.1") ` true describe "Localized book Obad (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Obad (is)", -> ` expect(p.parse("Obadia 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obadía 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Óbadia 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Óbadía 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Ob 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Ób 1:1").osis()).toEqual("Obad.1.1") p.include_apocrypha(false) expect(p.parse("OBADIA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBADÍA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("ÓBADIA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("ÓBADÍA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OB 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("ÓB 1:1").osis()).toEqual("Obad.1.1") ` true describe "Localized book Jonah (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jonah (is)", -> ` expect(p.parse("Jonah 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jonas 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jónas 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jon 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jón 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JONAS 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JÓNAS 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JON 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JÓN 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book Mic (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mic (is)", -> ` expect(p.parse("Mika 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Míka 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mik 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mík 1:1").osis()).toEqual("Mic.1.1") p.include_apocrypha(false) expect(p.parse("MIKA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MÍKA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIK 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MÍK 1:1").osis()).toEqual("Mic.1.1") ` true describe "Localized book Nah (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Nah (is)", -> ` expect(p.parse("Nahum 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nahúm 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1") p.include_apocrypha(false) expect(p.parse("NAHUM 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAHÚM 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1") ` true describe "Localized book Hab (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hab (is)", -> ` expect(p.parse("Habakkuk 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1") p.include_apocrypha(false) expect(p.parse("HABAKKUK 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1") ` true describe "Localized book Zeph (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zeph (is)", -> ` expect(p.parse("Sefania 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sefanía 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sef 1:1").osis()).toEqual("Zeph.1.1") p.include_apocrypha(false) expect(p.parse("SEFANIA 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SEFANÍA 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SEF 1:1").osis()).toEqual("Zeph.1.1") ` true describe "Localized book Hag (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hag (is)", -> ` expect(p.parse("Haggai 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Haggaí 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1") p.include_apocrypha(false) expect(p.parse("HAGGAI 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAGGAÍ 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1") ` true describe "Localized book Zech (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zech (is)", -> ` expect(p.parse("Sakaria 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Sakaría 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Sak 1:1").osis()).toEqual("Zech.1.1") p.include_apocrypha(false) expect(p.parse("SAKARIA 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("SAKARÍA 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("SAK 1:1").osis()).toEqual("Zech.1.1") ` true describe "Localized book Mal (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mal (is)", -> ` expect(p.parse("Malaki 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Malakí 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1") p.include_apocrypha(false) expect(p.parse("MALAKI 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MALAKÍ 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1") ` true describe "Localized book Matt (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Matt (is)", -> ` expect(p.parse("Matteusarguðspjall 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1") p.include_apocrypha(false) expect(p.parse("MATTEUSARGUÐSPJALL 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1") ` true describe "Localized book Mark (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mark (is)", -> ` expect(p.parse("Markusarguðspjall 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Markúsarguðspjall 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mrk 1:1").osis()).toEqual("Mark.1.1") p.include_apocrypha(false) expect(p.parse("MARKUSARGUÐSPJALL 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARKÚSARGUÐSPJALL 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MRK 1:1").osis()).toEqual("Mark.1.1") ` true describe "Localized book Luke (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Luke (is)", -> ` expect(p.parse("Lukasarguðspjall 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Lúkasarguðspjall 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luk 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Lúk 1:1").osis()).toEqual("Luke.1.1") p.include_apocrypha(false) expect(p.parse("LUKASARGUÐSPJALL 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LÚKASARGUÐSPJALL 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUK 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LÚK 1:1").osis()).toEqual("Luke.1.1") ` true describe "Localized book 1John (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1John (is)", -> ` expect(p.parse("Fyrsta bref Johannesar hið almenna 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bref Jóhannesar hið almenna 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bréf Johannesar hið almenna 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bréf Jóhannesar hið almenna 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bref Johannesar 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bref Jóhannesar 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bréf Johannesar 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bréf Jóhannesar 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta Johannesarbref 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta Johannesarbréf 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta Jóhannesarbref 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta Jóhannesarbréf 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Joh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Jóh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Joh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Jóh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Joh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Jóh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Joh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Jóh 1:1").osis()).toEqual("1John.1.1") p.include_apocrypha(false) expect(p.parse("FYRSTA BREF JOHANNESAR HIÐ ALMENNA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BREF JÓHANNESAR HIÐ ALMENNA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BRÉF JOHANNESAR HIÐ ALMENNA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BRÉF JÓHANNESAR HIÐ ALMENNA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BREF JOHANNESAR 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BREF JÓHANNESAR 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BRÉF JOHANNESAR 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BRÉF JÓHANNESAR 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA JOHANNESARBREF 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA JOHANNESARBRÉF 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA JÓHANNESARBREF 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA JÓHANNESARBRÉF 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. JOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. JÓH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. JOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. JÓH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 JOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 JÓH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I JOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I JÓH 1:1").osis()).toEqual("1John.1.1") ` true describe "Localized book 2John (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2John (is)", -> ` expect(p.parse("Annað bref Johannesar 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað bref Jóhannesar 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað bréf Johannesar 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað bréf Jóhannesar 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað Johannesarbref 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað Johannesarbréf 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað Jóhannesarbref 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað Jóhannesarbréf 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Joh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Jóh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Joh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Jóh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Joh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Jóh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Joh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Jóh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1") p.include_apocrypha(false) expect(p.parse("ANNAÐ BREF JOHANNESAR 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ BREF JÓHANNESAR 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ BRÉF JOHANNESAR 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ BRÉF JÓHANNESAR 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ JOHANNESARBREF 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ JOHANNESARBRÉF 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ JÓHANNESARBREF 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ JÓHANNESARBRÉF 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. JOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. JÓH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. JOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. JÓH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II JOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II JÓH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 JOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 JÓH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1") ` true describe "Localized book 3John (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3John (is)", -> ` expect(p.parse("Þriðja bref Johannesar 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja bref Jóhannesar 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja bréf Johannesar 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja bréf Jóhannesar 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja Johannesarbref 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja Johannesarbréf 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja Jóhannesarbref 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja Jóhannesarbréf 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Joh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Jóh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Joh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Jóh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Joh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Jóh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Joh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Jóh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1") p.include_apocrypha(false) expect(p.parse("ÞRIÐJA BREF JOHANNESAR 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA BREF JÓHANNESAR 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA BRÉF JOHANNESAR 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA BRÉF JÓHANNESAR 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA JOHANNESARBREF 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA JOHANNESARBRÉF 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA JÓHANNESARBREF 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA JÓHANNESARBRÉF 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. JOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. JÓH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III JOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III JÓH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. JOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. JÓH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 JOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 JÓH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1") ` true describe "Localized book John (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: John (is)", -> ` expect(p.parse("Johannesarguðspjall 1:1").osis()).toEqual("John.1.1") expect(p.parse("Jóhannesarguðspjall 1:1").osis()).toEqual("John.1.1") expect(p.parse("John 1:1").osis()).toEqual("John.1.1") expect(p.parse("Joh 1:1").osis()).toEqual("John.1.1") expect(p.parse("Jóh 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("JOHANNESARGUÐSPJALL 1:1").osis()).toEqual("John.1.1") expect(p.parse("JÓHANNESARGUÐSPJALL 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOH 1:1").osis()).toEqual("John.1.1") expect(p.parse("JÓH 1:1").osis()).toEqual("John.1.1") ` true describe "Localized book Acts (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Acts (is)", -> ` expect(p.parse("Postulasagan 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Post 1:1").osis()).toEqual("Acts.1.1") p.include_apocrypha(false) expect(p.parse("POSTULASAGAN 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("POST 1:1").osis()).toEqual("Acts.1.1") ` true describe "Localized book Rom (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rom (is)", -> ` expect(p.parse("Bref Pals til Romverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bref Pals til Rómverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bref Páls til Romverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bref Páls til Rómverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bréf Pals til Romverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bréf Pals til Rómverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bréf Páls til Romverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bréf Páls til Rómverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Romverjabrefið 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Romverjabréfið 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rómverjabrefið 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rómverjabréfið 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Róm 1:1").osis()).toEqual("Rom.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL ROMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BREF PALS TIL RÓMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BREF PÁLS TIL ROMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BREF PÁLS TIL RÓMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BRÉF PALS TIL ROMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BRÉF PALS TIL RÓMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BRÉF PÁLS TIL ROMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BRÉF PÁLS TIL RÓMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROMVERJABREFIÐ 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROMVERJABRÉFIÐ 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("RÓMVERJABREFIÐ 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("RÓMVERJABRÉFIÐ 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("RÓM 1:1").osis()).toEqual("Rom.1.1") ` true describe "Localized book 2Cor (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Cor (is)", -> ` expect(p.parse("Siðara bref Pals til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bref Páls til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bréf Pals til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bréf Páls til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bref Pals til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bref Páls til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bréf Pals til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bréf Páls til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bref Pals til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bref Páls til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bréf Pals til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bréf Páls til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bref Pals til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bref Páls til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bréf Pals til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bréf Páls til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara Korintubref 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara Korintubréf 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara Kórintubref 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara Kórintubréf 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara Korintubref 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara Korintubréf 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara Kórintubref 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara Kórintubréf 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARA BREF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BREF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BREF PALS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BREF PALS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA KORINTUBREF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA KORINTUBRÉF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA KÓRINTUBREF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA KÓRINTUBRÉF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA KORINTUBREF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA KORINTUBRÉF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA KÓRINTUBREF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA KÓRINTUBRÉF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1") ` true describe "Localized book 1Cor (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Cor (is)", -> ` expect(p.parse("Fyrra bref Pals til Korintumanna 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bref Páls til Korintumanna 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bréf Pals til Korintumanna 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bréf Páls til Korintumanna 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bref Pals til Korin 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bref Páls til Korin 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bréf Pals til Korin 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bréf Páls til Korin 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra Korintubref 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra Korintubréf 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1") p.include_apocrypha(false) expect(p.parse("FYRRA BREF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BREF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BRÉF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BREF PALS TIL KORIN 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BREF PÁLS TIL KORIN 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BRÉF PALS TIL KORIN 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL KORIN 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA KORINTUBREF 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA KORINTUBRÉF 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1") ` true describe "Localized book Gal (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gal (is)", -> ` expect(p.parse("Bref Pals til Galatamanna 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Bref Páls til Galatamanna 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Bréf Pals til Galatamanna 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Bréf Páls til Galatamanna 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Galatabrefið 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Galatabréfið 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL GALATAMANNA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("BREF PÁLS TIL GALATAMANNA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("BRÉF PALS TIL GALATAMANNA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("BRÉF PÁLS TIL GALATAMANNA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GALATABREFIÐ 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GALATABRÉFIÐ 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1") ` true describe "Localized book Eph (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eph (is)", -> ` expect(p.parse("Bref Pals til Efesusmanna 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Bref Páls til Efesusmanna 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Bréf Pals til Efesusmanna 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Bréf Páls til Efesusmanna 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Efesusbrefið 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Efesusbréfið 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Ef 1:1").osis()).toEqual("Eph.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL EFESUSMANNA 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("BREF PÁLS TIL EFESUSMANNA 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("BRÉF PALS TIL EFESUSMANNA 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("BRÉF PÁLS TIL EFESUSMANNA 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EFESUSBREFIÐ 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EFESUSBRÉFIÐ 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EF 1:1").osis()).toEqual("Eph.1.1") ` true describe "Localized book Phil (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phil (is)", -> ` expect(p.parse("Bref Pals til Filippimanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Pals til Filippímanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Páls til Filippimanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Páls til Filippímanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Pals til Filippimanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Pals til Filippímanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Páls til Filippimanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Páls til Filippímanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Pals til Filippimann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Pals til Filippímann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Páls til Filippimann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Páls til Filippímann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Pals til Filippimann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Pals til Filippímann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Páls til Filippimann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Páls til Filippímann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filippibrefið 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filippibréfið 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filippíbrefið 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filippíbréfið 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Fil 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL FILIPPIMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PALS TIL FILIPPÍMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PÁLS TIL FILIPPIMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PÁLS TIL FILIPPÍMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PALS TIL FILIPPIMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PALS TIL FILIPPÍMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PÁLS TIL FILIPPIMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PÁLS TIL FILIPPÍMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PALS TIL FILIPPIMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PALS TIL FILIPPÍMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PÁLS TIL FILIPPIMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PÁLS TIL FILIPPÍMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PALS TIL FILIPPIMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PALS TIL FILIPPÍMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PÁLS TIL FILIPPIMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PÁLS TIL FILIPPÍMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPPIBREFIÐ 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPPIBRÉFIÐ 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPPÍBREFIÐ 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPPÍBRÉFIÐ 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FIL 1:1").osis()).toEqual("Phil.1.1") ` true describe "Localized book Col (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Col (is)", -> ` expect(p.parse("Bref Pals til Kolossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Pals til Kólossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Páls til Kolossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Páls til Kólossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Pals til Kolossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Pals til Kólossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Páls til Kolossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Páls til Kólossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Pals til Kolossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Pals til Kólossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Páls til Kolossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Páls til Kólossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Pals til Kolossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Pals til Kólossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Páls til Kolossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Páls til Kólossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolossubrefið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolossubréfið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolussubrefið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolussubréfið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kólossubrefið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kólossubréfið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kólussubrefið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kólussubréfið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kol 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kól 1:1").osis()).toEqual("Col.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL KOLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PALS TIL KÓLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PÁLS TIL KOLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PÁLS TIL KÓLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PALS TIL KOLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PALS TIL KÓLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PÁLS TIL KOLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PÁLS TIL KÓLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PALS TIL KOLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PALS TIL KÓLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PÁLS TIL KOLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PÁLS TIL KÓLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PALS TIL KOLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PALS TIL KÓLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PÁLS TIL KOLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PÁLS TIL KÓLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLOSSUBREFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLOSSUBRÉFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLUSSUBREFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLUSSUBRÉFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KÓLOSSUBREFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KÓLOSSUBRÉFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KÓLUSSUBREFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KÓLUSSUBRÉFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KÓL 1:1").osis()).toEqual("Col.1.1") ` true describe "Localized book 2Thess (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Thess (is)", -> ` expect(p.parse("Siðara bref Pals til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bref Pals til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bref Páls til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bref Páls til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Pals til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Pals til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Páls til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Páls til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Pals til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Pals til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Páls til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Páls til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Pals til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Pals til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Páls til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Páls til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bref Pals til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bref Páls til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Pals til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Páls til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Pals til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Páls til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Pals til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Páls til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara Þessalonikubref 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara Þessalonikubréf 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara Þessaloníkubref 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara Þessaloníkubréf 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara Þessalonikubref 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara Þessalonikubréf 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara Þessaloníkubref 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara Þessaloníkubréf 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARA BREF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BREF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BREF PALS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PALS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA ÞESSALONIKUBREF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA ÞESSALONIKUBRÉF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA ÞESSALONÍKUBREF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA ÞESSALONÍKUBRÉF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA ÞESSALONIKUBREF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA ÞESSALONIKUBRÉF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA ÞESSALONÍKUBREF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA ÞESSALONÍKUBRÉF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1") ` true describe "Localized book 1Thess (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Thess (is)", -> ` expect(p.parse("Fyrra bref Pals til Þessalonikumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bref Pals til Þessaloníkumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bref Páls til Þessalonikumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bref Páls til Þessaloníkumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Pals til Þessalonikumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Pals til Þessaloníkumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Páls til Þessalonikumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Páls til Þessaloníkumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bref Pals til Þessa 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bref Páls til Þessa 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Pals til Þessa 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Páls til Þessa 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra Þessalonikubref 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra Þessalonikubréf 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra Þessaloníkubref 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra Þessaloníkubréf 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Þess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Þess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Þess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Þess 1:1").osis()).toEqual("1Thess.1.1") p.include_apocrypha(false) expect(p.parse("FYRRA BREF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BREF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BREF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BREF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BREF PALS TIL ÞESSA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BREF PÁLS TIL ÞESSA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PALS TIL ÞESSA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL ÞESSA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA ÞESSALONIKUBREF 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA ÞESSALONIKUBRÉF 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA ÞESSALONÍKUBREF 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA ÞESSALONÍKUBRÉF 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. ÞESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. ÞESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 ÞESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I ÞESS 1:1").osis()).toEqual("1Thess.1.1") ` true describe "Localized book 2Tim (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Tim (is)", -> ` expect(p.parse("Siðara bref Pals til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Timoteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Timoteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Timóteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Timóteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Tímoteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Tímoteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Tímóteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Tímóteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Timoteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Timoteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Timóteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Timóteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Tímoteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Tímoteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Tímóteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Tímóteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Tím 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Tím 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Tím 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Tím 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARA BREF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TIMOTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TIMOTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TIMÓTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TIMÓTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TÍMOTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TÍMOTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TÍMÓTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TÍMÓTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TIMOTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TIMOTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TIMÓTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TIMÓTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TÍMOTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TÍMOTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TÍMÓTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TÍMÓTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TÍM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TÍM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TÍM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TÍM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1") ` true describe "Localized book 1Tim (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Tim (is)", -> ` expect(p.parse("Fyrra bref Pals til Timoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Timóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Tímoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Tímóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Timoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Timóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Tímoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Tímóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Timoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Timóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Tímoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Tímóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Timoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Timóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Tímoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Tímóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Timot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Timót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Tímot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Tímót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Timot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Timót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Tímot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Tímót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Timot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Timót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Tímot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Tímót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Timot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Timót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Tímot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Tímót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Timoteusarbref 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Timoteusarbréf 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Timóteusarbref 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Timóteusarbréf 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Tímoteusarbref 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Tímoteusarbréf 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Tímóteusarbref 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Tímóteusarbréf 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Tím 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Tím 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Tím 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Tím 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1") p.include_apocrypha(false) expect(p.parse("FYRRA BREF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TIMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TIMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TÍMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TÍMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TIMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TIMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TÍMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TÍMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TIMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TIMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TÍMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TÍMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TIMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TIMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TÍMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TÍMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TIMOTEUSARBREF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TIMOTEUSARBRÉF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TIMÓTEUSARBREF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TIMÓTEUSARBRÉF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TÍMOTEUSARBREF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TÍMOTEUSARBRÉF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TÍMÓTEUSARBREF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TÍMÓTEUSARBRÉF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TÍM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TÍM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TÍM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TÍM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1") ` true describe "Localized book Titus (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Titus (is)", -> ` expect(p.parse("Bref Pals til Titusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bref Pals til Títusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bref Páls til Titusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bref Páls til Títusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bréf Pals til Titusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bréf Pals til Títusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bréf Páls til Titusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bréf Páls til Títusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titusarbrefið 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titusarbréfið 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Títusarbrefið 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Títusarbréfið 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titusarbref 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titusarbréf 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Títusarbref 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Títusarbréf 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tit 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tít 1:1").osis()).toEqual("Titus.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL TITUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BREF PALS TIL TÍTUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BREF PÁLS TIL TITUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BREF PÁLS TIL TÍTUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BRÉF PALS TIL TITUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BRÉF PALS TIL TÍTUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BRÉF PÁLS TIL TITUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BRÉF PÁLS TIL TÍTUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUSARBREFIÐ 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUSARBRÉFIÐ 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TÍTUSARBREFIÐ 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TÍTUSARBRÉFIÐ 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUSARBREF 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUSARBRÉF 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TÍTUSARBREF 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TÍTUSARBRÉF 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TIT 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TÍT 1:1").osis()).toEqual("Titus.1.1") ` true describe "Localized book Phlm (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phlm (is)", -> ` expect(p.parse("Bref Pals til Filemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bref Pals til Fílemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bref Páls til Filemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bref Páls til Fílemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bréf Pals til Filemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bréf Pals til Fílemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bréf Páls til Filemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bréf Páls til Fílemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Filemonsbrefið 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Filemonsbréfið 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Fílemonsbrefið 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Fílemonsbréfið 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Film 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Fílm 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL FILEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BREF PALS TIL FÍLEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BREF PÁLS TIL FILEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BREF PÁLS TIL FÍLEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BRÉF PALS TIL FILEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BRÉF PALS TIL FÍLEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BRÉF PÁLS TIL FILEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BRÉF PÁLS TIL FÍLEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILEMONSBREFIÐ 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILEMONSBRÉFIÐ 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FÍLEMONSBREFIÐ 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FÍLEMONSBRÉFIÐ 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FÍLM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1") ` true describe "Localized book Heb (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Heb (is)", -> ` expect(p.parse("Brefið til Hebrea 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Bréfið til Hebrea 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Hebreabrefið 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Hebreabréfið 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1") p.include_apocrypha(false) expect(p.parse("BREFIÐ TIL HEBREA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("BRÉFIÐ TIL HEBREA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEBREABREFIÐ 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEBREABRÉFIÐ 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1") ` true describe "Localized book Jas (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jas (is)", -> ` expect(p.parse("Hið almenna bref Jakobs 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Hið almenna bréf Jakobs 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jakobsbrefið 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jakobsbréfið 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jak 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1") p.include_apocrypha(false) expect(p.parse("HIÐ ALMENNA BREF JAKOBS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("HIÐ ALMENNA BRÉF JAKOBS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAKOBSBREFIÐ 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAKOBSBRÉFIÐ 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAK 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1") ` true describe "Localized book 2Pet (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Pet (is)", -> ` expect(p.parse("Siðara almenna bref Peturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara almenna bref Péturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara almenna bréf Peturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara almenna bréf Péturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara almenna bref Peturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara almenna bref Péturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara almenna bréf Peturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara almenna bréf Péturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara Petursbref 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara Petursbréf 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara Pétursbref 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara Pétursbréf 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara Petursbref 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara Petursbréf 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara Pétursbref 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara Pétursbréf 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. Pét 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. Pét 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II Pét 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Pét 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARA ALMENNA BREF PETURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA ALMENNA BREF PÉTURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA ALMENNA BRÉF PETURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA ALMENNA BRÉF PÉTURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA ALMENNA BREF PETURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA ALMENNA BREF PÉTURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA ALMENNA BRÉF PETURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA ALMENNA BRÉF PÉTURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA PETURSBREF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA PETURSBRÉF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA PÉTURSBREF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA PÉTURSBRÉF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA PETURSBREF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA PETURSBRÉF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA PÉTURSBREF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA PÉTURSBRÉF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. PÉT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. PÉT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II PÉT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PÉT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1") ` true describe "Localized book 1Pet (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Pet (is)", -> ` expect(p.parse("Fyrra almenna bref Peturs 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra almenna bref Péturs 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra almenna bréf Peturs 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra almenna bréf Péturs 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra Petursbref 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra Petursbréf 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra Pétursbref 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra Pétursbréf 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. Pét 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. Pét 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Pét 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I Pét 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1") p.include_apocrypha(false) expect(p.parse("FYRRA ALMENNA BREF PETURS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA ALMENNA BREF PÉTURS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA ALMENNA BRÉF PETURS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA ALMENNA BRÉF PÉTURS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA PETURSBREF 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA PETURSBRÉF 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA PÉTURSBREF 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA PÉTURSBRÉF 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. PÉT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. PÉT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PÉT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I PÉT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1") ` true describe "Localized book Jude (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jude (is)", -> ` expect(p.parse("Hið almenna bref Judasar 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Hið almenna bref Júdasar 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Hið almenna bréf Judasar 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Hið almenna bréf Júdasar 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judasarbrefið 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judasarbréfið 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Júdasarbrefið 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Júdasarbréfið 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judasarbref 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judasarbréf 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Júdasarbref 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Júdasarbréf 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jud 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Júd 1:1").osis()).toEqual("Jude.1.1") p.include_apocrypha(false) expect(p.parse("HIÐ ALMENNA BREF JUDASAR 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("HIÐ ALMENNA BREF JÚDASAR 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("HIÐ ALMENNA BRÉF JUDASAR 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("HIÐ ALMENNA BRÉF JÚDASAR 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDASARBREFIÐ 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDASARBRÉFIÐ 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JÚDASARBREFIÐ 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JÚDASARBRÉFIÐ 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDASARBREF 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDASARBRÉF 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JÚDASARBREF 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JÚDASARBRÉF 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUD 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JÚD 1:1").osis()).toEqual("Jude.1.1") ` true describe "Localized book Tob (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Tob (is)", -> ` expect(p.parse("Tobitsbok 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tobitsbók 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tobítsbok 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tobítsbók 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tóbitsbok 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tóbitsbók 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tóbítsbok 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tóbítsbók 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1") ` true describe "Localized book Jdt (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jdt (is)", -> ` expect(p.parse("Juditarbok 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Juditarbók 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Judítarbok 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Judítarbók 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Júditarbok 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Júditarbók 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Júdítarbok 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Júdítarbók 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Judt 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Júdt 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1") ` true describe "Localized book Bar (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bar (is)", -> ` expect(p.parse("Baruksbok 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Baruksbók 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Barúksbok 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Barúksbók 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1") ` true describe "Localized book Sus (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sus (is)", -> ` expect(p.parse("Susanna 1:1").osis()).toEqual("Sus.1.1") expect(p.parse("Súsanna 1:1").osis()).toEqual("Sus.1.1") expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1") ` true describe "Localized book 2Macc (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Macc (is)", -> ` expect(p.parse("Onnur Makkabeabok 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Onnur Makkabeabók 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Önnur Makkabeabok 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Önnur Makkabeabók 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II. Makk 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2. Makk 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II Makk 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2 Makk 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1") ` true describe "Localized book 3Macc (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3Macc (is)", -> ` expect(p.parse("Þriðja Makkabeabok 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("Þriðja Makkabeabók 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III. Makk 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III Makk 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3. Makk 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3 Makk 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1") ` true describe "Localized book 4Macc (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 4Macc (is)", -> ` expect(p.parse("Fjorða Makkabeabok 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Fjorða Makkabeabók 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Fjórða Makkabeabok 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Fjórða Makkabeabók 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV. Makk 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4. Makk 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV Makk 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4 Makk 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1") ` true describe "Localized book 1Macc (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Macc (is)", -> ` expect(p.parse("Fyrsta Makkabeabok 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("Fyrsta Makkabeabók 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1. Makk 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I. Makk 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1 Makk 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I Makk 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1") ` true describe "Miscellaneous tests", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete" p.include_apocrypha true it "should return the expected language", -> expect(p.languages).toEqual ["is"] it "should handle ranges (is)", -> expect(p.parse("Titus 1:1 - 2").osis()).toEqual "Titus.1.1-Titus.1.2" expect(p.parse("Matt 1-2").osis()).toEqual "Matt.1-Matt.2" expect(p.parse("Phlm 2 - 3").osis()).toEqual "Phlm.1.2-Phlm.1.3" it "should handle chapters (is)", -> expect(p.parse("Titus 1:1, kafli 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 KAFLI 6").osis()).toEqual "Matt.3.4,Matt.6" expect(p.parse("Titus 1:1, kafla 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 KAFLA 6").osis()).toEqual "Matt.3.4,Matt.6" expect(p.parse("Titus 1:1, kapítuli 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 KAPÍTULI 6").osis()).toEqual "Matt.3.4,Matt.6" expect(p.parse("Titus 1:1, kapituli 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 KAPITULI 6").osis()).toEqual "Matt.3.4,Matt.6" it "should handle verses (is)", -> expect(p.parse("Exod 1:1 vers 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm VERS 6").osis()).toEqual "Phlm.1.6" it "should handle 'and' (is)", -> expect(p.parse("Exod 1:1 og 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 OG 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" it "should handle titles (is)", -> expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" it "should handle 'ff' (is)", -> expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" it "should handle translations (is)", -> expect(p.parse("Lev 1 (B20)").osis_and_translations()).toEqual [["Lev.1", "B20"]] expect(p.parse("lev 1 b20").osis_and_translations()).toEqual [["Lev.1", "B20"]] it "should handle book ranges (is)", -> p.set_options {book_alone_strategy: "full", book_range_strategy: "include"} expect(p.parse("1 - 3 Joh").osis()).toEqual "1John.1-3John.1" expect(p.parse("1 - 3 Jóh").osis()).toEqual "1John.1-3John.1" it "should handle boundaries (is)", -> p.set_options {book_alone_strategy: "full"} expect(p.parse("\u2014Matt\u2014").osis()).toEqual "Matt.1-Matt.28" expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual "Matt.1.1"
7515
bcv_parser = require("../../js/is_bcv_parser.js").bcv_parser describe "Parsing", -> p = {} beforeEach -> p = new bcv_parser p.options.osis_compaction_strategy = "b" p.options.sequence_combination_strategy = "combine" it "should round-trip OSIS references", -> p.set_options osis_compaction_strategy: "bc" books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","<NAME>","<NAME>","<NAME>","<NAME>mos","<NAME>ad","<NAME>","<NAME>","<NAME>ah","Hab","Zeph","Hag","Zech","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range it "should round-trip OSIS Apocrypha references", -> p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b" p.include_apocrypha true books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range p.set_options ps151_strategy: "bc" expect(p.parse("Ps151.1").osis()).toEqual "Ps.151" expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1" expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2" p.include_apocrypha false for book in books bc = book + ".1" expect(p.parse(bc).osis()).toEqual "" it "should handle a preceding character", -> expect(p.parse(" Gen 1").osis()).toEqual "Gen.1" expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3" expect(p.parse("1Ps 1").osis()).toEqual "" expect(p.parse("11Sam 1").osis()).toEqual "" describe "Localized book Gen (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gen (is)", -> ` expect(p.parse("Fyrsta bok Mose 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta bok Móse 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta bók Mose 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta bók Móse 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta Mosebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta Mosebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta Mósebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta Mósebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. <NAME> 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. M<NAME> 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. M<NAME> 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. M<NAME>seb<NAME> 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. <NAME> 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. M<NAME>b<NAME> 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. <NAME> 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. M<NAME>sebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mosebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mosebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mósebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mósebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mosebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mosebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mósebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mósebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Genesis 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. Mos 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. Mós 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. Mos 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. Mós 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mos 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mós 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mos 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mós 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1Mós 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1") p.include_apocrypha(false) expect(p.parse("FYRSTA BOK MOSE 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA BOK MÓSE 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA BÓK MOSE 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA BÓK MÓSE 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA MOSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA MOSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA MÓSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA MÓSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MOSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MOSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MÓSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MÓSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MOSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MOSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MÓSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MÓSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MOSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MOSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MÓSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MÓSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MOSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MOSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MÓSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MÓSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GENESIS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MÓS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MÓS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MÓS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MÓS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1MÓS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1") ` true describe "Localized book Exod (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Exod (is)", -> ` expect(p.parse("Onnur bok Mose 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur bok Móse 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur bók Mose 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur bók Móse 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur bok Mose 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur bok Móse 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur bók Mose 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur bók Móse 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mos 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mós 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mos 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mós 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exodus 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mos 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mós 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mos 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mós 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2Mós 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1") p.include_apocrypha(false) expect(p.parse("ONNUR BOK MOSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR BOK MÓSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR BÓK MOSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR BÓK MÓSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR BOK MOSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR BOK MÓSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR BÓK MOSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR BÓK MÓSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MOS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MÓS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MOS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MÓS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXODUS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MOS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MÓS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MOS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MÓS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2MÓS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1") ` true describe "Localized book Bel (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bel (is)", -> ` expect(p.parse("Bel og drekinn 1:1").osis()).toEqual("Bel.1.1") expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1") ` true describe "Localized book Lev (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lev (is)", -> ` expect(p.parse("Þriðja bok Mose 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja bok Móse 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja bók Mose 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja bók Móse 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja Mosebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja Mosebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja Mósebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja Mósebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mosebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mosebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mósebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mósebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mosebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mosebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mósebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mósebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mosebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mosebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mósebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mósebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mosebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mosebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mósebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mósebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Leviticus 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mos 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mós 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mos 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mós 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mos 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mós 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mos 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mós 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3Mós 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1") p.include_apocrypha(false) expect(p.parse("ÞRIÐJA BOK MOSE 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA BOK MÓSE 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA BÓK MOSE 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA BÓK MÓSE 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA MOSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA MOSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA MÓSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA MÓSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MOSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MOSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MÓSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MÓSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MOSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MOSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MÓSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MÓSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MOSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MOSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MÓSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MÓSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MOSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MOSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MÓSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MÓSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEVITICUS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MOS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MÓS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MOS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MÓS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MOS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MÓS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MOS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MÓS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3MÓS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1") ` true describe "Localized book Num (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Num (is)", -> ` expect(p.parse("Fjorða bok Mose 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða bok Móse 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða bók Mose 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða bók Móse 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða bok Mose 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða bok Móse 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða bók Mose 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða bók Móse 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mos 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mós 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mos 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mós 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mos 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mós 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Numeri 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mos 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mós 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4Mós 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1") p.include_apocrypha(false) expect(p.parse("FJORÐA BOK MOSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA BOK MÓSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA BÓK MOSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA BÓK MÓSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA BOK MOSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA BOK MÓSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA BÓK MOSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA BÓK MÓSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MOS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MÓS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MOS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MÓS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MOS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MÓS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUMERI 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MOS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MÓS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4MÓS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1") ` true describe "Localized book Sir (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sir (is)", -> ` expect(p.parse("Siraksbok 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Siraksbók 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Síraksbok 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Síraksbók 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Sír 1:1").osis()).toEqual("Sir.1.1") ` true describe "Localized book Wis (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Wis (is)", -> ` expect(p.parse("Speki Salomons 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("Speki Salómons 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("SSal 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1") ` true describe "Localized book Lam (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lam (is)", -> ` expect(p.parse("Harmljoðin 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Harmljóðin 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Hlj 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1") p.include_apocrypha(false) expect(p.parse("HARMLJOÐIN 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("HARMLJÓÐIN 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("HLJ 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1") ` true describe "Localized book EpJer (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: EpJer (is)", -> ` expect(p.parse("Bref Jeremia 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("Bref Jeremía 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("Bréf Jeremia 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("Bréf Jeremía 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("BJer 1:1").osis()).toEqual("EpJer.1.1") ` true describe "Localized book Rev (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rev (is)", -> ` expect(p.parse("Op<NAME>berunarbok Johannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberunarbok Jóhannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberunarbók Johannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberunarbók Jóhannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberun Johannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberun Jóhannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberunarbokin 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberunarbókin 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opb 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1") p.include_apocrypha(false) expect(p.parse("OPINBERUNARBOK JOHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUNARBOK JÓHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUNARBÓK JOHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUNARBÓK JÓHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUN JOHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUN JÓHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUNARBOKIN 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUNARBÓKIN 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPB 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1") ` true describe "Localized book PrMan (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrMan (is)", -> ` expect(p.parse("Bæn Manasse 1:1").osis()).toEqual("PrMan.1.1") expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1") expect(p.parse("BMn 1:1").osis()).toEqual("PrMan.1.1") ` true describe "Localized book Deut (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Deut (is)", -> ` expect(p.parse("Fimmta bok Mose 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta bok Móse 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta bók Mose 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta bók Móse 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta Mosebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta Mosebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta Mósebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta Mósebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deuteronomium 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mosebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mosebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mósebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mósebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("<NAME> 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("<NAME> 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("<NAME> 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("<NAME> 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mosebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mosebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mósebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mósebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mosebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mosebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mósebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mósebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mos 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mós 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. Mos 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. Mós 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mos 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mós 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mos 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mós 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5Mós 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1") p.include_apocrypha(false) expect(p.parse("FIMMTA BOK MOSE 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA BOK MÓSE 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA BÓK MOSE 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA BÓK MÓSE 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA MOSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA MOSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA MÓSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA MÓSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUTERONOMIUM 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MOSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MOSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MÓSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MÓSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MOSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MOSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MÓSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MÓSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MOSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MOSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MÓSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MÓSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MOSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MOSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MÓSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MÓSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MOS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MÓS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MOS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MÓS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MOS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MÓS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MOS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MÓS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5MÓS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1") ` true describe "Localized book <NAME> (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (is)", -> ` expect(p.parse("Josuabok 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josuabók 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josúabok 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josúabók 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jósuabok 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jósuabók 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jósúabok 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jósúabók 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jos 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jós 1:1").osis()).toEqual("Josh.1.1") p.include_apocrypha(false) expect(p.parse("JOSUABOK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSUABÓK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSÚABOK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSÚABÓK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JÓSUABOK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JÓSUABÓK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JÓSÚABOK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JÓSÚABÓK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOS 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JÓS 1:1").osis()).toEqual("Josh.1.1") ` true describe "Localized book Judg (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Judg (is)", -> ` expect(p.parse("Domarabokin 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Domarabókin 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dómarabokin 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dómarabókin 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Domarabok 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Domarabók 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dómarabok 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dómarabók 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dom 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dóm 1:1").osis()).toEqual("Judg.1.1") p.include_apocrypha(false) expect(p.parse("DOMARABOKIN 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DOMARABÓKIN 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DÓMARABOKIN 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DÓMARABÓKIN 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DOMARABOK 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DOMARABÓK 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DÓMARABOK 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DÓMARABÓK 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DOM 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DÓM 1:1").osis()).toEqual("Judg.1.1") ` true describe "Localized book Ruth (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ruth (is)", -> ` expect(p.parse("Rutarbok 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rutarbók 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rut 1:1").osis()).toEqual("Ruth.1.1") p.include_apocrypha(false) expect(p.parse("RUTARBOK 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTARBÓK 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUT 1:1").osis()).toEqual("Ruth.1.1") ` true describe "Localized book 1Esd (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Esd (is)", -> ` expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1") ` true describe "Localized book 2Esd (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Esd (is)", -> ` expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1") ` true describe "Localized book Isa (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Isa (is)", -> ` expect(p.parse("Jesaja 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Jes 1:1").osis()).toEqual("Isa.1.1") p.include_apocrypha(false) expect(p.parse("JESAJA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("JES 1:1").osis()).toEqual("Isa.1.1") ` true describe "Localized book 2Sam (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Sam (is)", -> ` expect(p.parse("Siðari Samuelsbok 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Siðari Samuelsbók 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Siðari Samúelsbok 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Siðari Samúelsbók 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Síðari Samuelsbok 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Síðari Samuelsbók 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Síðari Samúelsbok 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Síðari Samúelsbók 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARI SAMUELSBOK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SIÐARI SAMUELSBÓK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SIÐARI SAMÚELSBOK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SIÐARI SAMÚELSBÓK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SÍÐARI SAMUELSBOK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SÍÐARI SAMUELSBÓK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SÍÐARI SAMÚELSBOK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SÍÐARI SAMÚELSBÓK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1") ` true describe "Localized book 1Sam (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Sam (is)", -> ` expect(p.parse("<NAME> 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("<NAME> 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("<NAME> 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("<NAME> 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. <NAME> 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. <NAME> 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1") p.include_apocrypha(false) expect(p.parse("FYRRI SAMUELSBOK 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("FYRRI SAMUELSBÓK 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("FYRRI SAMÚELSBOK 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("FYRRI SAMÚELSBÓK 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1") ` true describe "Localized book 2Kgs (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Kgs (is)", -> ` expect(p.parse("Siðari bok konunganna 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Siðari bók konunganna 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Síðari bok konunganna 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Síðari bók konunganna 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Siðari Konungabok 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Siðari Konungabók 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Síðari Konungabok 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Síðari Konungabók 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Síðari konungabók 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. Kon 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. Kon 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II Kon 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Kon 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARI BOK KONUNGANNA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SIÐARI BÓK KONUNGANNA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SÍÐARI BOK KONUNGANNA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SÍÐARI BÓK KONUNGANNA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SIÐARI KONUNGABOK 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SIÐARI KONUNGABÓK 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SÍÐARI KONUNGABOK 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SÍÐARI KONUNGABÓK 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SÍÐARI KONUNGABÓK 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. KON 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. KON 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II KON 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 KON 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1") ` true describe "Localized book 1Kgs (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Kgs (is)", -> ` expect(p.parse("Fyrri bok konunganna 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Fyrri bók konunganna 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Fyrri Konungabok 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Fyrri Konungabók 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Fyrri konungabók 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. Kon 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. Kon 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Kon 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I Kon 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1") p.include_apocrypha(false) expect(p.parse("FYRRI BOK KONUNGANNA 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("FYRRI BÓK KONUNGANNA 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("FYRRI KONUNGABOK 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("FYRRI KONUNGABÓK 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("FYRRI KONUNGABÓK 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. KON 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. KON 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 KON 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I KON 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1") ` true describe "Localized book 2Chr (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Chr (is)", -> ` expect(p.parse("Siðari Kronikubok 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Siðari Kronikubók 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Siðari Kroníkubok 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Siðari Kroníkubók 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Síðari Kronikubok 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Síðari Kronikubók 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Síðari Kroníkubok 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Síðari Kroníkubók 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Síðari kroníkubók 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. Kro 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. Kro 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II Kro 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Kro 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARI KRONIKUBOK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SIÐARI KRONIKUBÓK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SIÐARI KRONÍKUBOK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SIÐARI KRONÍKUBÓK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SÍÐARI KRONIKUBOK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SÍÐARI KRONIKUBÓK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SÍÐARI KRONÍKUBOK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SÍÐARI KRONÍKUBÓK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SÍÐARI KRONÍKUBÓK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. KRO 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. KRO 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II KRO 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 KRO 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1") ` true describe "Localized book 1Chr (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Chr (is)", -> ` expect(p.parse("Fyrri Kronikubok 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Fyrri Kronikubók 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Fyrri Kroníkubok 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Fyrri Kroníkubók 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Fyrri kroníkubók 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. Kro 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. Kro 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Kro 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I Kro 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1") p.include_apocrypha(false) expect(p.parse("FYRRI KRONIKUBOK 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("FYRRI KRONIKUBÓK 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("FYRRI KRONÍKUBOK 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("FYRRI KRONÍKUBÓK 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("FYRRI KRONÍKUBÓK 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. KRO 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. KRO 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 KRO 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I KRO 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1") ` true describe "Localized book Ezra (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezra (is)", -> ` expect(p.parse("Esrabok 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Esrabók 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Esr 1:1").osis()).toEqual("Ezra.1.1") p.include_apocrypha(false) expect(p.parse("ESRABOK 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("ESRABÓK 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("ESR 1:1").osis()).toEqual("Ezra.1.1") ` true describe "Localized book Neh (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Neh (is)", -> ` expect(p.parse("Nehemiabok 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Nehemiabók 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Nehemíabok 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Nehemíabók 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1") p.include_apocrypha(false) expect(p.parse("NEHEMIABOK 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEHEMIABÓK 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEHEMÍABOK 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEHEMÍABÓK 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1") ` true describe "Localized book GkEsth (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: GkEsth (is)", -> ` expect(p.parse("Esterarbok hin griska 1:1").osis()).toEqual("GkEsth.1.1") expect(p.parse("Esterarbok hin gríska 1:1").osis()).toEqual("GkEsth.1.1") expect(p.parse("Esterarbók hin griska 1:1").osis()).toEqual("GkEsth.1.1") expect(p.parse("Esterarbók hin gríska 1:1").osis()).toEqual("GkEsth.1.1") expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1") ` true describe "Localized book Esth (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Esth (is)", -> ` expect(p.parse("Esterarbok 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esterarbók 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1") p.include_apocrypha(false) expect(p.parse("ESTERARBOK 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTERARBÓK 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1") ` true describe "Localized book Job (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Job (is)", -> ` expect(p.parse("Jobsbok 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Jobsbók 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1") p.include_apocrypha(false) expect(p.parse("JOBSBOK 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOBSBÓK 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1") ` true describe "Localized book Ps (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ps (is)", -> ` expect(p.parse("Salmarnir 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Sálmarnir 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Slm 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1") p.include_apocrypha(false) expect(p.parse("SALMARNIR 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("SÁLMARNIR 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("SLM 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1") ` true describe "Localized book PrAzar (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrAzar (is)", -> ` expect(p.parse("Bæn Asarja 1:1").osis()).toEqual("PrAzar.1.1") expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1") ` true describe "Localized book Prov (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Prov (is)", -> ` expect(p.parse("Orðskviðirnir 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Okv 1:1").osis()).toEqual("Prov.1.1") p.include_apocrypha(false) expect(p.parse("ORÐSKVIÐIRNIR 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("OKV 1:1").osis()).toEqual("Prov.1.1") ` true describe "Localized book Eccl (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eccl (is)", -> ` expect(p.parse("Predikarinn 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Prédikarinn 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Pred 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Préd 1:1").osis()).toEqual("Eccl.1.1") p.include_apocrypha(false) expect(p.parse("PREDIKARINN 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("PRÉDIKARINN 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("PRED 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("PRÉD 1:1").osis()).toEqual("Eccl.1.1") ` true describe "Localized book SgThree (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: SgThree (is)", -> ` expect(p.parse("Lofsongur ungmennanna þriggja 1:1").osis()).toEqual("SgThree.1.1") expect(p.parse("Lofsöngur ungmennanna þriggja 1:1").osis()).toEqual("SgThree.1.1") expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1") ` true describe "Localized book Song (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Song (is)", -> ` expect(p.parse("Ljoðaljoðin 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ljoðaljóðin 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ljóðaljoðin 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ljóðaljóðin 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ljl 1:1").osis()).toEqual("Song.1.1") p.include_apocrypha(false) expect(p.parse("LJOÐALJOÐIN 1:1").osis()).toEqual("Song.1.1") expect(p.parse("LJOÐALJÓÐIN 1:1").osis()).toEqual("Song.1.1") expect(p.parse("LJÓÐALJOÐIN 1:1").osis()).toEqual("Song.1.1") expect(p.parse("LJÓÐALJÓÐIN 1:1").osis()).toEqual("Song.1.1") expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1") expect(p.parse("LJL 1:1").osis()).toEqual("Song.1.1") ` true describe "Localized book Jer (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jer (is)", -> ` expect(p.parse("Jeremia 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jeremía 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1") p.include_apocrypha(false) expect(p.parse("JEREMIA 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JEREMÍA 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1") ` true describe "Localized book Ezek (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezek (is)", -> ` expect(p.parse("Esekiel 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Esekíel 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Esk 1:1").osis()).toEqual("Ezek.1.1") p.include_apocrypha(false) expect(p.parse("ESEKIEL 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("ESEKÍEL 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("ESK 1:1").osis()).toEqual("Ezek.1.1") ` true describe "Localized book <NAME> (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (is)", -> ` expect(p.parse("<NAME> 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Daníel 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1") p.include_apocrypha(false) expect(p.parse("DANIEL 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DANÍEL 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1") ` true describe "Localized book Hos (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hos (is)", -> ` expect(p.parse("Hosea 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hósea 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hós 1:1").osis()).toEqual("Hos.1.1") p.include_apocrypha(false) expect(p.parse("HOSEA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HÓSEA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HÓS 1:1").osis()).toEqual("Hos.1.1") ` true describe "Localized book Joel (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Joel (is)", -> ` expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Jóel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Jl 1:1").osis()).toEqual("Joel.1.1") p.include_apocrypha(false) expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JÓEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JL 1:1").osis()).toEqual("Joel.1.1") ` true describe "Localized book Amos (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Amos (is)", -> ` expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Am 1:1").osis()).toEqual("Amos.1.1") p.include_apocrypha(false) expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AM 1:1").osis()).toEqual("Amos.1.1") ` true describe "Localized book Obad (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Obad (is)", -> ` expect(p.parse("Obadia 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obadía 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Óbadia 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Óbadía 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Ob 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Ób 1:1").osis()).toEqual("Obad.1.1") p.include_apocrypha(false) expect(p.parse("OBADIA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBADÍA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("ÓBADIA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("ÓBADÍA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OB 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("ÓB 1:1").osis()).toEqual("Obad.1.1") ` true describe "Localized book <NAME> (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (is)", -> ` expect(p.parse("<NAME> 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("<NAME> 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jónas 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jon 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jón 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JONAS 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JÓNAS 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JON 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JÓN 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book Mic (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME>ic (is)", -> ` expect(p.parse("Mika 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Míka 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mik 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mík 1:1").osis()).toEqual("Mic.1.1") p.include_apocrypha(false) expect(p.parse("MIKA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MÍKA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIK 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MÍK 1:1").osis()).toEqual("Mic.1.1") ` true describe "Localized book Nah (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Nah (is)", -> ` expect(p.parse("Nahum 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nahúm 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1") p.include_apocrypha(false) expect(p.parse("NAHUM 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAHÚM 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1") ` true describe "Localized book Hab (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hab (is)", -> ` expect(p.parse("Habakkuk 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1") p.include_apocrypha(false) expect(p.parse("HABAKKUK 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1") ` true describe "Localized book Zeph (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zeph (is)", -> ` expect(p.parse("Sefania 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sefanía 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sef 1:1").osis()).toEqual("Zeph.1.1") p.include_apocrypha(false) expect(p.parse("SEFANIA 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SEFANÍA 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SEF 1:1").osis()).toEqual("Zeph.1.1") ` true describe "Localized book Hag (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hag (is)", -> ` expect(p.parse("Haggai 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Haggaí 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1") p.include_apocrypha(false) expect(p.parse("HAGGAI 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAGGAÍ 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1") ` true describe "Localized book Zech (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zech (is)", -> ` expect(p.parse("Sakaria 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Sakaría 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Sak 1:1").osis()).toEqual("Zech.1.1") p.include_apocrypha(false) expect(p.parse("SAKARIA 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("SAKARÍA 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("SAK 1:1").osis()).toEqual("Zech.1.1") ` true describe "Localized book Mal (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (is)", -> ` expect(p.parse("Malaki 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Malakí 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1") p.include_apocrypha(false) expect(p.parse("MALAKI 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MALAKÍ 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1") ` true describe "Localized book <NAME> (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (is)", -> ` expect(p.parse("Matteusarguðspjall 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1") p.include_apocrypha(false) expect(p.parse("MATTEUSARGUÐSPJALL 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1") ` true describe "Localized book Mark (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mark (is)", -> ` expect(p.parse("Markusarguðspjall 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Markúsarguðspjall 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mrk 1:1").osis()).toEqual("Mark.1.1") p.include_apocrypha(false) expect(p.parse("MARKUSARGUÐSPJALL 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARKÚSARGUÐSPJALL 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MRK 1:1").osis()).toEqual("Mark.1.1") ` true describe "Localized book <NAME>uke (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME>uke (is)", -> ` expect(p.parse("Lukasarguðspjall 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Lúkasarguðspjall 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luk 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Lúk 1:1").osis()).toEqual("Luke.1.1") p.include_apocrypha(false) expect(p.parse("LUKASARGUÐSPJALL 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LÚKASARGUÐSPJALL 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUK 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LÚK 1:1").osis()).toEqual("Luke.1.1") ` true describe "Localized book 1John (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME>John (is)", -> ` expect(p.parse("Fyrsta bref Johannesar hið almenna 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bref Jóhannesar hið almenna 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bréf Johannesar hið almenna 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bréf Jóhannesar hið almenna 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bref Johannesar 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bref Jóhannesar 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bréf Johannesar 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bréf Jóhannesar 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta Johannesarbref 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta Johannesarbréf 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta Jóhannesarbref 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta Jóhannesarbréf 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Joh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Jóh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Joh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Jóh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Joh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Jóh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Joh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Jóh 1:1").osis()).toEqual("1John.1.1") p.include_apocrypha(false) expect(p.parse("FYRSTA BREF JOHANNESAR HIÐ ALMENNA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BREF JÓHANNESAR HIÐ ALMENNA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BRÉF JOHANNESAR HIÐ ALMENNA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BRÉF JÓHANNESAR HIÐ ALMENNA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BREF JOHANNESAR 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BREF JÓHANNESAR 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BRÉF JOHANNESAR 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BRÉF JÓHANNESAR 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA JOHANNESARBREF 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA JOHANNESARBRÉF 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA JÓHANNESARBREF 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA JÓHANNESARBRÉF 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. JOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. JÓH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. JOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. JÓH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 JOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 JÓH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I JOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I JÓH 1:1").osis()).toEqual("1John.1.1") ` true describe "Localized book 2John (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2John (is)", -> ` expect(p.parse("Annað bref Johannesar 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað bref Jóhannesar 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað bréf Johannesar 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað bréf Jóhannesar 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað Johannesarbref 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað Johannesarbréf 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað Jóhannesarbref 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað <NAME>bréf 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Joh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Jóh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Joh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Jóh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Joh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Jóh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Joh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Jóh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1") p.include_apocrypha(false) expect(p.parse("ANNAÐ BREF JOHANNESAR 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ BREF JÓHANNESAR 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ BRÉF JOHANNESAR 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ BRÉF JÓHANNESAR 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ JOHANNESARBREF 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ JOHANNESARBRÉF 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ JÓHANNESARBREF 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ JÓHANNESARBRÉF 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. JOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. JÓH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. JOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. JÓH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II JOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II JÓH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 JOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 JÓH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1") ` true describe "Localized book 3John (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3John (is)", -> ` expect(p.parse("Þriðja bref Johannesar 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja bref Jóhannesar 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja bréf Johannesar 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja bréf Jóhannesar 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja Johannesarbref 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja Johannesarbréf 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja Jóhannesarbref 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja Jóhannesarbréf 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Joh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Jóh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Joh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Jóh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Joh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Jóh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Joh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Jóh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1") p.include_apocrypha(false) expect(p.parse("ÞRIÐJA BREF JOHANNESAR 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA BREF JÓHANNESAR 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA BRÉF JOHANNESAR 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA BRÉF JÓHANNESAR 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA JOHANNESARBREF 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA JOHANNESARBRÉF 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA JÓHANNESARBREF 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA JÓHANNESARBRÉF 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. JOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. JÓH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III JOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III JÓH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. JOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. JÓH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 JOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 JÓH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1") ` true describe "Localized book John (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: John (is)", -> ` expect(p.parse("Johannesarguðspjall 1:1").osis()).toEqual("John.1.1") expect(p.parse("Jóhannesarguðspjall 1:1").osis()).toEqual("John.1.1") expect(p.parse("John 1:1").osis()).toEqual("John.1.1") expect(p.parse("Joh 1:1").osis()).toEqual("John.1.1") expect(p.parse("Jóh 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("JOHANNESARGUÐSPJALL 1:1").osis()).toEqual("John.1.1") expect(p.parse("JÓHANNESARGUÐSPJALL 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOH 1:1").osis()).toEqual("John.1.1") expect(p.parse("JÓH 1:1").osis()).toEqual("John.1.1") ` true describe "Localized book Acts (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Acts (is)", -> ` expect(p.parse("Postulasagan 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Post 1:1").osis()).toEqual("Acts.1.1") p.include_apocrypha(false) expect(p.parse("POSTULASAGAN 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("POST 1:1").osis()).toEqual("Acts.1.1") ` true describe "Localized book Rom (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rom (is)", -> ` expect(p.parse("Bref Pals til Romverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bref Pals til Rómverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bref Páls til Romverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bref Páls til Rómverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bréf Pals til Romverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bréf Pals til Rómverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bréf Páls til Romverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bréf Páls til Rómverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Romverjabrefið 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Romverjabréfið 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rómverjabrefið 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rómverjabréfið 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Róm 1:1").osis()).toEqual("Rom.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL ROMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BREF PALS TIL RÓMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BREF PÁLS TIL ROMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BREF PÁLS TIL RÓMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BRÉF PALS TIL ROMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BRÉF PALS TIL RÓMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BRÉF PÁLS TIL ROMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BRÉF PÁLS TIL RÓMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROMVERJABREFIÐ 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROMVERJABRÉFIÐ 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("RÓMVERJABREFIÐ 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("RÓMVERJABRÉFIÐ 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("RÓM 1:1").osis()).toEqual("Rom.1.1") ` true describe "Localized book 2Cor (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Cor (is)", -> ` expect(p.parse("Siðara bref Pals til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bref Páls til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bréf Pals til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bréf Páls til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bref Pals til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bref Páls til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bréf Pals til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bréf Páls til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bref Pals til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bref Páls til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bréf Pals til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bréf Páls til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bref Pals til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bref Páls til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bréf Pals til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bréf Páls til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara Korintubref 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara Korintubréf 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara Kórintubref 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara Kórintubréf 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara Korintubref 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara Korintubréf 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara Kórintubref 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara Kórintubréf 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARA BREF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BREF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BREF PALS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BREF PALS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA KORINTUBREF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA KORINTUBRÉF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA KÓRINTUBREF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA KÓRINTUBRÉF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA KORINTUBREF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA KORINTUBRÉF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA KÓRINTUBREF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA KÓRINTUBRÉF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1") ` true describe "Localized book 1Cor (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Cor (is)", -> ` expect(p.parse("Fyrra bref Pals til Korintumanna 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bref Páls til Korintumanna 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bréf Pals til Korintumanna 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bréf Páls til Korintumanna 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bref Pals til Korin 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bref Páls til Korin 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bréf Pals til Korin 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bréf Páls til Korin 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra Korintubref 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra Korintubréf 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1") p.include_apocrypha(false) expect(p.parse("FYRRA BREF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BREF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BRÉF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BREF PALS TIL KORIN 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BREF PÁLS TIL KORIN 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BRÉF PALS TIL KORIN 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL KORIN 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA KORINTUBREF 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA KORINTUBRÉF 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1") ` true describe "Localized book Gal (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gal (is)", -> ` expect(p.parse("Bref Pals til Galatamanna 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Bref Páls til Galatamanna 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Bréf Pals til Galatamanna 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Bréf Páls til Galatamanna 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Galatabrefið 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Galatabréfið 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL GALATAMANNA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("BREF PÁLS TIL GALATAMANNA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("BRÉF PALS TIL GALATAMANNA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("BRÉF PÁLS TIL GALATAMANNA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GALATABREFIÐ 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GALATABRÉFIÐ 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1") ` true describe "Localized book Eph (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eph (is)", -> ` expect(p.parse("Bref Pals til Efesusmanna 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Bref Páls til Efesusmanna 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Bréf Pals til Efesusmanna 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Bréf Páls til Efesusmanna 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Efesusbrefið 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Efesusbréfið 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Ef 1:1").osis()).toEqual("Eph.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL EFESUSMANNA 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("BREF PÁLS TIL EFESUSMANNA 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("BRÉF PALS TIL EFESUSMANNA 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("BRÉF PÁLS TIL EFESUSMANNA 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EFESUSBREFIÐ 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EFESUSBRÉFIÐ 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EF 1:1").osis()).toEqual("Eph.1.1") ` true describe "Localized book <NAME> (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (is)", -> ` expect(p.parse("Bref Pals til Filippimanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Pals til Filippímanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Páls til Filippimanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Páls til Filippímanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Pals til Filippimanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Pals til Filippímanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Páls til Filippimanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Páls til Filippímanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Pals til Filippimann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Pals til Filippímann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Páls til Filippimann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Páls til Filippímann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Pals til Filippimann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Pals til Filippímann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Páls til Filippimann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Páls til Filippímann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filippibrefið 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filippibréfið 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filippíbrefið 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filippíbréfið 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Fil 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL FILIPPIMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PALS TIL FILIPPÍMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PÁLS TIL FILIPPIMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PÁLS TIL FILIPPÍMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PALS TIL FILIPPIMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PALS TIL FILIPPÍMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PÁLS TIL FILIPPIMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PÁLS TIL FILIPPÍMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PALS TIL FILIPPIMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PALS TIL FILIPPÍMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PÁLS TIL FILIPPIMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PÁLS TIL FILIPPÍMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PALS TIL FILIPPIMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PALS TIL FILIPPÍMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PÁLS TIL FILIPPIMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PÁLS TIL FILIPPÍMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPPIBREFIÐ 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPPIBRÉFIÐ 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPPÍBREFIÐ 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPPÍBRÉFIÐ 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FIL 1:1").osis()).toEqual("Phil.1.1") ` true describe "Localized book Col (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Col (is)", -> ` expect(p.parse("Bref Pals til Kolossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Pals til Kólossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Páls til Kolossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Páls til Kólossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Pals til Kolossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Pals til Kólossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Páls til Kolossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Páls til Kólossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Pals til Kolossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Pals til Kólossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Páls til Kolossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Páls til Kólossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Pals til Kolossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Pals til Kólossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Páls til Kolossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Páls til Kólossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolossubrefið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolossubréfið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolussubrefið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolussubréfið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kólossubrefið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kólossubréfið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kólussubrefið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kólussubréfið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kol 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kól 1:1").osis()).toEqual("Col.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL KOLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PALS TIL KÓLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PÁLS TIL KOLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PÁLS TIL KÓLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PALS TIL KOLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PALS TIL KÓLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PÁLS TIL KOLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PÁLS TIL KÓLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PALS TIL KOLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PALS TIL KÓLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PÁLS TIL KOLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PÁLS TIL KÓLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PALS TIL KOLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PALS TIL KÓLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PÁLS TIL KOLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PÁLS TIL KÓLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLOSSUBREFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLOSSUBRÉFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLUSSUBREFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLUSSUBRÉFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KÓLOSSUBREFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KÓLOSSUBRÉFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KÓLUSSUBREFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KÓLUSSUBRÉFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KÓL 1:1").osis()).toEqual("Col.1.1") ` true describe "Localized book 2Thess (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Thess (is)", -> ` expect(p.parse("Siðara bref Pals til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bref Pals til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bref Páls til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bref Páls til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Pals til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Pals til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Páls til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Páls til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Pals til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Pals til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Páls til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Páls til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Pals til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Pals til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Páls til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Páls til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bref Pals til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bref Páls til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Pals til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Páls til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Pals til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Páls til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Pals til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Páls til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara Þessalonikubref 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara Þessalonikubréf 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara Þessaloníkubref 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara Þessaloníkubréf 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara Þessalonikubref 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara Þessalonikubréf 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara Þessaloníkubref 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara Þessaloníkubréf 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARA BREF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BREF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BREF PALS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PALS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA ÞESSALONIKUBREF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA ÞESSALONIKUBRÉF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA ÞESSALONÍKUBREF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA ÞESSALONÍKUBRÉF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA ÞESSALONIKUBREF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA ÞESSALONIKUBRÉF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA ÞESSALONÍKUBREF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA ÞESSALONÍKUBRÉF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1") ` true describe "Localized book 1Thess (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Thess (is)", -> ` expect(p.parse("Fyrra bref Pals til Þessalonikumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bref Pals til Þessaloníkumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bref Páls til Þessalonikumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bref Páls til Þessaloníkumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Pals til Þessalonikumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Pals til Þessaloníkumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Páls til Þessalonikumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Páls til Þessaloníkumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bref Pals til Þessa 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bref Páls til Þessa 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Pals til Þessa 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Páls til Þessa 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra Þessalonikubref 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra Þessalonikubréf 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra Þessaloníkubref 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra Þessaloníkubréf 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Þess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Þess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Þess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Þess 1:1").osis()).toEqual("1Thess.1.1") p.include_apocrypha(false) expect(p.parse("FYRRA BREF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BREF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BREF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BREF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BREF PALS TIL ÞESSA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BREF PÁLS TIL ÞESSA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PALS TIL ÞESSA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL ÞESSA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA ÞESSALONIKUBREF 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA ÞESSALONIKUBRÉF 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA ÞESSALONÍKUBREF 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA ÞESSALONÍKUBRÉF 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. ÞESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. ÞESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 ÞESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I ÞESS 1:1").osis()).toEqual("1Thess.1.1") ` true describe "Localized book 2Tim (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME>Tim (is)", -> ` expect(p.parse("Siðara bref Pals til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Timoteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Timoteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Timóteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Timóteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Tímoteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Tímoteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Tímóteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Tímóteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Timoteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Timoteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Timóteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Timóteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Tímoteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Tímoteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Tímóteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Tímóteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Tím 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Tím 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Tím 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Tím 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARA BREF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TIMOTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TIMOTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TIMÓTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TIMÓTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TÍMOTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TÍMOTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TÍMÓTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TÍMÓTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TIMOTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TIMOTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TIMÓTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TIMÓTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TÍMOTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TÍMOTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TÍMÓTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TÍMÓTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TÍM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TÍM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TÍM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TÍM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1") ` true describe "Localized book 1Tim (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Tim (is)", -> ` expect(p.parse("Fyrra bref Pals til Timoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Timóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Tímoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Tímóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Timoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Timóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Tímoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Tímóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Timoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Timóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Tímoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Tímóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Timoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Timóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Tímoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Tímóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Timot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Timót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Tímot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Tímót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Timot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Timót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Tímot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Tímót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Timot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Timót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Tímot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Tímót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Timot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Timót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Tímot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Tímót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Timoteusarbref 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Timoteusarbréf 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Timóteusarbref 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Timóteusarbréf 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Tímoteusarbref 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Tímoteusarbréf 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Tímóteusarbref 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Tímóteusarbréf 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Tím 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Tím 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Tím 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Tím 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1") p.include_apocrypha(false) expect(p.parse("FYRRA BREF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TIMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TIMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TÍMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TÍMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TIMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TIMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TÍMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TÍMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TIMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TIMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TÍMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TÍMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TIMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TIMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TÍMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TÍMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TIMOTEUSARBREF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TIMOTEUSARBRÉF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TIMÓTEUSARBREF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TIMÓTEUSARBRÉF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TÍMOTEUSARBREF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TÍMOTEUSARBRÉF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TÍMÓTEUSARBREF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TÍMÓTEUSARBRÉF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TÍM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TÍM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TÍM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TÍM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1") ` true describe "Localized book Titus (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Titus (is)", -> ` expect(p.parse("Bref Pals til Titusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bref Pals til Títusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bref Páls til Titusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bref Páls til Títusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bréf Pals til Titusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bréf Pals til Títusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bréf Páls til Titusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bréf Páls til Títusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titusarbrefið 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titusarbréfið 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Títusarbrefið 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Títusarbréfið 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titusarbref 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titusarbréf 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Títusarbref 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Títusarbréf 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tit 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tít 1:1").osis()).toEqual("Titus.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL TITUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BREF PALS TIL TÍTUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BREF PÁLS TIL TITUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BREF PÁLS TIL TÍTUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BRÉF PALS TIL TITUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BRÉF PALS TIL TÍTUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BRÉF PÁLS TIL TITUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BRÉF PÁLS TIL TÍTUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUSARBREFIÐ 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUSARBRÉFIÐ 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TÍTUSARBREFIÐ 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TÍTUSARBRÉFIÐ 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUSARBREF 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUSARBRÉF 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TÍTUSARBREF 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TÍTUSARBRÉF 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TIT 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TÍT 1:1").osis()).toEqual("Titus.1.1") ` true describe "Localized book Phlm (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phlm (is)", -> ` expect(p.parse("Bref Pals til Filemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bref Pals til Fílemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bref Páls til Filemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bref Páls til Fílemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bréf Pals til Filemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bréf Pals til Fílemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bréf Páls til Filemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bréf Páls til Fílemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Filemonsbrefið 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Filemonsbréfið 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Fílemonsbrefið 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Fílemonsbréfið 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Film 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Fílm 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL FILEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BREF PALS TIL FÍLEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BREF PÁLS TIL FILEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BREF PÁLS TIL FÍLEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BRÉF PALS TIL FILEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BRÉF PALS TIL FÍLEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BRÉF PÁLS TIL FILEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BRÉF PÁLS TIL FÍLEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILEMONSBREFIÐ 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILEMONSBRÉFIÐ 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FÍLEMONSBREFIÐ 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FÍLEMONSBRÉFIÐ 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FÍLM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1") ` true describe "Localized book Heb (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Heb (is)", -> ` expect(p.parse("Brefið til Hebrea 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Bréfið til Hebrea 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Hebreabrefið 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Hebreabréfið 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1") p.include_apocrypha(false) expect(p.parse("BREFIÐ TIL HEBREA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("BRÉFIÐ TIL HEBREA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEBREABREFIÐ 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEBREABRÉFIÐ 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1") ` true describe "Localized book Jas (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jas (is)", -> ` expect(p.parse("Hið almenna bref <NAME>akobs 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Hið almenna bréf <NAME>obs 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jakobsbrefið 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jakobsbréfið 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jak 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1") p.include_apocrypha(false) expect(p.parse("HIÐ ALMENNA BREF <NAME>AKOBS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("HIÐ ALMENNA BRÉF JAKOBS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAKOBSBREFIÐ 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAKOBSBRÉFIÐ 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAK 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1") ` true describe "Localized book 2Pet (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Pet (is)", -> ` expect(p.parse("Siðara almenna bref Peturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara almenna bref Péturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara almenna bréf Peturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara almenna bréf Péturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara almenna bref Peturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara almenna bref Péturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara almenna bréf Peturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara almenna bréf Péturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara Petursbref 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara Petursbréf 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara Pétursbref 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara Pétursbréf 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara Petursbref 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara Petursbréf 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara Pétursbref 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara Pétursbréf 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. Pét 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. Pét 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II Pét 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Pét 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARA ALMENNA BREF PETURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA ALMENNA BREF PÉTURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA ALMENNA BRÉF PETURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA ALMENNA BRÉF PÉTURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA ALMENNA BREF PETURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA ALMENNA BREF PÉTURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA ALMENNA BRÉF PETURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA ALMENNA BRÉF PÉTURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA PETURSBREF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA PETURSBRÉF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA PÉTURSBREF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA PÉTURSBRÉF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA PETURSBREF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA PETURSBRÉF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA PÉTURSBREF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA PÉTURSBRÉF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. PÉT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. PÉT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II PÉT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PÉT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1") ` true describe "Localized book 1Pet (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Pet (is)", -> ` expect(p.parse("Fyrra almenna bref Peturs 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra almenna bref Péturs 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra almenna bréf Peturs 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra almenna bréf Péturs 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra Petursbref 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra Petursbréf 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra Pétursbref 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra Pétursbréf 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. Pét 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. Pét 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Pét 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I Pét 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1") p.include_apocrypha(false) expect(p.parse("FYRRA ALMENNA BREF PETURS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA ALMENNA BREF PÉTURS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA ALMENNA BRÉF PETURS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA ALMENNA BRÉF PÉTURS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA PETURSBREF 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA PETURSBRÉF 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA PÉTURSBREF 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA PÉTURSBRÉF 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. PÉT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. PÉT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PÉT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I PÉT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1") ` true describe "Localized book <NAME> (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME> (is)", -> ` expect(p.parse("Hið almenna bref Judasar 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Hið almenna bref Júdasar 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Hið almenna bréf Judasar 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Hið almenna bréf Júdasar 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judasarbrefið 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judasarbréfið 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Júdasarbrefið 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Júdasarbréfið 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judasarbref 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judasarbréf 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Júdasarbref 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Júdasarbréf 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jud 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Júd 1:1").osis()).toEqual("Jude.1.1") p.include_apocrypha(false) expect(p.parse("HIÐ ALMENNA BREF JUDASAR 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("HIÐ ALMENNA BREF JÚDASAR 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("HIÐ ALMENNA BRÉF JUDASAR 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("HIÐ ALMENNA BRÉF JÚDASAR 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDASARBREFIÐ 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDASARBRÉFIÐ 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JÚDASARBREFIÐ 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JÚDASARBRÉFIÐ 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDASARBREF 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDASARBRÉF 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JÚDASARBREF 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JÚDASARBRÉF 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUD 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JÚD 1:1").osis()).toEqual("Jude.1.1") ` true describe "Localized book Tob (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Tob (is)", -> ` expect(p.parse("Tobitsbok 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tobitsbók 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tobítsbok 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tobítsbók 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tóbitsbok 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tóbitsbók 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tóbítsbok 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tóbítsbók 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1") ` true describe "Localized book Jdt (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jdt (is)", -> ` expect(p.parse("Juditarbok 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Juditarbók 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Judítarbok 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Judítarbók 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Júditarbok 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Júditarbók 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Júdítarbok 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Júdítarbók 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Judt 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Júdt 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1") ` true describe "Localized book Bar (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bar (is)", -> ` expect(p.parse("Baruksbok 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Baruksbók 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Barúksbok 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Barúksbók 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1") ` true describe "Localized book Sus (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sus (is)", -> ` expect(p.parse("<NAME> 1:1").osis()).toEqual("Sus.1.1") expect(p.parse("<NAME> 1:1").osis()).toEqual("Sus.1.1") expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1") ` true describe "Localized book 2Macc (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Macc (is)", -> ` expect(p.parse("Onnur Makkabeabok 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Onnur Makkabeabók 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Önnur Makkabeabok 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Önnur Makkabeabók 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II. Makk 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2. Makk 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II Makk 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2 Makk 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1") ` true describe "Localized book 3Macc (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3Macc (is)", -> ` expect(p.parse("Þriðja Makkabeabok 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("Þriðja Makkabeabók 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III. Makk 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III Makk 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3. Makk 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3 Makk 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1") ` true describe "Localized book 4Macc (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 4Macc (is)", -> ` expect(p.parse("Fjorða Makkabeabok 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Fjorða Makkabeabók 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Fjórða Makkabeabok 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Fjórða Makkabeabók 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV. Makk 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4. Makk 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV Makk 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4 Makk 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1") ` true describe "Localized book 1Macc (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Macc (is)", -> ` expect(p.parse("Fyrsta Makkabeabok 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("Fyrsta Makkabeabók 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1. Makk 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I. Makk 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1 Makk 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I Makk 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1") ` true describe "Miscellaneous tests", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete" p.include_apocrypha true it "should return the expected language", -> expect(p.languages).toEqual ["is"] it "should handle ranges (is)", -> expect(p.parse("Titus 1:1 - 2").osis()).toEqual "Titus.1.1-Titus.1.2" expect(p.parse("Matt 1-2").osis()).toEqual "Matt.1-Matt.2" expect(p.parse("Phlm 2 - 3").osis()).toEqual "Phlm.1.2-Phlm.1.3" it "should handle chapters (is)", -> expect(p.parse("Titus 1:1, kafli 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 KAFLI 6").osis()).toEqual "Matt.3.4,Matt.6" expect(p.parse("Titus 1:1, kafla 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 KAFLA 6").osis()).toEqual "Matt.3.4,Matt.6" expect(p.parse("Titus 1:1, kapítuli 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 KAPÍTULI 6").osis()).toEqual "Matt.3.4,Matt.6" expect(p.parse("Titus 1:1, kapituli 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 KAPITULI 6").osis()).toEqual "Matt.3.4,Matt.6" it "should handle verses (is)", -> expect(p.parse("Exod 1:1 vers 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm VERS 6").osis()).toEqual "Phlm.1.6" it "should handle 'and' (is)", -> expect(p.parse("Exod 1:1 og 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 OG 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" it "should handle titles (is)", -> expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" it "should handle 'ff' (is)", -> expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" it "should handle translations (is)", -> expect(p.parse("Lev 1 (B20)").osis_and_translations()).toEqual [["Lev.1", "B20"]] expect(p.parse("lev 1 b20").osis_and_translations()).toEqual [["Lev.1", "B20"]] it "should handle book ranges (is)", -> p.set_options {book_alone_strategy: "full", book_range_strategy: "include"} expect(p.parse("1 - 3 Joh").osis()).toEqual "1John.1-3John.1" expect(p.parse("1 - 3 Jóh").osis()).toEqual "1John.1-3John.1" it "should handle boundaries (is)", -> p.set_options {book_alone_strategy: "full"} expect(p.parse("\u2014Matt\u2014").osis()).toEqual "Matt.1-Matt.28" expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual "Matt.1.1"
true
bcv_parser = require("../../js/is_bcv_parser.js").bcv_parser describe "Parsing", -> p = {} beforeEach -> p = new bcv_parser p.options.osis_compaction_strategy = "b" p.options.sequence_combination_strategy = "combine" it "should round-trip OSIS references", -> p.set_options osis_compaction_strategy: "bc" books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PImos","PI:NAME:<NAME>END_PIad","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PIah","Hab","Zeph","Hag","Zech","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range it "should round-trip OSIS Apocrypha references", -> p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b" p.include_apocrypha true books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range p.set_options ps151_strategy: "bc" expect(p.parse("Ps151.1").osis()).toEqual "Ps.151" expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1" expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2" p.include_apocrypha false for book in books bc = book + ".1" expect(p.parse(bc).osis()).toEqual "" it "should handle a preceding character", -> expect(p.parse(" Gen 1").osis()).toEqual "Gen.1" expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3" expect(p.parse("1Ps 1").osis()).toEqual "" expect(p.parse("11Sam 1").osis()).toEqual "" describe "Localized book Gen (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gen (is)", -> ` expect(p.parse("Fyrsta bok Mose 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta bok Móse 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta bók Mose 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta bók Móse 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta Mosebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta Mosebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta Mósebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Fyrsta Mósebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MPI:NAME:<NAME>END_PIsebPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MPI:NAME:<NAME>END_PIbPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MPI:NAME:<NAME>END_PIsebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mosebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mosebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mósebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mósebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mosebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mosebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mósebok 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mósebók 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Genesis 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. Mos 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. Mós 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. Mos 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. Mós 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mos 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 Mós 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mos 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I Mós 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1Mós 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1") p.include_apocrypha(false) expect(p.parse("FYRSTA BOK MOSE 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA BOK MÓSE 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA BÓK MOSE 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA BÓK MÓSE 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA MOSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA MOSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA MÓSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("FYRSTA MÓSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MOSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MOSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MÓSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MÓSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MOSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MOSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MÓSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MÓSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MOSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MOSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MÓSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MÓSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MOSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MOSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MÓSEBOK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MÓSEBÓK 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GENESIS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1. MÓS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I. MÓS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1 MÓS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MOS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("I MÓS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("1MÓS 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1") ` true describe "Localized book Exod (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Exod (is)", -> ` expect(p.parse("Onnur bok Mose 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur bok Móse 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur bók Mose 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur bók Móse 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur bok Mose 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur bok Móse 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur bók Mose 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur bók Móse 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Onnur Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Önnur Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mosebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mosebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mósebok 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mósebók 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mos 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. Mós 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mos 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. Mós 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exodus 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mos 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II Mós 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mos 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 Mós 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2Mós 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1") p.include_apocrypha(false) expect(p.parse("ONNUR BOK MOSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR BOK MÓSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR BÓK MOSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR BÓK MÓSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR BOK MOSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR BOK MÓSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR BÓK MOSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR BÓK MÓSE 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ONNUR MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("ÖNNUR MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MOSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MOSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MÓSEBOK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MÓSEBÓK 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MOS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II. MÓS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MOS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2. MÓS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXODUS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MOS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("II MÓS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MOS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2 MÓS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("2MÓS 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1") ` true describe "Localized book Bel (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bel (is)", -> ` expect(p.parse("Bel og drekinn 1:1").osis()).toEqual("Bel.1.1") expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1") ` true describe "Localized book Lev (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lev (is)", -> ` expect(p.parse("Þriðja bok Mose 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja bok Móse 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja bók Mose 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja bók Móse 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja Mosebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja Mosebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja Mósebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Þriðja Mósebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mosebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mosebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mósebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mósebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mosebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mosebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mósebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mósebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mosebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mosebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mósebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mósebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mosebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mosebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mósebok 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mósebók 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Leviticus 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mos 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. Mós 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mos 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III Mós 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mos 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. Mós 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mos 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 Mós 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3Mós 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1") p.include_apocrypha(false) expect(p.parse("ÞRIÐJA BOK MOSE 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA BOK MÓSE 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA BÓK MOSE 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA BÓK MÓSE 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA MOSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA MOSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA MÓSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("ÞRIÐJA MÓSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MOSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MOSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MÓSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MÓSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MOSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MOSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MÓSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MÓSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MOSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MOSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MÓSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MÓSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MOSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MOSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MÓSEBOK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MÓSEBÓK 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEVITICUS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MOS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III. MÓS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MOS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("III MÓS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MOS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3. MÓS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MOS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3 MÓS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("3MÓS 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1") ` true describe "Localized book Num (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Num (is)", -> ` expect(p.parse("Fjorða bok Mose 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða bok Móse 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða bók Mose 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða bók Móse 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða bok Mose 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða bok Móse 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða bók Mose 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða bók Móse 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjorða Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Fjórða Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mosebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mosebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mósebok 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mósebók 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mos 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. Mós 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mos 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. Mós 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mos 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV Mós 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Numeri 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mos 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 Mós 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4Mós 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1") p.include_apocrypha(false) expect(p.parse("FJORÐA BOK MOSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA BOK MÓSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA BÓK MOSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA BÓK MÓSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA BOK MOSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA BOK MÓSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA BÓK MOSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA BÓK MÓSE 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJORÐA MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("FJÓRÐA MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MOSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MOSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MÓSEBOK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MÓSEBÓK 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MOS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV. MÓS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MOS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4. MÓS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MOS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("IV MÓS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUMERI 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MOS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4 MÓS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("4MÓS 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1") ` true describe "Localized book Sir (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sir (is)", -> ` expect(p.parse("Siraksbok 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Siraksbók 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Síraksbok 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Síraksbók 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1") expect(p.parse("Sír 1:1").osis()).toEqual("Sir.1.1") ` true describe "Localized book Wis (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Wis (is)", -> ` expect(p.parse("Speki Salomons 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("Speki Salómons 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("SSal 1:1").osis()).toEqual("Wis.1.1") expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1") ` true describe "Localized book Lam (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Lam (is)", -> ` expect(p.parse("Harmljoðin 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Harmljóðin 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Hlj 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1") p.include_apocrypha(false) expect(p.parse("HARMLJOÐIN 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("HARMLJÓÐIN 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("HLJ 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1") ` true describe "Localized book EpJer (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: EpJer (is)", -> ` expect(p.parse("Bref Jeremia 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("Bref Jeremía 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("Bréf Jeremia 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("Bréf Jeremía 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1") expect(p.parse("BJer 1:1").osis()).toEqual("EpJer.1.1") ` true describe "Localized book Rev (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rev (is)", -> ` expect(p.parse("OpPI:NAME:<NAME>END_PIberunarbok Johannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberunarbok Jóhannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberunarbók Johannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberunarbók Jóhannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberun Johannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberun Jóhannesar 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberunarbokin 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opinberunarbókin 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Opb 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1") p.include_apocrypha(false) expect(p.parse("OPINBERUNARBOK JOHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUNARBOK JÓHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUNARBÓK JOHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUNARBÓK JÓHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUN JOHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUN JÓHANNESAR 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUNARBOKIN 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPINBERUNARBÓKIN 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("OPB 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1") ` true describe "Localized book PrMan (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrMan (is)", -> ` expect(p.parse("Bæn Manasse 1:1").osis()).toEqual("PrMan.1.1") expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1") expect(p.parse("BMn 1:1").osis()).toEqual("PrMan.1.1") ` true describe "Localized book Deut (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Deut (is)", -> ` expect(p.parse("Fimmta bok Mose 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta bok Móse 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta bók Mose 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta bók Móse 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta Mosebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta Mosebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta Mósebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Fimmta Mósebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deuteronomium 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mosebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mosebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mósebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mósebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mosebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mosebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mósebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mósebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mosebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mosebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mósebok 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mósebók 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mos 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. Mós 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. Mos 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. Mós 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mos 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 Mós 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mos 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V Mós 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5Mós 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1") p.include_apocrypha(false) expect(p.parse("FIMMTA BOK MOSE 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA BOK MÓSE 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA BÓK MOSE 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA BÓK MÓSE 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA MOSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA MOSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA MÓSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("FIMMTA MÓSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUTERONOMIUM 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MOSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MOSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MÓSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MÓSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MOSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MOSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MÓSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MÓSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MOSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MOSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MÓSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MÓSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MOSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MOSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MÓSEBOK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MÓSEBÓK 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MOS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5. MÓS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MOS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V. MÓS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MOS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5 MÓS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MOS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("V MÓS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("5MÓS 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (is)", -> ` expect(p.parse("Josuabok 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josuabók 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josúabok 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josúabók 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jósuabok 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jósuabók 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jósúabok 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jósúabók 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jos 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Jós 1:1").osis()).toEqual("Josh.1.1") p.include_apocrypha(false) expect(p.parse("JOSUABOK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSUABÓK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSÚABOK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSÚABÓK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JÓSUABOK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JÓSUABÓK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JÓSÚABOK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JÓSÚABÓK 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOS 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JÓS 1:1").osis()).toEqual("Josh.1.1") ` true describe "Localized book Judg (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Judg (is)", -> ` expect(p.parse("Domarabokin 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Domarabókin 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dómarabokin 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dómarabókin 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Domarabok 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Domarabók 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dómarabok 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dómarabók 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dom 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Dóm 1:1").osis()).toEqual("Judg.1.1") p.include_apocrypha(false) expect(p.parse("DOMARABOKIN 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DOMARABÓKIN 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DÓMARABOKIN 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DÓMARABÓKIN 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DOMARABOK 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DOMARABÓK 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DÓMARABOK 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DÓMARABÓK 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DOM 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("DÓM 1:1").osis()).toEqual("Judg.1.1") ` true describe "Localized book Ruth (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ruth (is)", -> ` expect(p.parse("Rutarbok 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rutarbók 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Rut 1:1").osis()).toEqual("Ruth.1.1") p.include_apocrypha(false) expect(p.parse("RUTARBOK 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTARBÓK 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("RUT 1:1").osis()).toEqual("Ruth.1.1") ` true describe "Localized book 1Esd (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Esd (is)", -> ` expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1") ` true describe "Localized book 2Esd (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Esd (is)", -> ` expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1") ` true describe "Localized book Isa (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Isa (is)", -> ` expect(p.parse("Jesaja 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Jes 1:1").osis()).toEqual("Isa.1.1") p.include_apocrypha(false) expect(p.parse("JESAJA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("JES 1:1").osis()).toEqual("Isa.1.1") ` true describe "Localized book 2Sam (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Sam (is)", -> ` expect(p.parse("Siðari Samuelsbok 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Siðari Samuelsbók 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Siðari Samúelsbok 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Siðari Samúelsbók 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Síðari Samuelsbok 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Síðari Samuelsbók 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Síðari Samúelsbok 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Síðari Samúelsbók 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARI SAMUELSBOK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SIÐARI SAMUELSBÓK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SIÐARI SAMÚELSBOK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SIÐARI SAMÚELSBÓK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SÍÐARI SAMUELSBOK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SÍÐARI SAMUELSBÓK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SÍÐARI SAMÚELSBOK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SÍÐARI SAMÚELSBÓK 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1") ` true describe "Localized book 1Sam (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Sam (is)", -> ` expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1") p.include_apocrypha(false) expect(p.parse("FYRRI SAMUELSBOK 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("FYRRI SAMUELSBÓK 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("FYRRI SAMÚELSBOK 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("FYRRI SAMÚELSBÓK 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1") ` true describe "Localized book 2Kgs (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Kgs (is)", -> ` expect(p.parse("Siðari bok konunganna 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Siðari bók konunganna 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Síðari bok konunganna 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Síðari bók konunganna 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Siðari Konungabok 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Siðari Konungabók 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Síðari Konungabok 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Síðari Konungabók 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("Síðari konungabók 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. Kon 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. Kon 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II Kon 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Kon 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARI BOK KONUNGANNA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SIÐARI BÓK KONUNGANNA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SÍÐARI BOK KONUNGANNA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SÍÐARI BÓK KONUNGANNA 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SIÐARI KONUNGABOK 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SIÐARI KONUNGABÓK 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SÍÐARI KONUNGABOK 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SÍÐARI KONUNGABÓK 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("SÍÐARI KONUNGABÓK 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. KON 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. KON 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II KON 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 KON 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1") ` true describe "Localized book 1Kgs (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Kgs (is)", -> ` expect(p.parse("Fyrri bok konunganna 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Fyrri bók konunganna 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Fyrri Konungabok 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Fyrri Konungabók 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("Fyrri konungabók 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. Kon 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. Kon 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Kon 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I Kon 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1") p.include_apocrypha(false) expect(p.parse("FYRRI BOK KONUNGANNA 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("FYRRI BÓK KONUNGANNA 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("FYRRI KONUNGABOK 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("FYRRI KONUNGABÓK 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("FYRRI KONUNGABÓK 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. KON 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. KON 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 KON 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I KON 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1") ` true describe "Localized book 2Chr (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Chr (is)", -> ` expect(p.parse("Siðari Kronikubok 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Siðari Kronikubók 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Siðari Kroníkubok 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Siðari Kroníkubók 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Síðari Kronikubok 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Síðari Kronikubók 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Síðari Kroníkubok 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Síðari Kroníkubók 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("Síðari kroníkubók 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. Kro 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. Kro 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II Kro 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Kro 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARI KRONIKUBOK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SIÐARI KRONIKUBÓK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SIÐARI KRONÍKUBOK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SIÐARI KRONÍKUBÓK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SÍÐARI KRONIKUBOK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SÍÐARI KRONIKUBÓK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SÍÐARI KRONÍKUBOK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SÍÐARI KRONÍKUBÓK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("SÍÐARI KRONÍKUBÓK 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. KRO 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. KRO 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II KRO 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 KRO 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1") ` true describe "Localized book 1Chr (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Chr (is)", -> ` expect(p.parse("Fyrri Kronikubok 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Fyrri Kronikubók 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Fyrri Kroníkubok 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Fyrri Kroníkubók 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("Fyrri kroníkubók 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. Kro 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. Kro 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Kro 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I Kro 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1") p.include_apocrypha(false) expect(p.parse("FYRRI KRONIKUBOK 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("FYRRI KRONIKUBÓK 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("FYRRI KRONÍKUBOK 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("FYRRI KRONÍKUBÓK 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("FYRRI KRONÍKUBÓK 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. KRO 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. KRO 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 KRO 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I KRO 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1") ` true describe "Localized book Ezra (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezra (is)", -> ` expect(p.parse("Esrabok 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Esrabók 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Esr 1:1").osis()).toEqual("Ezra.1.1") p.include_apocrypha(false) expect(p.parse("ESRABOK 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("ESRABÓK 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("ESR 1:1").osis()).toEqual("Ezra.1.1") ` true describe "Localized book Neh (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Neh (is)", -> ` expect(p.parse("Nehemiabok 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Nehemiabók 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Nehemíabok 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Nehemíabók 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1") p.include_apocrypha(false) expect(p.parse("NEHEMIABOK 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEHEMIABÓK 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEHEMÍABOK 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEHEMÍABÓK 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1") ` true describe "Localized book GkEsth (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: GkEsth (is)", -> ` expect(p.parse("Esterarbok hin griska 1:1").osis()).toEqual("GkEsth.1.1") expect(p.parse("Esterarbok hin gríska 1:1").osis()).toEqual("GkEsth.1.1") expect(p.parse("Esterarbók hin griska 1:1").osis()).toEqual("GkEsth.1.1") expect(p.parse("Esterarbók hin gríska 1:1").osis()).toEqual("GkEsth.1.1") expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1") ` true describe "Localized book Esth (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Esth (is)", -> ` expect(p.parse("Esterarbok 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esterarbók 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1") p.include_apocrypha(false) expect(p.parse("ESTERARBOK 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTERARBÓK 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1") ` true describe "Localized book Job (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Job (is)", -> ` expect(p.parse("Jobsbok 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Jobsbók 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1") p.include_apocrypha(false) expect(p.parse("JOBSBOK 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOBSBÓK 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1") ` true describe "Localized book Ps (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ps (is)", -> ` expect(p.parse("Salmarnir 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Sálmarnir 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Slm 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1") p.include_apocrypha(false) expect(p.parse("SALMARNIR 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("SÁLMARNIR 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("SLM 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1") ` true describe "Localized book PrAzar (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PrAzar (is)", -> ` expect(p.parse("Bæn Asarja 1:1").osis()).toEqual("PrAzar.1.1") expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1") ` true describe "Localized book Prov (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Prov (is)", -> ` expect(p.parse("Orðskviðirnir 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Okv 1:1").osis()).toEqual("Prov.1.1") p.include_apocrypha(false) expect(p.parse("ORÐSKVIÐIRNIR 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("OKV 1:1").osis()).toEqual("Prov.1.1") ` true describe "Localized book Eccl (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eccl (is)", -> ` expect(p.parse("Predikarinn 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Prédikarinn 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Pred 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Préd 1:1").osis()).toEqual("Eccl.1.1") p.include_apocrypha(false) expect(p.parse("PREDIKARINN 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("PRÉDIKARINN 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("PRED 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("PRÉD 1:1").osis()).toEqual("Eccl.1.1") ` true describe "Localized book SgThree (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: SgThree (is)", -> ` expect(p.parse("Lofsongur ungmennanna þriggja 1:1").osis()).toEqual("SgThree.1.1") expect(p.parse("Lofsöngur ungmennanna þriggja 1:1").osis()).toEqual("SgThree.1.1") expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1") ` true describe "Localized book Song (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Song (is)", -> ` expect(p.parse("Ljoðaljoðin 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ljoðaljóðin 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ljóðaljoðin 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ljóðaljóðin 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Ljl 1:1").osis()).toEqual("Song.1.1") p.include_apocrypha(false) expect(p.parse("LJOÐALJOÐIN 1:1").osis()).toEqual("Song.1.1") expect(p.parse("LJOÐALJÓÐIN 1:1").osis()).toEqual("Song.1.1") expect(p.parse("LJÓÐALJOÐIN 1:1").osis()).toEqual("Song.1.1") expect(p.parse("LJÓÐALJÓÐIN 1:1").osis()).toEqual("Song.1.1") expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1") expect(p.parse("LJL 1:1").osis()).toEqual("Song.1.1") ` true describe "Localized book Jer (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jer (is)", -> ` expect(p.parse("Jeremia 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jeremía 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1") p.include_apocrypha(false) expect(p.parse("JEREMIA 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JEREMÍA 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1") ` true describe "Localized book Ezek (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Ezek (is)", -> ` expect(p.parse("Esekiel 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Esekíel 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Esk 1:1").osis()).toEqual("Ezek.1.1") p.include_apocrypha(false) expect(p.parse("ESEKIEL 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("ESEKÍEL 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("ESK 1:1").osis()).toEqual("Ezek.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (is)", -> ` expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Daníel 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1") p.include_apocrypha(false) expect(p.parse("DANIEL 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DANÍEL 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1") ` true describe "Localized book Hos (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hos (is)", -> ` expect(p.parse("Hosea 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hósea 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hós 1:1").osis()).toEqual("Hos.1.1") p.include_apocrypha(false) expect(p.parse("HOSEA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HÓSEA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HÓS 1:1").osis()).toEqual("Hos.1.1") ` true describe "Localized book Joel (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Joel (is)", -> ` expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Jóel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Jl 1:1").osis()).toEqual("Joel.1.1") p.include_apocrypha(false) expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JÓEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JL 1:1").osis()).toEqual("Joel.1.1") ` true describe "Localized book Amos (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Amos (is)", -> ` expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Am 1:1").osis()).toEqual("Amos.1.1") p.include_apocrypha(false) expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AM 1:1").osis()).toEqual("Amos.1.1") ` true describe "Localized book Obad (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Obad (is)", -> ` expect(p.parse("Obadia 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obadía 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Óbadia 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Óbadía 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Ob 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Ób 1:1").osis()).toEqual("Obad.1.1") p.include_apocrypha(false) expect(p.parse("OBADIA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBADÍA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("ÓBADIA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("ÓBADÍA 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OB 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("ÓB 1:1").osis()).toEqual("Obad.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (is)", -> ` expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jónas 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jon 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jón 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JONAS 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JÓNAS 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JON 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JÓN 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book Mic (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PIic (is)", -> ` expect(p.parse("Mika 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Míka 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mik 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mík 1:1").osis()).toEqual("Mic.1.1") p.include_apocrypha(false) expect(p.parse("MIKA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MÍKA 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIK 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MÍK 1:1").osis()).toEqual("Mic.1.1") ` true describe "Localized book Nah (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Nah (is)", -> ` expect(p.parse("Nahum 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nahúm 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1") p.include_apocrypha(false) expect(p.parse("NAHUM 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAHÚM 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1") ` true describe "Localized book Hab (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hab (is)", -> ` expect(p.parse("Habakkuk 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1") p.include_apocrypha(false) expect(p.parse("HABAKKUK 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1") ` true describe "Localized book Zeph (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zeph (is)", -> ` expect(p.parse("Sefania 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sefanía 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sef 1:1").osis()).toEqual("Zeph.1.1") p.include_apocrypha(false) expect(p.parse("SEFANIA 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SEFANÍA 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SEF 1:1").osis()).toEqual("Zeph.1.1") ` true describe "Localized book Hag (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Hag (is)", -> ` expect(p.parse("Haggai 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Haggaí 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1") p.include_apocrypha(false) expect(p.parse("HAGGAI 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAGGAÍ 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1") ` true describe "Localized book Zech (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Zech (is)", -> ` expect(p.parse("Sakaria 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Sakaría 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Sak 1:1").osis()).toEqual("Zech.1.1") p.include_apocrypha(false) expect(p.parse("SAKARIA 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("SAKARÍA 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("SAK 1:1").osis()).toEqual("Zech.1.1") ` true describe "Localized book Mal (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (is)", -> ` expect(p.parse("Malaki 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Malakí 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1") p.include_apocrypha(false) expect(p.parse("MALAKI 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MALAKÍ 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (is)", -> ` expect(p.parse("Matteusarguðspjall 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1") p.include_apocrypha(false) expect(p.parse("MATTEUSARGUÐSPJALL 1:1").osis()).toEqual("Matt.1.1") expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1") ` true describe "Localized book Mark (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Mark (is)", -> ` expect(p.parse("Markusarguðspjall 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Markúsarguðspjall 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("Mrk 1:1").osis()).toEqual("Mark.1.1") p.include_apocrypha(false) expect(p.parse("MARKUSARGUÐSPJALL 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARKÚSARGUÐSPJALL 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1") expect(p.parse("MRK 1:1").osis()).toEqual("Mark.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PIuke (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PIuke (is)", -> ` expect(p.parse("Lukasarguðspjall 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Lúkasarguðspjall 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luk 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Lúk 1:1").osis()).toEqual("Luke.1.1") p.include_apocrypha(false) expect(p.parse("LUKASARGUÐSPJALL 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LÚKASARGUÐSPJALL 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUK 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LÚK 1:1").osis()).toEqual("Luke.1.1") ` true describe "Localized book 1John (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PIJohn (is)", -> ` expect(p.parse("Fyrsta bref Johannesar hið almenna 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bref Jóhannesar hið almenna 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bréf Johannesar hið almenna 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bréf Jóhannesar hið almenna 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bref Johannesar 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bref Jóhannesar 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bréf Johannesar 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta bréf Jóhannesar 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta Johannesarbref 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta Johannesarbréf 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta Jóhannesarbref 1:1").osis()).toEqual("1John.1.1") expect(p.parse("Fyrsta Jóhannesarbréf 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Joh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Jóh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Joh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Jóh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Joh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Jóh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Joh 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Jóh 1:1").osis()).toEqual("1John.1.1") p.include_apocrypha(false) expect(p.parse("FYRSTA BREF JOHANNESAR HIÐ ALMENNA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BREF JÓHANNESAR HIÐ ALMENNA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BRÉF JOHANNESAR HIÐ ALMENNA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BRÉF JÓHANNESAR HIÐ ALMENNA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BREF JOHANNESAR 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BREF JÓHANNESAR 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BRÉF JOHANNESAR 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA BRÉF JÓHANNESAR 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA JOHANNESARBREF 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA JOHANNESARBRÉF 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA JÓHANNESARBREF 1:1").osis()).toEqual("1John.1.1") expect(p.parse("FYRSTA JÓHANNESARBRÉF 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. JOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. JÓH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. JOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. JÓH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 JOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 JÓH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I JOH 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I JÓH 1:1").osis()).toEqual("1John.1.1") ` true describe "Localized book 2John (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2John (is)", -> ` expect(p.parse("Annað bref Johannesar 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað bref Jóhannesar 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað bréf Johannesar 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað bréf Jóhannesar 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað Johannesarbref 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað Johannesarbréf 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað Jóhannesarbref 1:1").osis()).toEqual("2John.1.1") expect(p.parse("Annað PI:NAME:<NAME>END_PIbréf 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Joh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Jóh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Joh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Jóh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Joh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Jóh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Joh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Jóh 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1") p.include_apocrypha(false) expect(p.parse("ANNAÐ BREF JOHANNESAR 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ BREF JÓHANNESAR 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ BRÉF JOHANNESAR 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ BRÉF JÓHANNESAR 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ JOHANNESARBREF 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ JOHANNESARBRÉF 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ JÓHANNESARBREF 1:1").osis()).toEqual("2John.1.1") expect(p.parse("ANNAÐ JÓHANNESARBRÉF 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. JOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. JÓH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. JOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. JÓH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II JOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II JÓH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 JOH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 JÓH 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1") ` true describe "Localized book 3John (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3John (is)", -> ` expect(p.parse("Þriðja bref Johannesar 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja bref Jóhannesar 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja bréf Johannesar 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja bréf Jóhannesar 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja Johannesarbref 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja Johannesarbréf 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja Jóhannesarbref 1:1").osis()).toEqual("3John.1.1") expect(p.parse("Þriðja Jóhannesarbréf 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Joh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Jóh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Joh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Jóh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Joh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Jóh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Joh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Jóh 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1") p.include_apocrypha(false) expect(p.parse("ÞRIÐJA BREF JOHANNESAR 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA BREF JÓHANNESAR 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA BRÉF JOHANNESAR 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA BRÉF JÓHANNESAR 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA JOHANNESARBREF 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA JOHANNESARBRÉF 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA JÓHANNESARBREF 1:1").osis()).toEqual("3John.1.1") expect(p.parse("ÞRIÐJA JÓHANNESARBRÉF 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. JOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. JÓH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III JOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III JÓH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. JOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. JÓH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 JOH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 JÓH 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1") ` true describe "Localized book John (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: John (is)", -> ` expect(p.parse("Johannesarguðspjall 1:1").osis()).toEqual("John.1.1") expect(p.parse("Jóhannesarguðspjall 1:1").osis()).toEqual("John.1.1") expect(p.parse("John 1:1").osis()).toEqual("John.1.1") expect(p.parse("Joh 1:1").osis()).toEqual("John.1.1") expect(p.parse("Jóh 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("JOHANNESARGUÐSPJALL 1:1").osis()).toEqual("John.1.1") expect(p.parse("JÓHANNESARGUÐSPJALL 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOH 1:1").osis()).toEqual("John.1.1") expect(p.parse("JÓH 1:1").osis()).toEqual("John.1.1") ` true describe "Localized book Acts (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Acts (is)", -> ` expect(p.parse("Postulasagan 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Post 1:1").osis()).toEqual("Acts.1.1") p.include_apocrypha(false) expect(p.parse("POSTULASAGAN 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("POST 1:1").osis()).toEqual("Acts.1.1") ` true describe "Localized book Rom (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Rom (is)", -> ` expect(p.parse("Bref Pals til Romverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bref Pals til Rómverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bref Páls til Romverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bref Páls til Rómverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bréf Pals til Romverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bréf Pals til Rómverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bréf Páls til Romverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Bréf Páls til Rómverja 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Romverjabrefið 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Romverjabréfið 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rómverjabrefið 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rómverjabréfið 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Róm 1:1").osis()).toEqual("Rom.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL ROMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BREF PALS TIL RÓMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BREF PÁLS TIL ROMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BREF PÁLS TIL RÓMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BRÉF PALS TIL ROMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BRÉF PALS TIL RÓMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BRÉF PÁLS TIL ROMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("BRÉF PÁLS TIL RÓMVERJA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROMVERJABREFIÐ 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROMVERJABRÉFIÐ 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("RÓMVERJABREFIÐ 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("RÓMVERJABRÉFIÐ 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("RÓM 1:1").osis()).toEqual("Rom.1.1") ` true describe "Localized book 2Cor (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Cor (is)", -> ` expect(p.parse("Siðara bref Pals til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bref Páls til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bréf Pals til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bréf Páls til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bref Pals til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bref Páls til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bréf Pals til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bréf Páls til Korintumanna 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bref Pals til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bref Páls til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bréf Pals til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara bréf Páls til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bref Pals til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bref Páls til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bréf Pals til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara bréf Páls til Kori 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara Korintubref 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara Korintubréf 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara Kórintubref 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Siðara Kórintubréf 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara Korintubref 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara Korintubréf 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara Kórintubref 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("Síðara Kórintubréf 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARA BREF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BREF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BREF PALS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BREF PALS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL KORI 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA KORINTUBREF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA KORINTUBRÉF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA KÓRINTUBREF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SIÐARA KÓRINTUBRÉF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA KORINTUBREF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA KORINTUBRÉF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA KÓRINTUBREF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("SÍÐARA KÓRINTUBRÉF 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1") ` true describe "Localized book 1Cor (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Cor (is)", -> ` expect(p.parse("Fyrra bref Pals til Korintumanna 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bref Páls til Korintumanna 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bréf Pals til Korintumanna 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bréf Páls til Korintumanna 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bref Pals til Korin 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bref Páls til Korin 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bréf Pals til Korin 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra bréf Páls til Korin 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra Korintubref 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("Fyrra Korintubréf 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1") p.include_apocrypha(false) expect(p.parse("FYRRA BREF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BREF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BRÉF PALS TIL KORINTUMANNA 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL KORINTUMANNA 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BREF PALS TIL KORIN 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BREF PÁLS TIL KORIN 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BRÉF PALS TIL KORIN 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL KORIN 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA KORINTUBREF 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("FYRRA KORINTUBRÉF 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1") ` true describe "Localized book Gal (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Gal (is)", -> ` expect(p.parse("Bref Pals til Galatamanna 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Bref Páls til Galatamanna 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Bréf Pals til Galatamanna 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Bréf Páls til Galatamanna 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Galatabrefið 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Galatabréfið 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL GALATAMANNA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("BREF PÁLS TIL GALATAMANNA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("BRÉF PALS TIL GALATAMANNA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("BRÉF PÁLS TIL GALATAMANNA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GALATABREFIÐ 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GALATABRÉFIÐ 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1") ` true describe "Localized book Eph (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Eph (is)", -> ` expect(p.parse("Bref Pals til Efesusmanna 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Bref Páls til Efesusmanna 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Bréf Pals til Efesusmanna 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Bréf Páls til Efesusmanna 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Efesusbrefið 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Efesusbréfið 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("Ef 1:1").osis()).toEqual("Eph.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL EFESUSMANNA 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("BREF PÁLS TIL EFESUSMANNA 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("BRÉF PALS TIL EFESUSMANNA 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("BRÉF PÁLS TIL EFESUSMANNA 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EFESUSBREFIÐ 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EFESUSBRÉFIÐ 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1") expect(p.parse("EF 1:1").osis()).toEqual("Eph.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (is)", -> ` expect(p.parse("Bref Pals til Filippimanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Pals til Filippímanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Páls til Filippimanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Páls til Filippímanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Pals til Filippimanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Pals til Filippímanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Páls til Filippimanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Páls til Filippímanna 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Pals til Filippimann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Pals til Filippímann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Páls til Filippimann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bref Páls til Filippímann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Pals til Filippimann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Pals til Filippímann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Páls til Filippimann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Bréf Páls til Filippímann 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filippibrefið 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filippibréfið 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filippíbrefið 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Filippíbréfið 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Fil 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL FILIPPIMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PALS TIL FILIPPÍMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PÁLS TIL FILIPPIMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PÁLS TIL FILIPPÍMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PALS TIL FILIPPIMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PALS TIL FILIPPÍMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PÁLS TIL FILIPPIMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PÁLS TIL FILIPPÍMANNA 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PALS TIL FILIPPIMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PALS TIL FILIPPÍMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PÁLS TIL FILIPPIMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BREF PÁLS TIL FILIPPÍMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PALS TIL FILIPPIMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PALS TIL FILIPPÍMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PÁLS TIL FILIPPIMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("BRÉF PÁLS TIL FILIPPÍMANN 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPPIBREFIÐ 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPPIBRÉFIÐ 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPPÍBREFIÐ 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FILIPPÍBRÉFIÐ 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FIL 1:1").osis()).toEqual("Phil.1.1") ` true describe "Localized book Col (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Col (is)", -> ` expect(p.parse("Bref Pals til Kolossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Pals til Kólossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Páls til Kolossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Páls til Kólossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Pals til Kolossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Pals til Kólossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Páls til Kolossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Páls til Kólossumanna 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Pals til Kolossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Pals til Kólossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Páls til Kolossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bref Páls til Kólossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Pals til Kolossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Pals til Kólossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Páls til Kolossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Bréf Páls til Kólossumann 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolossubrefið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolossubréfið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolussubrefið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kolussubréfið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kólossubrefið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kólossubréfið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kólussubrefið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kólussubréfið 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kol 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kól 1:1").osis()).toEqual("Col.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL KOLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PALS TIL KÓLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PÁLS TIL KOLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PÁLS TIL KÓLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PALS TIL KOLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PALS TIL KÓLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PÁLS TIL KOLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PÁLS TIL KÓLOSSUMANNA 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PALS TIL KOLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PALS TIL KÓLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PÁLS TIL KOLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BREF PÁLS TIL KÓLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PALS TIL KOLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PALS TIL KÓLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PÁLS TIL KOLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("BRÉF PÁLS TIL KÓLOSSUMANN 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLOSSUBREFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLOSSUBRÉFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLUSSUBREFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOLUSSUBRÉFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KÓLOSSUBREFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KÓLOSSUBRÉFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KÓLUSSUBREFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KÓLUSSUBRÉFIÐ 1:1").osis()).toEqual("Col.1.1") expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KÓL 1:1").osis()).toEqual("Col.1.1") ` true describe "Localized book 2Thess (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Thess (is)", -> ` expect(p.parse("Siðara bref Pals til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bref Pals til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bref Páls til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bref Páls til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Pals til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Pals til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Páls til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Páls til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Pals til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Pals til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Páls til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Páls til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Pals til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Pals til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Páls til Þessalonikumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Páls til Þessaloníkumanna 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bref Pals til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bref Páls til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Pals til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara bréf Páls til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Pals til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bref Páls til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Pals til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara bréf Páls til Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara Þessalonikubref 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara Þessalonikubréf 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara Þessaloníkubref 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Siðara Þessaloníkubréf 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara Þessalonikubref 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara Þessalonikubréf 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara Þessaloníkubref 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("Síðara Þessaloníkubréf 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Þess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARA BREF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BREF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BREF PALS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PALS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA ÞESSALONIKUBREF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA ÞESSALONIKUBRÉF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA ÞESSALONÍKUBREF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SIÐARA ÞESSALONÍKUBRÉF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA ÞESSALONIKUBREF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA ÞESSALONIKUBRÉF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA ÞESSALONÍKUBREF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("SÍÐARA ÞESSALONÍKUBRÉF 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 ÞESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1") ` true describe "Localized book 1Thess (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Thess (is)", -> ` expect(p.parse("Fyrra bref Pals til Þessalonikumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bref Pals til Þessaloníkumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bref Páls til Þessalonikumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bref Páls til Þessaloníkumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Pals til Þessalonikumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Pals til Þessaloníkumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Páls til Þessalonikumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Páls til Þessaloníkumanna 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bref Pals til Þessa 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bref Páls til Þessa 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Pals til Þessa 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra bréf Páls til Þessa 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra Þessalonikubref 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra Þessalonikubréf 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra Þessaloníkubref 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("Fyrra Þessaloníkubréf 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Þess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Þess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Þess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Þess 1:1").osis()).toEqual("1Thess.1.1") p.include_apocrypha(false) expect(p.parse("FYRRA BREF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BREF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BREF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BREF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PALS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PALS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL ÞESSALONIKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL ÞESSALONÍKUMANNA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BREF PALS TIL ÞESSA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BREF PÁLS TIL ÞESSA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PALS TIL ÞESSA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL ÞESSA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA ÞESSALONIKUBREF 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA ÞESSALONIKUBRÉF 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA ÞESSALONÍKUBREF 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("FYRRA ÞESSALONÍKUBRÉF 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. ÞESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. ÞESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 ÞESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I ÞESS 1:1").osis()).toEqual("1Thess.1.1") ` true describe "Localized book 2Tim (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PITim (is)", -> ` expect(p.parse("Siðara bref Pals til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Timoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Timóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Tímoteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Tímóteusar 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Pals til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bref Páls til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Pals til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara bréf Páls til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Pals til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bref Páls til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Pals til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Timo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Timó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Tímo 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara bréf Páls til Tímó 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Timoteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Timoteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Timóteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Timóteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Tímoteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Tímoteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Tímóteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Siðara Tímóteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Timoteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Timoteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Timóteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Timóteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Tímoteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Tímoteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Tímóteusarbref 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("Síðara Tímóteusarbréf 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Tím 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Tím 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Tím 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Tím 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARA BREF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PALS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BREF PÁLS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PALS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA BRÉF PÁLS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PALS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BREF PÁLS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PALS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TIMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TIMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TÍMO 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA BRÉF PÁLS TIL TÍMÓ 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TIMOTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TIMOTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TIMÓTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TIMÓTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TÍMOTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TÍMOTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TÍMÓTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SIÐARA TÍMÓTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TIMOTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TIMOTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TIMÓTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TIMÓTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TÍMOTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TÍMOTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TÍMÓTEUSARBREF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("SÍÐARA TÍMÓTEUSARBRÉF 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TÍM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TÍM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TÍM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TÍM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1") ` true describe "Localized book 1Tim (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Tim (is)", -> ` expect(p.parse("Fyrra bref Pals til Timoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Timóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Tímoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Tímóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Timoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Timóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Tímoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Tímóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Timoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Timóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Tímoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Tímóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Timoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Timóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Tímoteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Tímóteusar 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Timot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Timót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Tímot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Pals til Tímót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Timot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Timót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Tímot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bref Páls til Tímót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Timot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Timót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Tímot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Pals til Tímót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Timot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Timót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Tímot 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra bréf Páls til Tímót 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Timoteusarbref 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Timoteusarbréf 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Timóteusarbref 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Timóteusarbréf 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Tímoteusarbref 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Tímoteusarbréf 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Tímóteusarbref 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("Fyrra Tímóteusarbréf 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Tím 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Tím 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Tím 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Tím 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1") p.include_apocrypha(false) expect(p.parse("FYRRA BREF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TIMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TIMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TÍMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TIMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TIMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TÍMOTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TÍMÓTEUSAR 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TIMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TIMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TÍMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PALS TIL TÍMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TIMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TIMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TÍMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BREF PÁLS TIL TÍMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TIMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TIMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TÍMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PALS TIL TÍMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TIMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TIMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TÍMOT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA BRÉF PÁLS TIL TÍMÓT 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TIMOTEUSARBREF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TIMOTEUSARBRÉF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TIMÓTEUSARBREF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TIMÓTEUSARBRÉF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TÍMOTEUSARBREF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TÍMOTEUSARBRÉF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TÍMÓTEUSARBREF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("FYRRA TÍMÓTEUSARBRÉF 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TÍM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TÍM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TÍM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TÍM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1") ` true describe "Localized book Titus (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Titus (is)", -> ` expect(p.parse("Bref Pals til Titusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bref Pals til Títusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bref Páls til Titusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bref Páls til Títusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bréf Pals til Titusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bréf Pals til Títusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bréf Páls til Titusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Bréf Páls til Títusar 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titusarbrefið 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titusarbréfið 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Títusarbrefið 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Títusarbréfið 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titusarbref 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titusarbréf 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Títusarbref 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Títusarbréf 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tit 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tít 1:1").osis()).toEqual("Titus.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL TITUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BREF PALS TIL TÍTUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BREF PÁLS TIL TITUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BREF PÁLS TIL TÍTUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BRÉF PALS TIL TITUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BRÉF PALS TIL TÍTUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BRÉF PÁLS TIL TITUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("BRÉF PÁLS TIL TÍTUSAR 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUSARBREFIÐ 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUSARBRÉFIÐ 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TÍTUSARBREFIÐ 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TÍTUSARBRÉFIÐ 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUSARBREF 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUSARBRÉF 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TÍTUSARBREF 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TÍTUSARBRÉF 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TIT 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TÍT 1:1").osis()).toEqual("Titus.1.1") ` true describe "Localized book Phlm (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Phlm (is)", -> ` expect(p.parse("Bref Pals til Filemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bref Pals til Fílemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bref Páls til Filemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bref Páls til Fílemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bréf Pals til Filemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bréf Pals til Fílemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bréf Páls til Filemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Bréf Páls til Fílemons 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Filemonsbrefið 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Filemonsbréfið 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Fílemonsbrefið 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Fílemonsbréfið 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Film 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Fílm 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1") p.include_apocrypha(false) expect(p.parse("BREF PALS TIL FILEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BREF PALS TIL FÍLEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BREF PÁLS TIL FILEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BREF PÁLS TIL FÍLEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BRÉF PALS TIL FILEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BRÉF PALS TIL FÍLEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BRÉF PÁLS TIL FILEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("BRÉF PÁLS TIL FÍLEMONS 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILEMONSBREFIÐ 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILEMONSBRÉFIÐ 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FÍLEMONSBREFIÐ 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FÍLEMONSBRÉFIÐ 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FILM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("FÍLM 1:1").osis()).toEqual("Phlm.1.1") expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1") ` true describe "Localized book Heb (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Heb (is)", -> ` expect(p.parse("Brefið til Hebrea 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Bréfið til Hebrea 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Hebreabrefið 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Hebreabréfið 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1") p.include_apocrypha(false) expect(p.parse("BREFIÐ TIL HEBREA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("BRÉFIÐ TIL HEBREA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEBREABREFIÐ 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEBREABRÉFIÐ 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1") ` true describe "Localized book Jas (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jas (is)", -> ` expect(p.parse("Hið almenna bref PI:NAME:<NAME>END_PIakobs 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Hið almenna bréf PI:NAME:<NAME>END_PIobs 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jakobsbrefið 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jakobsbréfið 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jak 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1") p.include_apocrypha(false) expect(p.parse("HIÐ ALMENNA BREF PI:NAME:<NAME>END_PIAKOBS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("HIÐ ALMENNA BRÉF JAKOBS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAKOBSBREFIÐ 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAKOBSBRÉFIÐ 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAK 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1") ` true describe "Localized book 2Pet (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Pet (is)", -> ` expect(p.parse("Siðara almenna bref Peturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara almenna bref Péturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara almenna bréf Peturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara almenna bréf Péturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara almenna bref Peturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara almenna bref Péturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara almenna bréf Peturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara almenna bréf Péturs 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara Petursbref 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara Petursbréf 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara Pétursbref 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Siðara Pétursbréf 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara Petursbref 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara Petursbréf 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara Pétursbref 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("Síðara Pétursbréf 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. Pét 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. Pét 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II Pét 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Pet 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Pét 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1") p.include_apocrypha(false) expect(p.parse("SIÐARA ALMENNA BREF PETURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA ALMENNA BREF PÉTURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA ALMENNA BRÉF PETURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA ALMENNA BRÉF PÉTURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA ALMENNA BREF PETURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA ALMENNA BREF PÉTURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA ALMENNA BRÉF PETURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA ALMENNA BRÉF PÉTURS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA PETURSBREF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA PETURSBRÉF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA PÉTURSBREF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SIÐARA PÉTURSBRÉF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA PETURSBREF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA PETURSBRÉF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA PÉTURSBREF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("SÍÐARA PÉTURSBRÉF 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. PÉT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. PÉT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II PÉT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PET 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 PÉT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1") ` true describe "Localized book 1Pet (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Pet (is)", -> ` expect(p.parse("Fyrra almenna bref Peturs 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra almenna bref Péturs 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra almenna bréf Peturs 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra almenna bréf Péturs 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra Petursbref 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra Petursbréf 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra Pétursbref 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("Fyrra Pétursbréf 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. Pét 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. Pét 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Pét 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I Pet 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I Pét 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1") p.include_apocrypha(false) expect(p.parse("FYRRA ALMENNA BREF PETURS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA ALMENNA BREF PÉTURS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA ALMENNA BRÉF PETURS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA ALMENNA BRÉF PÉTURS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA PETURSBREF 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA PETURSBRÉF 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA PÉTURSBREF 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("FYRRA PÉTURSBRÉF 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. PÉT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. PÉT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 PÉT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I PET 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I PÉT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PI (is)", -> ` expect(p.parse("Hið almenna bref Judasar 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Hið almenna bref Júdasar 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Hið almenna bréf Judasar 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Hið almenna bréf Júdasar 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judasarbrefið 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judasarbréfið 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Júdasarbrefið 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Júdasarbréfið 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judasarbref 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Judasarbréf 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Júdasarbref 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Júdasarbréf 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jud 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Júd 1:1").osis()).toEqual("Jude.1.1") p.include_apocrypha(false) expect(p.parse("HIÐ ALMENNA BREF JUDASAR 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("HIÐ ALMENNA BREF JÚDASAR 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("HIÐ ALMENNA BRÉF JUDASAR 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("HIÐ ALMENNA BRÉF JÚDASAR 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDASARBREFIÐ 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDASARBRÉFIÐ 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JÚDASARBREFIÐ 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JÚDASARBRÉFIÐ 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDASARBREF 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDASARBRÉF 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JÚDASARBREF 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JÚDASARBRÉF 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUD 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JÚD 1:1").osis()).toEqual("Jude.1.1") ` true describe "Localized book Tob (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Tob (is)", -> ` expect(p.parse("Tobitsbok 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tobitsbók 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tobítsbok 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tobítsbók 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tóbitsbok 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tóbitsbók 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tóbítsbok 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tóbítsbók 1:1").osis()).toEqual("Tob.1.1") expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1") ` true describe "Localized book Jdt (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Jdt (is)", -> ` expect(p.parse("Juditarbok 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Juditarbók 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Judítarbok 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Judítarbók 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Júditarbok 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Júditarbók 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Júdítarbok 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Júdítarbók 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Judt 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Júdt 1:1").osis()).toEqual("Jdt.1.1") expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1") ` true describe "Localized book Bar (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Bar (is)", -> ` expect(p.parse("Baruksbok 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Baruksbók 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Barúksbok 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Barúksbók 1:1").osis()).toEqual("Bar.1.1") expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1") ` true describe "Localized book Sus (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: Sus (is)", -> ` expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Sus.1.1") expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Sus.1.1") expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1") ` true describe "Localized book 2Macc (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 2Macc (is)", -> ` expect(p.parse("Onnur Makkabeabok 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Onnur Makkabeabók 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Önnur Makkabeabok 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("Önnur Makkabeabók 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II. Makk 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2. Makk 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("II Makk 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2 Makk 1:1").osis()).toEqual("2Macc.1.1") expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1") ` true describe "Localized book 3Macc (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 3Macc (is)", -> ` expect(p.parse("Þriðja Makkabeabok 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("Þriðja Makkabeabók 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III. Makk 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("III Makk 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3. Makk 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3 Makk 1:1").osis()).toEqual("3Macc.1.1") expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1") ` true describe "Localized book 4Macc (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 4Macc (is)", -> ` expect(p.parse("Fjorða Makkabeabok 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Fjorða Makkabeabók 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Fjórða Makkabeabok 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("Fjórða Makkabeabók 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV. Makk 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4. Makk 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("IV Makk 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4 Makk 1:1").osis()).toEqual("4Macc.1.1") expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1") ` true describe "Localized book 1Macc (is)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: 1Macc (is)", -> ` expect(p.parse("Fyrsta Makkabeabok 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("Fyrsta Makkabeabók 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1. Makk 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I. Makk 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1 Makk 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("I Makk 1:1").osis()).toEqual("1Macc.1.1") expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1") ` true describe "Miscellaneous tests", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete" p.include_apocrypha true it "should return the expected language", -> expect(p.languages).toEqual ["is"] it "should handle ranges (is)", -> expect(p.parse("Titus 1:1 - 2").osis()).toEqual "Titus.1.1-Titus.1.2" expect(p.parse("Matt 1-2").osis()).toEqual "Matt.1-Matt.2" expect(p.parse("Phlm 2 - 3").osis()).toEqual "Phlm.1.2-Phlm.1.3" it "should handle chapters (is)", -> expect(p.parse("Titus 1:1, kafli 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 KAFLI 6").osis()).toEqual "Matt.3.4,Matt.6" expect(p.parse("Titus 1:1, kafla 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 KAFLA 6").osis()).toEqual "Matt.3.4,Matt.6" expect(p.parse("Titus 1:1, kapítuli 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 KAPÍTULI 6").osis()).toEqual "Matt.3.4,Matt.6" expect(p.parse("Titus 1:1, kapituli 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 KAPITULI 6").osis()).toEqual "Matt.3.4,Matt.6" it "should handle verses (is)", -> expect(p.parse("Exod 1:1 vers 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm VERS 6").osis()).toEqual "Phlm.1.6" it "should handle 'and' (is)", -> expect(p.parse("Exod 1:1 og 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 OG 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" it "should handle titles (is)", -> expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" it "should handle 'ff' (is)", -> expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" it "should handle translations (is)", -> expect(p.parse("Lev 1 (B20)").osis_and_translations()).toEqual [["Lev.1", "B20"]] expect(p.parse("lev 1 b20").osis_and_translations()).toEqual [["Lev.1", "B20"]] it "should handle book ranges (is)", -> p.set_options {book_alone_strategy: "full", book_range_strategy: "include"} expect(p.parse("1 - 3 Joh").osis()).toEqual "1John.1-3John.1" expect(p.parse("1 - 3 Jóh").osis()).toEqual "1John.1-3John.1" it "should handle boundaries (is)", -> p.set_options {book_alone_strategy: "full"} expect(p.parse("\u2014Matt\u2014").osis()).toEqual "Matt.1-Matt.28" expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual "Matt.1.1"
[ { "context": "oGLib\n# Module | Stat Methods\n# Author | Sherif Emabrak\n# Description | The hull method returns the conve", "end": 163, "score": 0.9998723268508911, "start": 149, "tag": "NAME", "value": "Sherif Emabrak" } ]
src/lib/statistics/link/hull.coffee
Sherif-Embarak/gp-test
0
# ------------------------------------------------------------------------------ # Project | GoGLib # Module | Stat Methods # Author | Sherif Emabrak # Description | The hull method returns the convex hull of a set of # points, which is the set of edges connecting the outermost # nodes in a planar graph. # ------------------------------------------------------------------------------ hull = () ->
16162
# ------------------------------------------------------------------------------ # Project | GoGLib # Module | Stat Methods # Author | <NAME> # Description | The hull method returns the convex hull of a set of # points, which is the set of edges connecting the outermost # nodes in a planar graph. # ------------------------------------------------------------------------------ hull = () ->
true
# ------------------------------------------------------------------------------ # Project | GoGLib # Module | Stat Methods # Author | PI:NAME:<NAME>END_PI # Description | The hull method returns the convex hull of a set of # points, which is the set of edges connecting the outermost # nodes in a planar graph. # ------------------------------------------------------------------------------ hull = () ->
[ { "context": "#\n# Cookie notice CoffeeScript file.\n#\n# @author Matthew Casey\n#\n# (c) University of Surrey 2019\n#\n\n#\n# Initiali", "end": 62, "score": 0.9998668432235718, "start": 49, "tag": "NAME", "value": "Matthew Casey" } ]
app/assets/javascripts/cookie_notice.coffee
saschneider/VMVLedger
0
# # Cookie notice CoffeeScript file. # # @author Matthew Casey # # (c) University of Surrey 2019 # # # Initialise whenever the page is loaded. # $ -> $(document).on 'click', '[data-dismiss-cookie-notice]', (event) -> VMV.dismissCookieNotice(@) event.preventDefault() # # Dismisses the cookie notice and sets a cookie. # # @param target The target element. # VMV.dismissCookieNotice = (target) -> toHide = $(target).attr('data-target') document.cookie = 'dismiss_cookie_notice=1; path=/' $(toHide).hide() return
124885
# # Cookie notice CoffeeScript file. # # @author <NAME> # # (c) University of Surrey 2019 # # # Initialise whenever the page is loaded. # $ -> $(document).on 'click', '[data-dismiss-cookie-notice]', (event) -> VMV.dismissCookieNotice(@) event.preventDefault() # # Dismisses the cookie notice and sets a cookie. # # @param target The target element. # VMV.dismissCookieNotice = (target) -> toHide = $(target).attr('data-target') document.cookie = 'dismiss_cookie_notice=1; path=/' $(toHide).hide() return
true
# # Cookie notice CoffeeScript file. # # @author PI:NAME:<NAME>END_PI # # (c) University of Surrey 2019 # # # Initialise whenever the page is loaded. # $ -> $(document).on 'click', '[data-dismiss-cookie-notice]', (event) -> VMV.dismissCookieNotice(@) event.preventDefault() # # Dismisses the cookie notice and sets a cookie. # # @param target The target element. # VMV.dismissCookieNotice = (target) -> toHide = $(target).attr('data-target') document.cookie = 'dismiss_cookie_notice=1; path=/' $(toHide).hide() return
[ { "context": " username: sftpUsername\n password: sftpPassword\n sftpTarget: argv.sftpTarget\n\n th", "end": 5567, "score": 0.9631576538085938, "start": 5555, "tag": "PASSWORD", "value": "sftpPassword" }, { "context": " new Sftp\n host: host\n username: username\n password: password\n logger: lo", "end": 5871, "score": 0.9760592579841614, "start": 5863, "tag": "USERNAME", "value": "username" }, { "context": "t\n username: username\n password: password\n logger: logger\n\n sftpClient.open", "end": 5900, "score": 0.9991371631622314, "start": 5892, "tag": "PASSWORD", "value": "password" } ]
src/coffee/run.coffee
alfinonet/commercetools-customer-export
0
path = require 'path' _ = require 'underscore' Promise = require 'bluebird' fs = Promise.promisifyAll require('fs') tmp = Promise.promisifyAll require('tmp') {ExtendedLogger, ProjectCredentialsConfig, Sftp} = require 'sphere-node-utils' package_json = require '../package.json' CustomerExport = require './customerexport' argv = require('optimist') .usage('Usage: $0 --projectKey key --clientId id --clientSecret secret') .describe('projectKey', 'your commercetools platform project-key') .describe('clientId', 'your OAuth client id for the commercetools platform API') .describe('clientSecret', 'your OAuth client secret for the commercetools platform API') .describe('accessToken', 'an OAuth access token for the SPHERE.IO API, used instead of clientId and clientSecret') .describe('sphereHost', 'SPHERE.IO API host to connect to') .describe('where', 'where predicate used to filter customers exported. More info here http://dev.commercetools.com/http-api.html#predicates') .describe('targetDir', 'the folder where exported files are saved') .describe('useExportTmpDir', 'whether to use a system tmp folder to store exported files') .describe('csvTemplate', 'CSV template to define the structure of the export') .describe('fileWithTimestamp', 'whether exported file should contain a timestamp') .describe('sftpCredentials', 'the path to a JSON file where to read the credentials from') .describe('sftpHost', 'the SFTP host (overwrite value in sftpCredentials JSON, if given)') .describe('sftpUsername', 'the SFTP username (overwrite value in sftpCredentials JSON, if given)') .describe('sftpPassword', 'the SFTP password (overwrite value in sftpCredentials JSON, if given)') .describe('sftpTarget', 'path in the SFTP server to where to move the worked files') .describe('sftpContinueOnProblems', 'ignore errors when processing a file and continue with the next one') .describe('logLevel', 'log level for file logging') .describe('logDir', 'directory to store logs') .describe('logSilent', 'use console to print messages') .describe('timeout', 'Set timeout for requests') .default('targetDir', path.join(__dirname,'../exports')) .default('useExportTmpDir', false) .default('fileWithTimestamp', false) .default('logLevel', 'info') .default('logDir', '.') .default('logSilent', false) .default('timeout', 60000) .default('sftpContinueOnProblems', false) .demand(['projectKey']) .argv logOptions = name: "#{package_json.name}-#{package_json.version}" streams: [ { level: 'error', stream: process.stderr } { level: argv.logLevel, path: "#{argv.logDir}/#{package_json.name}.log" } ] logOptions.silent = argv.logSilent if argv.logSilent logger = new ExtendedLogger additionalFields: project_key: argv.projectKey logConfig: logOptions if argv.logSilent logger.bunyanLogger.trace = -> # noop logger.bunyanLogger.debug = -> # noop process.on 'exit', => process.exit(@exitCode) tmp.setGracefulCleanup() fsExistsAsync = (path) -> new Promise (resolve, reject) -> fs.exists path, (exists) -> if exists resolve(true) else resolve(false) ensureExportDir = -> if "#{argv.useExportTmpDir}" is 'true' # unsafeCleanup: recursively removes the created temporary directory, even when it's not empty tmp.dirAsync {unsafeCleanup: true} else exportsPath = argv.targetDir fsExistsAsync(exportsPath) .then (exists) -> if exists Promise.resolve(exportsPath) else fs.mkdirAsync(exportsPath) .then -> Promise.resolve(exportsPath) readJsonFromPath = (path) -> return Promise.resolve({}) unless path fs.readFileAsync(path, {encoding: 'utf-8'}).then (content) -> Promise.resolve JSON.parse(content) ensureCredentials = ({ accessToken, projectKey, clientId, clientSecret }) -> if accessToken Promise.resolve config: project_key: projectKey access_token: accessToken else ProjectCredentialsConfig.create() .then (credentials) -> Promise.resolve config: credentials.enrichCredentials project_key: projectKey client_id: clientId client_secret: clientSecret ensureCredentials(argv) .then (credentials) -> clientOptions = _.extend credentials, timeout: argv.timeout user_agent: "#{package_json.name} - #{package_json.version}" clientOptions.host = argv.sphereHost if argv.sphereHost customerExport = new CustomerExport client: clientOptions export: where: argv.where csvTemplate: argv.csvTemplate || "#{__dirname}/../data/template-customer-simple.csv" ensureExportDir() .then (outputDir) => logger.debug "Created output dir at #{outputDir}" @outputDir = outputDir customerExport.run() .then (data) => @customerReferences = [] ts = (new Date()).getTime() if argv.fileWithTimestamp fileName = "customers_#{ts}.csv" else fileName = 'customers.csv' csvFile = "#{@outputDir}/#{fileName}" logger.info "Storing CSV export to '#{csvFile}'." fs.writeFileAsync csvFile, data .then => {sftpCredentials, sftpHost, sftpUsername, sftpPassword} = argv if sftpCredentials or (sftpHost and sftpUsername and sftpPassword) readJsonFromPath(sftpCredentials) .then (credentials) => projectSftpCredentials = credentials[argv.projectKey] or {} {host, username, password, sftpTarget} = _.defaults projectSftpCredentials, host: sftpHost username: sftpUsername password: sftpPassword sftpTarget: argv.sftpTarget throw new Error 'Missing sftp host' unless host throw new Error 'Missing sftp username' unless username throw new Error 'Missing sftp password' unless password sftpClient = new Sftp host: host username: username password: password logger: logger sftpClient.openSftp() .then (sftp) => fs.readdirAsync(@outputDir) .then (files) => logger.info "About to upload #{_.size files} file(s) from #{@outputDir} to #{sftpTarget}" filesSkipped = 0 Promise.map files, (filename) => logger.debug "Uploading #{@outputDir}/#{filename}" sftpClient.safePutFile(sftp, "#{@outputDir}/#{filename}", "#{sftpTarget}/#{filename}") .then -> logger.debug "Upload of #{filename} successful." .catch (err) -> if argv.sftpContinueOnProblems filesSkipped++ logger.warn err, "There was an error processing the file #{file}, skipping and continue" Promise.resolve() else Promise.reject err , {concurrency: 1} .then -> totFiles = _.size(files) if totFiles > 0 logger.info "Export to SFTP successfully finished: #{totFiles - filesSkipped} out of #{totFiles} files were processed" else logger.info "Export successfully finished: there were no new files to be processed" sftpClient.close(sftp) Promise.resolve() .finally -> sftpClient.close(sftp) .catch (err) => logger.error err, 'There was an error uploading the files to SFTP' @exitCode = 1 .catch (err) => logger.error err, "Problems on getting sftp credentials from config files for project #{argv.projectKey}." @exitCode = 1 else Promise.resolve() # no sftp .then => logger.info 'Customer export complete' @exitCode = 0 .catch (error) => logger.error error, 'Oops, something went wrong!' @exitCode = 1 .done() .catch (err) => logger.error err, 'Problems on getting client credentials from config files.' @exitCode = 1 .done()
68903
path = require 'path' _ = require 'underscore' Promise = require 'bluebird' fs = Promise.promisifyAll require('fs') tmp = Promise.promisifyAll require('tmp') {ExtendedLogger, ProjectCredentialsConfig, Sftp} = require 'sphere-node-utils' package_json = require '../package.json' CustomerExport = require './customerexport' argv = require('optimist') .usage('Usage: $0 --projectKey key --clientId id --clientSecret secret') .describe('projectKey', 'your commercetools platform project-key') .describe('clientId', 'your OAuth client id for the commercetools platform API') .describe('clientSecret', 'your OAuth client secret for the commercetools platform API') .describe('accessToken', 'an OAuth access token for the SPHERE.IO API, used instead of clientId and clientSecret') .describe('sphereHost', 'SPHERE.IO API host to connect to') .describe('where', 'where predicate used to filter customers exported. More info here http://dev.commercetools.com/http-api.html#predicates') .describe('targetDir', 'the folder where exported files are saved') .describe('useExportTmpDir', 'whether to use a system tmp folder to store exported files') .describe('csvTemplate', 'CSV template to define the structure of the export') .describe('fileWithTimestamp', 'whether exported file should contain a timestamp') .describe('sftpCredentials', 'the path to a JSON file where to read the credentials from') .describe('sftpHost', 'the SFTP host (overwrite value in sftpCredentials JSON, if given)') .describe('sftpUsername', 'the SFTP username (overwrite value in sftpCredentials JSON, if given)') .describe('sftpPassword', 'the SFTP password (overwrite value in sftpCredentials JSON, if given)') .describe('sftpTarget', 'path in the SFTP server to where to move the worked files') .describe('sftpContinueOnProblems', 'ignore errors when processing a file and continue with the next one') .describe('logLevel', 'log level for file logging') .describe('logDir', 'directory to store logs') .describe('logSilent', 'use console to print messages') .describe('timeout', 'Set timeout for requests') .default('targetDir', path.join(__dirname,'../exports')) .default('useExportTmpDir', false) .default('fileWithTimestamp', false) .default('logLevel', 'info') .default('logDir', '.') .default('logSilent', false) .default('timeout', 60000) .default('sftpContinueOnProblems', false) .demand(['projectKey']) .argv logOptions = name: "#{package_json.name}-#{package_json.version}" streams: [ { level: 'error', stream: process.stderr } { level: argv.logLevel, path: "#{argv.logDir}/#{package_json.name}.log" } ] logOptions.silent = argv.logSilent if argv.logSilent logger = new ExtendedLogger additionalFields: project_key: argv.projectKey logConfig: logOptions if argv.logSilent logger.bunyanLogger.trace = -> # noop logger.bunyanLogger.debug = -> # noop process.on 'exit', => process.exit(@exitCode) tmp.setGracefulCleanup() fsExistsAsync = (path) -> new Promise (resolve, reject) -> fs.exists path, (exists) -> if exists resolve(true) else resolve(false) ensureExportDir = -> if "#{argv.useExportTmpDir}" is 'true' # unsafeCleanup: recursively removes the created temporary directory, even when it's not empty tmp.dirAsync {unsafeCleanup: true} else exportsPath = argv.targetDir fsExistsAsync(exportsPath) .then (exists) -> if exists Promise.resolve(exportsPath) else fs.mkdirAsync(exportsPath) .then -> Promise.resolve(exportsPath) readJsonFromPath = (path) -> return Promise.resolve({}) unless path fs.readFileAsync(path, {encoding: 'utf-8'}).then (content) -> Promise.resolve JSON.parse(content) ensureCredentials = ({ accessToken, projectKey, clientId, clientSecret }) -> if accessToken Promise.resolve config: project_key: projectKey access_token: accessToken else ProjectCredentialsConfig.create() .then (credentials) -> Promise.resolve config: credentials.enrichCredentials project_key: projectKey client_id: clientId client_secret: clientSecret ensureCredentials(argv) .then (credentials) -> clientOptions = _.extend credentials, timeout: argv.timeout user_agent: "#{package_json.name} - #{package_json.version}" clientOptions.host = argv.sphereHost if argv.sphereHost customerExport = new CustomerExport client: clientOptions export: where: argv.where csvTemplate: argv.csvTemplate || "#{__dirname}/../data/template-customer-simple.csv" ensureExportDir() .then (outputDir) => logger.debug "Created output dir at #{outputDir}" @outputDir = outputDir customerExport.run() .then (data) => @customerReferences = [] ts = (new Date()).getTime() if argv.fileWithTimestamp fileName = "customers_#{ts}.csv" else fileName = 'customers.csv' csvFile = "#{@outputDir}/#{fileName}" logger.info "Storing CSV export to '#{csvFile}'." fs.writeFileAsync csvFile, data .then => {sftpCredentials, sftpHost, sftpUsername, sftpPassword} = argv if sftpCredentials or (sftpHost and sftpUsername and sftpPassword) readJsonFromPath(sftpCredentials) .then (credentials) => projectSftpCredentials = credentials[argv.projectKey] or {} {host, username, password, sftpTarget} = _.defaults projectSftpCredentials, host: sftpHost username: sftpUsername password: <PASSWORD> sftpTarget: argv.sftpTarget throw new Error 'Missing sftp host' unless host throw new Error 'Missing sftp username' unless username throw new Error 'Missing sftp password' unless password sftpClient = new Sftp host: host username: username password: <PASSWORD> logger: logger sftpClient.openSftp() .then (sftp) => fs.readdirAsync(@outputDir) .then (files) => logger.info "About to upload #{_.size files} file(s) from #{@outputDir} to #{sftpTarget}" filesSkipped = 0 Promise.map files, (filename) => logger.debug "Uploading #{@outputDir}/#{filename}" sftpClient.safePutFile(sftp, "#{@outputDir}/#{filename}", "#{sftpTarget}/#{filename}") .then -> logger.debug "Upload of #{filename} successful." .catch (err) -> if argv.sftpContinueOnProblems filesSkipped++ logger.warn err, "There was an error processing the file #{file}, skipping and continue" Promise.resolve() else Promise.reject err , {concurrency: 1} .then -> totFiles = _.size(files) if totFiles > 0 logger.info "Export to SFTP successfully finished: #{totFiles - filesSkipped} out of #{totFiles} files were processed" else logger.info "Export successfully finished: there were no new files to be processed" sftpClient.close(sftp) Promise.resolve() .finally -> sftpClient.close(sftp) .catch (err) => logger.error err, 'There was an error uploading the files to SFTP' @exitCode = 1 .catch (err) => logger.error err, "Problems on getting sftp credentials from config files for project #{argv.projectKey}." @exitCode = 1 else Promise.resolve() # no sftp .then => logger.info 'Customer export complete' @exitCode = 0 .catch (error) => logger.error error, 'Oops, something went wrong!' @exitCode = 1 .done() .catch (err) => logger.error err, 'Problems on getting client credentials from config files.' @exitCode = 1 .done()
true
path = require 'path' _ = require 'underscore' Promise = require 'bluebird' fs = Promise.promisifyAll require('fs') tmp = Promise.promisifyAll require('tmp') {ExtendedLogger, ProjectCredentialsConfig, Sftp} = require 'sphere-node-utils' package_json = require '../package.json' CustomerExport = require './customerexport' argv = require('optimist') .usage('Usage: $0 --projectKey key --clientId id --clientSecret secret') .describe('projectKey', 'your commercetools platform project-key') .describe('clientId', 'your OAuth client id for the commercetools platform API') .describe('clientSecret', 'your OAuth client secret for the commercetools platform API') .describe('accessToken', 'an OAuth access token for the SPHERE.IO API, used instead of clientId and clientSecret') .describe('sphereHost', 'SPHERE.IO API host to connect to') .describe('where', 'where predicate used to filter customers exported. More info here http://dev.commercetools.com/http-api.html#predicates') .describe('targetDir', 'the folder where exported files are saved') .describe('useExportTmpDir', 'whether to use a system tmp folder to store exported files') .describe('csvTemplate', 'CSV template to define the structure of the export') .describe('fileWithTimestamp', 'whether exported file should contain a timestamp') .describe('sftpCredentials', 'the path to a JSON file where to read the credentials from') .describe('sftpHost', 'the SFTP host (overwrite value in sftpCredentials JSON, if given)') .describe('sftpUsername', 'the SFTP username (overwrite value in sftpCredentials JSON, if given)') .describe('sftpPassword', 'the SFTP password (overwrite value in sftpCredentials JSON, if given)') .describe('sftpTarget', 'path in the SFTP server to where to move the worked files') .describe('sftpContinueOnProblems', 'ignore errors when processing a file and continue with the next one') .describe('logLevel', 'log level for file logging') .describe('logDir', 'directory to store logs') .describe('logSilent', 'use console to print messages') .describe('timeout', 'Set timeout for requests') .default('targetDir', path.join(__dirname,'../exports')) .default('useExportTmpDir', false) .default('fileWithTimestamp', false) .default('logLevel', 'info') .default('logDir', '.') .default('logSilent', false) .default('timeout', 60000) .default('sftpContinueOnProblems', false) .demand(['projectKey']) .argv logOptions = name: "#{package_json.name}-#{package_json.version}" streams: [ { level: 'error', stream: process.stderr } { level: argv.logLevel, path: "#{argv.logDir}/#{package_json.name}.log" } ] logOptions.silent = argv.logSilent if argv.logSilent logger = new ExtendedLogger additionalFields: project_key: argv.projectKey logConfig: logOptions if argv.logSilent logger.bunyanLogger.trace = -> # noop logger.bunyanLogger.debug = -> # noop process.on 'exit', => process.exit(@exitCode) tmp.setGracefulCleanup() fsExistsAsync = (path) -> new Promise (resolve, reject) -> fs.exists path, (exists) -> if exists resolve(true) else resolve(false) ensureExportDir = -> if "#{argv.useExportTmpDir}" is 'true' # unsafeCleanup: recursively removes the created temporary directory, even when it's not empty tmp.dirAsync {unsafeCleanup: true} else exportsPath = argv.targetDir fsExistsAsync(exportsPath) .then (exists) -> if exists Promise.resolve(exportsPath) else fs.mkdirAsync(exportsPath) .then -> Promise.resolve(exportsPath) readJsonFromPath = (path) -> return Promise.resolve({}) unless path fs.readFileAsync(path, {encoding: 'utf-8'}).then (content) -> Promise.resolve JSON.parse(content) ensureCredentials = ({ accessToken, projectKey, clientId, clientSecret }) -> if accessToken Promise.resolve config: project_key: projectKey access_token: accessToken else ProjectCredentialsConfig.create() .then (credentials) -> Promise.resolve config: credentials.enrichCredentials project_key: projectKey client_id: clientId client_secret: clientSecret ensureCredentials(argv) .then (credentials) -> clientOptions = _.extend credentials, timeout: argv.timeout user_agent: "#{package_json.name} - #{package_json.version}" clientOptions.host = argv.sphereHost if argv.sphereHost customerExport = new CustomerExport client: clientOptions export: where: argv.where csvTemplate: argv.csvTemplate || "#{__dirname}/../data/template-customer-simple.csv" ensureExportDir() .then (outputDir) => logger.debug "Created output dir at #{outputDir}" @outputDir = outputDir customerExport.run() .then (data) => @customerReferences = [] ts = (new Date()).getTime() if argv.fileWithTimestamp fileName = "customers_#{ts}.csv" else fileName = 'customers.csv' csvFile = "#{@outputDir}/#{fileName}" logger.info "Storing CSV export to '#{csvFile}'." fs.writeFileAsync csvFile, data .then => {sftpCredentials, sftpHost, sftpUsername, sftpPassword} = argv if sftpCredentials or (sftpHost and sftpUsername and sftpPassword) readJsonFromPath(sftpCredentials) .then (credentials) => projectSftpCredentials = credentials[argv.projectKey] or {} {host, username, password, sftpTarget} = _.defaults projectSftpCredentials, host: sftpHost username: sftpUsername password: PI:PASSWORD:<PASSWORD>END_PI sftpTarget: argv.sftpTarget throw new Error 'Missing sftp host' unless host throw new Error 'Missing sftp username' unless username throw new Error 'Missing sftp password' unless password sftpClient = new Sftp host: host username: username password: PI:PASSWORD:<PASSWORD>END_PI logger: logger sftpClient.openSftp() .then (sftp) => fs.readdirAsync(@outputDir) .then (files) => logger.info "About to upload #{_.size files} file(s) from #{@outputDir} to #{sftpTarget}" filesSkipped = 0 Promise.map files, (filename) => logger.debug "Uploading #{@outputDir}/#{filename}" sftpClient.safePutFile(sftp, "#{@outputDir}/#{filename}", "#{sftpTarget}/#{filename}") .then -> logger.debug "Upload of #{filename} successful." .catch (err) -> if argv.sftpContinueOnProblems filesSkipped++ logger.warn err, "There was an error processing the file #{file}, skipping and continue" Promise.resolve() else Promise.reject err , {concurrency: 1} .then -> totFiles = _.size(files) if totFiles > 0 logger.info "Export to SFTP successfully finished: #{totFiles - filesSkipped} out of #{totFiles} files were processed" else logger.info "Export successfully finished: there were no new files to be processed" sftpClient.close(sftp) Promise.resolve() .finally -> sftpClient.close(sftp) .catch (err) => logger.error err, 'There was an error uploading the files to SFTP' @exitCode = 1 .catch (err) => logger.error err, "Problems on getting sftp credentials from config files for project #{argv.projectKey}." @exitCode = 1 else Promise.resolve() # no sftp .then => logger.info 'Customer export complete' @exitCode = 0 .catch (error) => logger.error error, 'Oops, something went wrong!' @exitCode = 1 .done() .catch (err) => logger.error err, 'Problems on getting client credentials from config files.' @exitCode = 1 .done()
[ { "context": "// Defaults to \"account_admin\"\n cacheKey: 'myapp.admin.session'\n })\n\n admin.ready.then(function () {\n ", "end": 372, "score": 0.678455650806427, "start": 353, "tag": "KEY", "value": "myapp.admin.session" }, { "context": ")'\n 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#construct", "end": 617, "score": 0.9990646243095398, "start": 609, "tag": "USERNAME", "value": "hoodiehq" }, { "context": "account-client/tree/master/admin#constructor'\n\n 'admin username':\n 'prefix': 'admin username'\n 'body': 'adm", "end": 689, "score": 0.7662672400474548, "start": 675, "tag": "USERNAME", "value": "admin username" }, { "context": "#constructor'\n\n 'admin username':\n 'prefix': 'admin username'\n 'body': 'admin.username'\n 'description': ", "end": 721, "score": 0.8868573904037476, "start": 707, "tag": "USERNAME", "value": "admin username" }, { "context": "ame':\n 'prefix': 'admin username'\n 'body': 'admin.username'\n 'description': 'Returns the username if sign", "end": 750, "score": 0.9988208413124084, "start": 736, "tag": "USERNAME", "value": "admin.username" }, { "context": " in, otherwise undefined'\n 'rightLabelHTML' : 'admin.username'\n 'descriptionMoreURL' : 'https://github.com/h", "end": 866, "score": 0.9987983107566833, "start": 852, "tag": "USERNAME", "value": "admin.username" }, { "context": "e'\n 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminuser", "end": 923, "score": 0.9991252422332764, "start": 915, "tag": "USERNAME", "value": "hoodiehq" }, { "context": "/hoodiehq/hoodie-account-client/tree/master/admin#adminusername'\n\n 'admin isSignedIn':\n 'prefix': 'isSignedIn", "end": 977, "score": 0.9985066652297974, "start": 964, "tag": "USERNAME", "value": "adminusername" }, { "context": ")'\n 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminissi", "end": 1244, "score": 0.9991243481636047, "start": 1236, "tag": "USERNAME", "value": "hoodiehq" }, { "context": ")'\n 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminissi", "end": 1567, "score": 0.9991304278373718, "start": 1559, "tag": "USERNAME", "value": "hoodiehq" }, { "context": " 'body': \"\"\"\n admin.signIn({username:'${1:username}', password: '${2:password}'})then(function (sess", "end": 1725, "score": 0.9741086959838867, "start": 1717, "tag": "USERNAME", "value": "username" }, { "context": " admin.signIn({username:'${1:username}', password: '${2:password}'})then(function (sessionProperties) {\n ", "end": 1743, "score": 0.9496389031410217, "start": 1739, "tag": "PASSWORD", "value": "'${2" }, { "context": ".signIn({username:'${1:username}', password: '${2:password}'})then(function (sessionProperties) {\n ${", "end": 1752, "score": 0.8971683979034424, "start": 1744, "tag": "PASSWORD", "value": "password" }, { "context": ")'\n 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsign", "end": 2056, "score": 0.9986889362335205, "start": 2048, "tag": "USERNAME", "value": "hoodiehq" }, { "context": ")'\n 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsign", "end": 2521, "score": 0.9981350302696228, "start": 2513, "tag": "USERNAME", "value": "hoodiehq" }, { "context": " admin.sessions.add({\n username: '${1:pat}'\n }).then(function (sessionProperties) {\n ", "end": 2699, "score": 0.8335820436477661, "start": 2696, "tag": "USERNAME", "value": "pat" }, { "context": ")'\n 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsess", "end": 3009, "score": 0.9974136352539062, "start": 3001, "tag": "USERNAME", "value": "hoodiehq" }, { "context": ")'\n 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsess", "end": 3620, "score": 0.9978470206260681, "start": 3612, "tag": "USERNAME", "value": "hoodiehq" }, { "context": ")'\n 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsess", "end": 4103, "score": 0.9992620348930359, "start": 4095, "tag": "USERNAME", "value": "hoodiehq" }, { "context": ")'\n 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsess", "end": 4606, "score": 0.999076783657074, "start": 4598, "tag": "USERNAME", "value": "hoodiehq" }, { "context": ")'\n 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsess", "end": 5219, "score": 0.9992907643318176, "start": 5211, "tag": "USERNAME", "value": "hoodiehq" } ]
snippets/admin-snippets.cson
distalx/hoodie-api-atom
0
'.source.js': 'admin constructor': 'prefix': 'new AccountAdmin' 'body': """ var admin = new AccountAdmin({ // required. Path or full URL to root location of the account JSON API url: '/api', // name of localStorage key where to persist the session state. // Defaults to "account_admin" cacheKey: 'myapp.admin.session' }) admin.ready.then(function () { // admin API is now ready }) """ 'description': 'Admin constructor' 'rightLabelHTML' : 'new AccountAdmin(options)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#constructor' 'admin username': 'prefix': 'admin username' 'body': 'admin.username' 'description': 'Returns the username if signed in, otherwise undefined' 'rightLabelHTML' : 'admin.username' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminusername' 'admin isSignedIn': 'prefix': 'isSignedIn' 'body': 'admin.isSignedIn()' 'description': 'Returns true if user is currently signed in, otherwise false.' 'rightLabelHTML' : 'admin.isSignedIn()' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminissignedin' 'admin isSignedIn': 'prefix': 'isSignedIn' 'body': 'admin.isSignedIn()' 'description': 'Returns true if user is currently signed in, otherwise false.' 'rightLabelHTML' : 'admin.isSignedIn()' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminissignedin' 'admin signIn': 'prefix': 'signIn' 'body': """ admin.signIn({username:'${1:username}', password: '${2:password}'})then(function (sessionProperties) { ${4:alert(sessionProperties)} }).catch(function (error) { ${5:alert(error)} })$6 """ 'description': 'Creates a user session.' 'rightLabelHTML' : 'admin.signIn(options)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsignin' 'admin signOut': 'prefix': 'signOut' 'body': """ admin.signOut().then(function (sessionProperties) { ${1:alert('Bye, ' + sessionProperties.account.username)} }).catch(function (error) { ${2:alert(error)} }) """ 'description': 'Deletes the user’s session' 'rightLabelHTML' : 'admin.signOut(options)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsignout' 'admin sessions add': 'prefix': 'sessions add' 'body': """ admin.sessions.add({ username: '${1:pat}' }).then(function (sessionProperties) { $2 }).catch(function (error) { ${3:console.error(error)} })$4 """ 'description': 'Admins can create a session for any user.' 'rightLabelHTML' : 'admin.sessions.add()' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsessionsadd' 'admin sessions find': 'prefix': 'sessions find' 'body': """ admin.sessions.find(${1:sessionId}).then(function (sessionProperties) { ${2:alert('Session is valid.')} }).catch(function (error) { if (error.name === 'NotFoundError') { ${3:alert('Session is invalid')} return } console.error(error) })$4 """ 'description': 'Resolves with sessionProperties' 'rightLabelHTML' : 'admin.sessions.find(sessionId)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsessionsfind' 'admin sessions find all': 'prefix': 'sessions findAll' 'body': """ admin.sessions.findAll() .then(function (rendrenderSessions) { }) .catch(function (error) { ${2:console.error(error)} })$3 """ 'description': 'Resolves with Array of sessionProperties' 'rightLabelHTML' : 'admin.sessions.findAll(options)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsessionsfindall' 'admin sessions remove': 'prefix': 'sessions remove' 'body': """ admin.sessions.remove(${1:sessionId}).then(function (sessionProperties) { ${2:alert('Session invalidated')} }).catch(function (error) { ${3:console.error(error)} })$4 """ 'description': 'Remove session by id' 'rightLabelHTML' : 'admin.sessions.remove(sessionId)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsessionsremove' 'admin sessions remove all': 'prefix': 'sessions removeAll' 'body': """ admin.sessions.removeAll().then(function (sessionProperties) { ${1:alert('All Sessions invalidated.')} }).catch(function (error) { if (error.name === 'NotFoundError') { ${2:alert('Session is invalid')} return } ${3:console.error(error)} })$4 """ 'description': 'Remove all sessions' 'rightLabelHTML' : 'admin.sessions.removeAll()' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsessionsremoveall'
91246
'.source.js': 'admin constructor': 'prefix': 'new AccountAdmin' 'body': """ var admin = new AccountAdmin({ // required. Path or full URL to root location of the account JSON API url: '/api', // name of localStorage key where to persist the session state. // Defaults to "account_admin" cacheKey: '<KEY>' }) admin.ready.then(function () { // admin API is now ready }) """ 'description': 'Admin constructor' 'rightLabelHTML' : 'new AccountAdmin(options)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#constructor' 'admin username': 'prefix': 'admin username' 'body': 'admin.username' 'description': 'Returns the username if signed in, otherwise undefined' 'rightLabelHTML' : 'admin.username' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminusername' 'admin isSignedIn': 'prefix': 'isSignedIn' 'body': 'admin.isSignedIn()' 'description': 'Returns true if user is currently signed in, otherwise false.' 'rightLabelHTML' : 'admin.isSignedIn()' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminissignedin' 'admin isSignedIn': 'prefix': 'isSignedIn' 'body': 'admin.isSignedIn()' 'description': 'Returns true if user is currently signed in, otherwise false.' 'rightLabelHTML' : 'admin.isSignedIn()' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminissignedin' 'admin signIn': 'prefix': 'signIn' 'body': """ admin.signIn({username:'${1:username}', password: <PASSWORD>:<PASSWORD>}'})then(function (sessionProperties) { ${4:alert(sessionProperties)} }).catch(function (error) { ${5:alert(error)} })$6 """ 'description': 'Creates a user session.' 'rightLabelHTML' : 'admin.signIn(options)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsignin' 'admin signOut': 'prefix': 'signOut' 'body': """ admin.signOut().then(function (sessionProperties) { ${1:alert('Bye, ' + sessionProperties.account.username)} }).catch(function (error) { ${2:alert(error)} }) """ 'description': 'Deletes the user’s session' 'rightLabelHTML' : 'admin.signOut(options)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsignout' 'admin sessions add': 'prefix': 'sessions add' 'body': """ admin.sessions.add({ username: '${1:pat}' }).then(function (sessionProperties) { $2 }).catch(function (error) { ${3:console.error(error)} })$4 """ 'description': 'Admins can create a session for any user.' 'rightLabelHTML' : 'admin.sessions.add()' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsessionsadd' 'admin sessions find': 'prefix': 'sessions find' 'body': """ admin.sessions.find(${1:sessionId}).then(function (sessionProperties) { ${2:alert('Session is valid.')} }).catch(function (error) { if (error.name === 'NotFoundError') { ${3:alert('Session is invalid')} return } console.error(error) })$4 """ 'description': 'Resolves with sessionProperties' 'rightLabelHTML' : 'admin.sessions.find(sessionId)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsessionsfind' 'admin sessions find all': 'prefix': 'sessions findAll' 'body': """ admin.sessions.findAll() .then(function (rendrenderSessions) { }) .catch(function (error) { ${2:console.error(error)} })$3 """ 'description': 'Resolves with Array of sessionProperties' 'rightLabelHTML' : 'admin.sessions.findAll(options)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsessionsfindall' 'admin sessions remove': 'prefix': 'sessions remove' 'body': """ admin.sessions.remove(${1:sessionId}).then(function (sessionProperties) { ${2:alert('Session invalidated')} }).catch(function (error) { ${3:console.error(error)} })$4 """ 'description': 'Remove session by id' 'rightLabelHTML' : 'admin.sessions.remove(sessionId)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsessionsremove' 'admin sessions remove all': 'prefix': 'sessions removeAll' 'body': """ admin.sessions.removeAll().then(function (sessionProperties) { ${1:alert('All Sessions invalidated.')} }).catch(function (error) { if (error.name === 'NotFoundError') { ${2:alert('Session is invalid')} return } ${3:console.error(error)} })$4 """ 'description': 'Remove all sessions' 'rightLabelHTML' : 'admin.sessions.removeAll()' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsessionsremoveall'
true
'.source.js': 'admin constructor': 'prefix': 'new AccountAdmin' 'body': """ var admin = new AccountAdmin({ // required. Path or full URL to root location of the account JSON API url: '/api', // name of localStorage key where to persist the session state. // Defaults to "account_admin" cacheKey: 'PI:KEY:<KEY>END_PI' }) admin.ready.then(function () { // admin API is now ready }) """ 'description': 'Admin constructor' 'rightLabelHTML' : 'new AccountAdmin(options)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#constructor' 'admin username': 'prefix': 'admin username' 'body': 'admin.username' 'description': 'Returns the username if signed in, otherwise undefined' 'rightLabelHTML' : 'admin.username' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminusername' 'admin isSignedIn': 'prefix': 'isSignedIn' 'body': 'admin.isSignedIn()' 'description': 'Returns true if user is currently signed in, otherwise false.' 'rightLabelHTML' : 'admin.isSignedIn()' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminissignedin' 'admin isSignedIn': 'prefix': 'isSignedIn' 'body': 'admin.isSignedIn()' 'description': 'Returns true if user is currently signed in, otherwise false.' 'rightLabelHTML' : 'admin.isSignedIn()' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminissignedin' 'admin signIn': 'prefix': 'signIn' 'body': """ admin.signIn({username:'${1:username}', password: PI:PASSWORD:<PASSWORD>END_PI:PI:PASSWORD:<PASSWORD>END_PI}'})then(function (sessionProperties) { ${4:alert(sessionProperties)} }).catch(function (error) { ${5:alert(error)} })$6 """ 'description': 'Creates a user session.' 'rightLabelHTML' : 'admin.signIn(options)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsignin' 'admin signOut': 'prefix': 'signOut' 'body': """ admin.signOut().then(function (sessionProperties) { ${1:alert('Bye, ' + sessionProperties.account.username)} }).catch(function (error) { ${2:alert(error)} }) """ 'description': 'Deletes the user’s session' 'rightLabelHTML' : 'admin.signOut(options)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsignout' 'admin sessions add': 'prefix': 'sessions add' 'body': """ admin.sessions.add({ username: '${1:pat}' }).then(function (sessionProperties) { $2 }).catch(function (error) { ${3:console.error(error)} })$4 """ 'description': 'Admins can create a session for any user.' 'rightLabelHTML' : 'admin.sessions.add()' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsessionsadd' 'admin sessions find': 'prefix': 'sessions find' 'body': """ admin.sessions.find(${1:sessionId}).then(function (sessionProperties) { ${2:alert('Session is valid.')} }).catch(function (error) { if (error.name === 'NotFoundError') { ${3:alert('Session is invalid')} return } console.error(error) })$4 """ 'description': 'Resolves with sessionProperties' 'rightLabelHTML' : 'admin.sessions.find(sessionId)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsessionsfind' 'admin sessions find all': 'prefix': 'sessions findAll' 'body': """ admin.sessions.findAll() .then(function (rendrenderSessions) { }) .catch(function (error) { ${2:console.error(error)} })$3 """ 'description': 'Resolves with Array of sessionProperties' 'rightLabelHTML' : 'admin.sessions.findAll(options)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsessionsfindall' 'admin sessions remove': 'prefix': 'sessions remove' 'body': """ admin.sessions.remove(${1:sessionId}).then(function (sessionProperties) { ${2:alert('Session invalidated')} }).catch(function (error) { ${3:console.error(error)} })$4 """ 'description': 'Remove session by id' 'rightLabelHTML' : 'admin.sessions.remove(sessionId)' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsessionsremove' 'admin sessions remove all': 'prefix': 'sessions removeAll' 'body': """ admin.sessions.removeAll().then(function (sessionProperties) { ${1:alert('All Sessions invalidated.')} }).catch(function (error) { if (error.name === 'NotFoundError') { ${2:alert('Session is invalid')} return } ${3:console.error(error)} })$4 """ 'description': 'Remove all sessions' 'rightLabelHTML' : 'admin.sessions.removeAll()' 'descriptionMoreURL' : 'https://github.com/hoodiehq/hoodie-account-client/tree/master/admin#adminsessionsremoveall'
[ { "context": "ic: (browser)->\n browser.fill \"Name\", \"ArmBiter\"\n \"should set text field\": (browser)->\n ", "end": 5607, "score": 0.9996221661567688, "start": 5599, "tag": "NAME", "value": "ArmBiter" }, { "context": "qual browser.querySelector(\"#field-name\").value, \"ArmBiter\"\n \"should fire change event\": (browser)-", "end": 5734, "score": 0.9995715022087097, "start": 5726, "tag": "NAME", "value": "ArmBiter" }, { "context": "c: (browser)->\n browser.fill \"Email\", \"armbiter@example.com\"\n \"should set email field\": (browser)->\n", "end": 5958, "score": 0.9999262094497681, "start": 5938, "tag": "EMAIL", "value": "armbiter@example.com" }, { "context": "ual browser.querySelector(\"#field-email\").value, \"armbiter@example.com\"\n \"should fire change event\": (browser)-", "end": 6099, "score": 0.9999275803565979, "start": 6079, "tag": "EMAIL", "value": "armbiter@example.com" }, { "context": "c: (browser)->\n browser.fill \"likes\", \"Arm Biting\"\n \"should set textarea\": (browser)->\n ", "end": 6303, "score": 0.9995465278625488, "start": 6293, "tag": "NAME", "value": "Arm Biting" }, { "context": "ual browser.querySelector(\"#field-likes\").value, \"Arm Biting\"\n \"should fire change event\": (browser)-", "end": 6431, "score": 0.9994890689849854, "start": 6421, "tag": "NAME", "value": "Arm Biting" }, { "context": " browser.fill \":password[name=password]\", \"b100d\"\n \"should set password\": (browser)->\n ", "end": 6653, "score": 0.9994190335273743, "start": 6648, "tag": "PASSWORD", "value": "b100d" }, { "context": " browser.querySelector(\"#field-password\").value, \"b100d\"\n \"should fire change event\": (browser)-", "end": 6779, "score": 0.9994510412216187, "start": 6774, "tag": "PASSWORD", "value": "b100d" }, { "context": "ser.fill browser.querySelector(\"#field-email2\"), \"headchomper@example.com\"\n \"should set email2 field\": (browser)->", "end": 7392, "score": 0.9999269247055054, "start": 7369, "tag": "EMAIL", "value": "headchomper@example.com" }, { "context": "al browser.querySelector(\"#field-email2\").value, \"headchomper@example.com\"\n \"should fire change event\": (browser)-", "end": 7538, "score": 0.9999291896820068, "start": 7515, "tag": "EMAIL", "value": "headchomper@example.com" }, { "context": "ser.fill browser.querySelector(\"#field-email3\"), \"headchomper@example.com\", @callback\n \"should fire the callback\":", "end": 7780, "score": 0.9999281167984009, "start": 7757, "tag": "EMAIL", "value": "headchomper@example.com" }, { "context": "al browser.querySelector(\"#field-email3\").value, \"headchomper@example.com\"\n\n\n \"check box\":\n Browser.wants \"http://l", "end": 7941, "score": 0.9999293088912964, "start": 7918, "tag": "EMAIL", "value": "headchomper@example.com" }, { "context": "ic: (browser)->\n browser.fill(\"Name\", \"ArmBiter\").fill(\"likes\", \"Arm Biting\").\n chec", "end": 17324, "score": 0.9995277523994446, "start": 17316, "tag": "NAME", "value": "ArmBiter" }, { "context": " browser.fill(\"Name\", \"ArmBiter\").fill(\"likes\", \"Arm Biting\").\n check(\"You bet\").choose(\"Scary\")", "end": 17352, "score": 0.9458017349243164, "start": 17342, "tag": "NAME", "value": "Arm Biting" }, { "context": "ic: (browser)->\n browser.fill(\"Name\", \"ArmBiter\")\n browser.querySelector(\"form :reset\"", "end": 18822, "score": 0.998931348323822, "start": 18814, "tag": "NAME", "value": "ArmBiter" }, { "context": "qual browser.querySelector(\"#field-name\").value, \"ArmBiter\"\n\n \"by clicking reset input\":\n Browse", "end": 19172, "score": 0.9963818192481995, "start": 19164, "tag": "NAME", "value": "ArmBiter" }, { "context": "ic: (browser)->\n browser.fill(\"Name\", \"ArmBiter\")\n browser.querySelector(\"form :reset\"", "end": 19336, "score": 0.9989597201347351, "start": 19328, "tag": "NAME", "value": "ArmBiter" }, { "context": "ic: (browser)->\n browser.fill(\"Name\", \"ArmBiter\").fill(\"likes\", \"Arm Biting\").check(\"You bet\").\n ", "end": 19770, "score": 0.9993447661399841, "start": 19762, "tag": "NAME", "value": "ArmBiter" }, { "context": "\n assert.equal browser.text(\"#name\"), \"ArmBiter\"\n \"should send textarea values to server", "end": 20633, "score": 0.9801549911499023, "start": 20625, "tag": "NAME", "value": "ArmBiter" }, { "context": "ic: (browser)->\n browser.fill(\"Name\", \"ArmBiter\").fill(\"likes\", \"Arm Biting\").pressButton \"Hit Me", "end": 22219, "score": 0.9381325244903564, "start": 22211, "tag": "NAME", "value": "ArmBiter" }, { "context": "\n assert.equal browser.text(\"#name\"), \"ArmBiter\"\n assert.equal browser.text(\"#likes\"),", "end": 22755, "score": 0.998468816280365, "start": 22747, "tag": "NAME", "value": "ArmBiter" }, { "context": "ic: (browser)->\n browser.fill(\"Name\", \"ArmBiter\").fill(\"likes\", \"Arm Biting\").pressButton \"#image", "end": 23122, "score": 0.999745786190033, "start": 23114, "tag": "NAME", "value": "ArmBiter" }, { "context": " browser.fill(\"Name\", \"ArmBiter\").fill(\"likes\", \"Arm Biting\").pressButton \"#image_submit\", @callback\n ", "end": 23150, "score": 0.9971768856048584, "start": 23140, "tag": "NAME", "value": "Arm Biting" }, { "context": "\n assert.equal browser.text(\"#name\"), \"ArmBiter\"\n assert.equal browser.text(\"#likes\"),", "end": 23676, "score": 0.998293399810791, "start": 23668, "tag": "NAME", "value": "ArmBiter" }, { "context": "ic: (browser)->\n browser.fill(\"Name\", \"ArmBiter\").fill(\"likes\", \"Arm Biting\").pressButton \"Submit", "end": 24030, "score": 0.9997937083244324, "start": 24022, "tag": "NAME", "value": "ArmBiter" }, { "context": " browser.fill(\"Name\", \"ArmBiter\").fill(\"likes\", \"Arm Biting\").pressButton \"Submit\", @callback\n \"shou", "end": 24058, "score": 0.9908568859100342, "start": 24048, "tag": "NAME", "value": "Arm Biting" }, { "context": "\n assert.equal browser.text(\"#name\"), \"ArmBiter\"\n assert.equal browser.text(\"#likes\"),", "end": 24566, "score": 0.890247106552124, "start": 24558, "tag": "USERNAME", "value": "ArmBiter" }, { "context": " assert.equal browser.text(\"#likes\"), \"Arm Biting\"\n\n\n # File upload\n \"file upload\":\n to", "end": 24621, "score": 0.5295618176460266, "start": 24618, "tag": "NAME", "value": "Arm" } ]
nodejs/marketplace/submodules/zombie/spec/forms_spec.coffee
flarebyte/wonderful-bazar
1
{ Vows, assert, brains, Browser } = require("./helpers") File = require("fs") Crypto = require("crypto") Vows.describe("Forms").addBatch( "standard": topic: -> brains.get "/forms/form", (req, res)-> res.send """ <html> <body> <form action="/forms/submit" method="post"> <label>Name <input type="text" name="name" id="field-name"></label> <label for="field-email">Email</label> <input type="text" name="email" id="field-email"></label> <textarea name="likes" id="field-likes">Warm brains</textarea> <input type="password" name="password" id="field-password"> <input type="badtype" name="invalidtype" id="field-invalidtype" /> <input type="text" name="email2" id="field-email2" /> <input type="text" name="email3" id="field-email3" /> <label>Hungry</label> <label>You bet<input type="checkbox" name="hungry[]" value="you bet" id="field-hungry"></label> <label>Certainly<input type="checkbox" name="hungry[]" value="certainly" id="field-hungry-certainly"></label> <label for="field-brains">Brains?</label> <input type="checkbox" name="brains" value="yes" id="field-brains"> <input type="checkbox" name="green" id="field-green" value="Super green!" checked="checked"> <input type="checkbox" name="check" id="field-check" value="Huh?" checked="checked"> <input type="checkbox" name="uncheck" id="field-uncheck" value="Yeah!"> <label>Looks <select name="looks" id="field-looks"> <option value="blood" label="Bloody"></option> <option value="clean" label="Clean"></option> <option value="" label="Choose one"></option> </select> </label> <label>Scary <input name="scary" type="radio" value="yes" id="field-scary"></label> <label>Not scary <input name="scary" type="radio" value="no" id="field-notscary" checked="checked"></label> <select name="state" id="field-state"> <option>alive</option> <option>dead</option> <option>neither</option> </select> <span>First address</span> <label for='address1_street'>Street</label> <input type="text" name="addresses[][street]" value="" id="address1_street"> <label for='address1_city'>City</label> <input type="text" name="addresses[][city]" value="" id="address1_city"> <span>Second address</span> <label for='address2_street'>Street</label> <input type="text" name="addresses[][street]" value="" id="address2_street"> <label for='address2_city'>City</label> <input type="text" name="addresses[][city]" value="" id="address2_city"> <select name="kills" id="field-kills"> <option>Five</option> <option>Seventeen</option> <option id="option-killed-thousands">Thousands</option> </select> <select name="unselected_state" id="field-unselected-state"> <option>alive</option> <option>dead</option> </select> <select name="hobbies[]" id="field-hobbies" multiple="multiple"> <option>Eat Brains</option> <option id="hobbies-messy">Make Messy</option> <option>Sleep</option> </select> <input type="unknown" name="unknown" value="yes"> <input type="reset" value="Reset"> <input type="submit" name="button" value="Submit"> <input type="image" name="image" id="image_submit" value="Image Submit"> <button name="button" value="hit-me">Hit Me</button> </form> </body> </html> """ brains.post "/forms/submit", (req, res)-> res.send """ <html> <body> <div id="name">#{req.body.name}</div> <div id="likes">#{req.body.likes}</div> <div id="green">#{req.body.green}</div> <div id="brains">#{req.body.brains}</div> <div id="looks">#{req.body.looks}</div> <div id="hungry">#{JSON.stringify(req.body.hungry)}</div> <div id="state">#{req.body.state}</div> <div id="scary">#{req.body.scary}</div> <div id="state">#{req.body.state}</div> <div id="unselected_state">#{req.body.unselected_state}</div> <div id="hobbies">#{JSON.stringify(req.body.hobbies)}</div> <div id="addresses">#{JSON.stringify(req.body.addresses)}</div> <div id="unknown">#{req.body.unknown}</div> <div id="clicked">#{req.body.button}</div> <div id="image_clicked">#{req.body.image}</div> </body> </html> """ "fill field": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> for field in ["email", "likes", "name", "password", "invalidtype", "email2"] do (field)-> browser.querySelector("#field-#{field}").addEventListener "change", -> browser["#{field}Changed"] = true @callback null, browser "text input enclosed in label": topic: (browser)-> browser.fill "Name", "ArmBiter" "should set text field": (browser)-> assert.equal browser.querySelector("#field-name").value, "ArmBiter" "should fire change event": (browser)-> assert.ok browser.nameChanged "email input referenced from label": topic: (browser)-> browser.fill "Email", "armbiter@example.com" "should set email field": (browser)-> assert.equal browser.querySelector("#field-email").value, "armbiter@example.com" "should fire change event": (browser)-> assert.ok browser.emailChanged "textarea by field name": topic: (browser)-> browser.fill "likes", "Arm Biting" "should set textarea": (browser)-> assert.equal browser.querySelector("#field-likes").value, "Arm Biting" "should fire change event": (browser)-> assert.ok browser.likesChanged "password input by selector": topic: (browser)-> browser.fill ":password[name=password]", "b100d" "should set password": (browser)-> assert.equal browser.querySelector("#field-password").value, "b100d" "should fire change event": (browser)-> assert.ok browser.passwordChanged "input without a valid type": topic: (browser)-> browser.fill ":input[name=invalidtype]", "some value" "should set value": (browser)-> assert.equal browser.querySelector("#field-invalidtype").value, "some value" "should fire change event": (browser)-> assert.ok browser.invalidtypeChanged "email2 input by node": topic: (browser)-> browser.fill browser.querySelector("#field-email2"), "headchomper@example.com" "should set email2 field": (browser)-> assert.equal browser.querySelector("#field-email2").value, "headchomper@example.com" "should fire change event": (browser)-> assert.ok browser.email2Changed "should callback": topic: (browser)-> browser.fill browser.querySelector("#field-email3"), "headchomper@example.com", @callback "should fire the callback": (_, browser)-> assert.equal browser.querySelector("#field-email3").value, "headchomper@example.com" "check box": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> for field in ["hungry", "brains", "green"] do (field)-> browser.querySelector("#field-#{field}").addEventListener "click", -> browser["#{field}Clicked"] = true browser.querySelector("#field-#{field}").addEventListener "change", -> browser["#{field}Changed"] = true @callback null, browser "checkbox enclosed in label": topic: (browser)-> browser.check "You bet" browser.wait @callback "should check checkbox": (browser)-> assert.ok browser.querySelector("#field-hungry").checked "should fire change event": (browser)-> assert.ok browser.hungryChanged "should fire clicked event": (browser)-> assert.ok browser.hungryClicked "with callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.check "Brains?", @callback "should callback": (_, browser)-> assert.ok browser.querySelector("#field-brains").checked "checkbox referenced from label": topic: (browser)-> browser.check "Brains?" browser.wait @callback "should check checkbox": (browser)-> assert.ok browser.querySelector("#field-brains").checked "should fire change event": (browser)-> assert.ok browser.brainsChanged "uncheck with callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.check "Brains?" browser.uncheck "Brains?", @callback "should callback": (_, browser)-> assert.ok !browser.querySelector("#field-brains").checked "checkbox by name": topic: (browser)-> browser.check "green" browser["greenChanged"] = false browser.uncheck "green" browser.wait @callback "should uncheck checkbox": (browser)-> assert.ok !browser.querySelector("#field-green").checked "should fire change event": (browser)-> assert.ok browser.greenChanged "check callback": topic: (browser)-> browser.check "uncheck", @callback "should callback": (_, browser)-> assert.ok browser.querySelector("#field-uncheck").checked "uncheck callback": topic: (browser)-> browser.uncheck "check", @callback "should callback": (_, browser)-> assert.ok !browser.querySelector("#field-check").checked "radio buttons": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> for field in ["scary", "notscary"] do (field)-> browser.querySelector("#field-#{field}").addEventListener "click", -> browser["#{field}Clicked"] = true browser.querySelector("#field-#{field}").addEventListener "change", -> browser["#{field}Changed"] = true @callback null, browser "radio button enclosed in label": topic: (browser)-> browser.choose "Scary" "should check radio": (browser)-> assert.ok browser.querySelector("#field-scary").checked "should fire click event": (browser)-> assert.ok browser.scaryClicked "should fire change event": (browser)-> assert.ok browser.scaryChanged "with callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.choose "Scary", @callback "should callback": (_, browser)-> assert.ok browser.querySelector("#field-scary").checked "radio button by value": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.choose "no" "should check radio": (browser)-> assert.ok browser.querySelector("#field-notscary").checked "should uncheck other radio": (browser)-> assert.ok !browser.querySelector("#field-scary").checked "select option": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> for field in ["looks", "state", "kills"] do (field)-> browser.querySelector("#field-#{field}").addEventListener "change", -> browser["#{field}Changed"] = true @callback null, browser "enclosed in label using option label": topic: (browser)-> browser.select "Looks", "Bloody" "should set value": (browser)-> assert.equal browser.querySelector("#field-looks").value, "blood" "should select first option": (browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-looks").options) assert.deepEqual selected, [true, false, false] "should fire change event": (browser)-> assert.ok browser.looksChanged "select name using option value": topic: (browser)-> browser.select "state", "dead" "should set value": (browser)-> assert.equal browser.querySelector("#field-state").value, "dead" "should select second option": (browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-state").options) assert.deepEqual selected, [false, true, false] "should fire change event": (browser)-> assert.ok browser.stateChanged "select option value directly": topic: (browser)-> browser.selectOption browser.querySelector("#option-killed-thousands") "should set value": (browser)-> assert.equal browser.querySelector("#field-kills").value, "Thousands" "should select second option": (browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-kills").options) assert.deepEqual selected, [false, false, true] "should fire change event": (browser)-> assert.ok browser.killsChanged "select callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.select "unselected_state", "dead", @callback "should callback": (_, browser)-> assert.equal browser.querySelector("#field-unselected-state").value, "dead" "select option callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.selectOption browser.querySelector("#option-killed-thousands"), @callback "should callback": (_, browser)-> assert.equal browser.querySelector("#field-kills").value, "Thousands" "multiple select option": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.querySelector("#field-hobbies").addEventListener "change", -> browser["hobbiesChanged"] = true @callback null, browser "select name using option value": topic: (browser)-> browser.select "#field-hobbies", "Eat Brains" browser.select "#field-hobbies", "Sleep" "should select first and second options": (browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options) assert.deepEqual selected, [true, false, true] "should fire change event": (browser)-> assert.ok browser.hobbiesChanged "should not fire change event if nothing changed": (browser)-> browser["hobbiesChanged"] = false browser.select "#field-hobbies", "Eat Brains" assert.ok !browser.hobbiesChanged "unselect name using option value": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.select "#field-hobbies", "Eat Brains" browser.select "#field-hobbies", "Sleep" browser.unselect "#field-hobbies", "Sleep" "should unselect items": (browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options) assert.deepEqual selected, [true, false, false] "with callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.unselect "#field-hobbies", "Eat Brains" browser.unselect "#field-hobbies", "Sleep" browser.select "#field-hobbies", "Eat Brains", @callback "should unselect callback": (_, browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options) assert.deepEqual selected, [true, false, false] "reset form": "by calling reset": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "ArmBiter").fill("likes", "Arm Biting"). check("You bet").choose("Scary").select("state", "dead") browser.querySelector("form").reset() @callback null, browser "should reset input field to original value": (browser)-> assert.equal browser.querySelector("#field-name").value, "" "should reset textarea to original value": (browser)-> assert.equal browser.querySelector("#field-likes").value, "Warm brains" "should reset checkbox to original value": (browser)-> assert.ok !browser.querySelector("#field-hungry").value "should reset radio to original value": (browser)-> assert.ok !browser.querySelector("#field-scary").checked assert.ok browser.querySelector("#field-notscary").checked "should reset select to original option": (browser)-> assert.equal browser.querySelector("#field-state").value, "alive" "with event handler": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.querySelector("form :reset").addEventListener "click", (event)=> @callback null, event browser.querySelector("form :reset").click() "should fire click event": (event)-> assert.equal event.type, "click" "with preventDefault": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "ArmBiter") browser.querySelector("form :reset").addEventListener "click", (event)-> event.preventDefault() browser.querySelector("form :reset").click() @callback null, browser "should not reset input field": (browser)-> assert.equal browser.querySelector("#field-name").value, "ArmBiter" "by clicking reset input": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "ArmBiter") browser.querySelector("form :reset").click() @callback null, browser "should reset input field to original value": (browser)-> assert.equal browser.querySelector("#field-name").value, "" # Submitting form "submit form": "by calling submit": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "ArmBiter").fill("likes", "Arm Biting").check("You bet"). check("Certainly").choose("Scary").select("state", "dead").select("looks", "Choose one"). select("#field-hobbies", "Eat Brains").select("#field-hobbies", "Sleep").check("Brains?"). fill('#address1_city', 'Paris').fill('#address1_street', 'CDG'). fill('#address2_city', 'Mikolaiv').fill('#address2_street', 'PGS') browser.querySelector("form").submit() browser.wait @callback "should open new page": (browser)-> assert.equal browser.location, "http://localhost:3003/forms/submit" "should add location to history": (browser)-> assert.lengthOf browser.window.history, 2 "should send text input values to server": (browser)-> assert.equal browser.text("#name"), "ArmBiter" "should send textarea values to server": (browser)-> assert.equal browser.text("#likes"), "Arm Biting" "should send radio button to server": (browser)-> assert.equal browser.text("#scary"), "yes" "should send unknown types to server": (browser)-> assert.equal browser.text("#unknown"), "yes" "should send checkbox with default value to server": (browser)-> assert.equal browser.text("#brains"), "yes" "should send checkbox with default value to server": (browser)-> assert.equal browser.text("#green"), "Super green!" "should send multiple checkbox values to server": (browser)-> assert.equal browser.text("#hungry"), '["you bet","certainly"]' "should send selected option to server": (browser)-> assert.equal browser.text("#state"), "dead" "should send first selected option if none was chosen to server": (browser)-> assert.equal browser.text("#unselected_state"), "alive" assert.equal browser.text("#looks"), "" "should send multiple selected options to server": (browser)-> assert.equal browser.text("#hobbies"), '["Eat Brains","Sleep"]' "should send nested attributes in the order they are declared": (browser) -> assert.equal browser.text("#addresses"), '["CDG","Paris","PGS","Mikolaiv"]' "by clicking button": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "ArmBiter").fill("likes", "Arm Biting").pressButton "Hit Me", @callback "should open new page": (browser)-> assert.equal browser.location, "http://localhost:3003/forms/submit" "should add location to history": (browser)-> assert.lengthOf browser.window.history, 2 "should send button value to server": (browser)-> assert.equal browser.text("#clicked"), "hit-me" "should send input values to server": (browser)-> assert.equal browser.text("#name"), "ArmBiter" assert.equal browser.text("#likes"), "Arm Biting" "should not send other button values to server": (browser)-> assert.equal browser.text("#image_clicked"), "undefined" "by clicking image button": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "ArmBiter").fill("likes", "Arm Biting").pressButton "#image_submit", @callback "should open new page": (browser)-> assert.equal browser.location, "http://localhost:3003/forms/submit" "should add location to history": (browser)-> assert.lengthOf browser.window.history, 2 "should send image value to server": (browser)-> assert.equal browser.text("#image_clicked"), "Image Submit" "should send input values to server": (browser)-> assert.equal browser.text("#name"), "ArmBiter" assert.equal browser.text("#likes"), "Arm Biting" "should not send other button values to server": (browser)-> assert.equal browser.text("#clicked"), "undefined" "by clicking input": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "ArmBiter").fill("likes", "Arm Biting").pressButton "Submit", @callback "should open new page": (browser)-> assert.equal browser.location, "http://localhost:3003/forms/submit" "should add location to history": (browser)-> assert.lengthOf browser.window.history, 2 "should send submit value to server": (browser)-> assert.equal browser.text("#clicked"), "Submit" "should send input values to server": (browser)-> assert.equal browser.text("#name"), "ArmBiter" assert.equal browser.text("#likes"), "Arm Biting" # File upload "file upload": topic: -> brains.get "/forms/upload", (req, res)-> res.send """ <html> <body> <form method="post" enctype="multipart/form-data"> <input name="text" type="file"> <input name="image" type="file"> <button>Upload</button> </form> <form> <input name="get_file" type="file"> <input type="submit" value="Get Upload"> </form> </body> </html> """ brains.post "/forms/upload", (req, res)-> if req.files [text, image] = [req.files.text, req.files.image] data = File.readFileSync((text || image).path) if image digest = Crypto.createHash("md5").update(data).digest("hex") res.send """ <html> <head><title>#{(text || image).filename}</title></head> <body>#{digest || data}</body> </html> """ else res.send """ <html> <body>nothing</body> </html> """ "text": Browser.wants "http://localhost:3003/forms/upload" topic: (browser)-> filename = __dirname + "/data/random.txt" browser.attach("text", filename).pressButton "Upload", @callback "should upload file": (browser)-> assert.equal browser.text("body").trim(), "Random text" "should upload include name": (browser)-> assert.equal browser.text("title"), "random.txt" "binary": Browser.wants "http://localhost:3003/forms/upload" topic: (browser)-> @filename = __dirname + "/data/zombie.jpg" browser.attach("image", @filename).pressButton "Upload", @callback "should upload include name": (browser)-> assert.equal browser.text("title"), "zombie.jpg" "should upload file": (browser)-> digest = Crypto.createHash("md5").update(File.readFileSync(@filename)).digest("hex") assert.equal browser.text("body").trim(), digest "empty": Browser.wants "http://localhost:3003/forms/upload" topic: (browser)-> browser.attach "text", "" browser.pressButton "Upload", @callback "should not upload any file": (browser)-> assert.equal browser.text("body").trim(), "nothing" "not set": Browser.wants "http://localhost:3003/forms/upload" topic: (browser)-> browser.pressButton "Upload", @callback "should not send inputs without names": (browser)-> assert.equal browser.text("body").trim(), "nothing" "get": Browser.wants "http://localhost:3003/forms/upload" topic: (browser)-> filename = __dirname + "/data/random.txt" browser.attach("get_file", filename).pressButton "Get Upload", @callback "should send just the file basename": (browser)-> assert.equal browser.location.search, "?get_file=random.txt" "content length": topic: -> brains.get "/forms/urlencoded", (req, res)-> res.send """ <html> <body> <form method="post"> <input name="text" type="text"> <input type="submit" value="submit"> </form> </body> </html> """ brains.post "/forms/urlencoded", (req, res)-> text = req.body.text res.send """ <html> <head><title>bite back</title></head> <body>#{text}</body> </html> """ "post form urlencoded having content": Browser.wants "http://localhost:3003/forms/urlencoded" topic: (browser)-> browser.fill("text", "bite").pressButton "submit", @callback "should send content-length header": (browser) -> assert.include browser.lastRequest.headers, "content-length" "should match expected content-length": (browser) -> assert.equal browser.lastRequest.headers["content-length"], "text=bite".length "should have body with content of input field": (browser) -> assert.equal browser.text("body"), "bite" "post form urlencoded being empty": Browser.wants "http://localhost:3003/forms/urlencoded" topic: (browser)-> browser.pressButton "submit", @callback "should send content-length header": (browser) -> assert.include browser.lastRequest.headers, "content-length" "should have size of 0": (browser) -> assert.equal browser.lastRequest.headers["content-length"], 0 ).export(module)
93643
{ Vows, assert, brains, Browser } = require("./helpers") File = require("fs") Crypto = require("crypto") Vows.describe("Forms").addBatch( "standard": topic: -> brains.get "/forms/form", (req, res)-> res.send """ <html> <body> <form action="/forms/submit" method="post"> <label>Name <input type="text" name="name" id="field-name"></label> <label for="field-email">Email</label> <input type="text" name="email" id="field-email"></label> <textarea name="likes" id="field-likes">Warm brains</textarea> <input type="password" name="password" id="field-password"> <input type="badtype" name="invalidtype" id="field-invalidtype" /> <input type="text" name="email2" id="field-email2" /> <input type="text" name="email3" id="field-email3" /> <label>Hungry</label> <label>You bet<input type="checkbox" name="hungry[]" value="you bet" id="field-hungry"></label> <label>Certainly<input type="checkbox" name="hungry[]" value="certainly" id="field-hungry-certainly"></label> <label for="field-brains">Brains?</label> <input type="checkbox" name="brains" value="yes" id="field-brains"> <input type="checkbox" name="green" id="field-green" value="Super green!" checked="checked"> <input type="checkbox" name="check" id="field-check" value="Huh?" checked="checked"> <input type="checkbox" name="uncheck" id="field-uncheck" value="Yeah!"> <label>Looks <select name="looks" id="field-looks"> <option value="blood" label="Bloody"></option> <option value="clean" label="Clean"></option> <option value="" label="Choose one"></option> </select> </label> <label>Scary <input name="scary" type="radio" value="yes" id="field-scary"></label> <label>Not scary <input name="scary" type="radio" value="no" id="field-notscary" checked="checked"></label> <select name="state" id="field-state"> <option>alive</option> <option>dead</option> <option>neither</option> </select> <span>First address</span> <label for='address1_street'>Street</label> <input type="text" name="addresses[][street]" value="" id="address1_street"> <label for='address1_city'>City</label> <input type="text" name="addresses[][city]" value="" id="address1_city"> <span>Second address</span> <label for='address2_street'>Street</label> <input type="text" name="addresses[][street]" value="" id="address2_street"> <label for='address2_city'>City</label> <input type="text" name="addresses[][city]" value="" id="address2_city"> <select name="kills" id="field-kills"> <option>Five</option> <option>Seventeen</option> <option id="option-killed-thousands">Thousands</option> </select> <select name="unselected_state" id="field-unselected-state"> <option>alive</option> <option>dead</option> </select> <select name="hobbies[]" id="field-hobbies" multiple="multiple"> <option>Eat Brains</option> <option id="hobbies-messy">Make Messy</option> <option>Sleep</option> </select> <input type="unknown" name="unknown" value="yes"> <input type="reset" value="Reset"> <input type="submit" name="button" value="Submit"> <input type="image" name="image" id="image_submit" value="Image Submit"> <button name="button" value="hit-me">Hit Me</button> </form> </body> </html> """ brains.post "/forms/submit", (req, res)-> res.send """ <html> <body> <div id="name">#{req.body.name}</div> <div id="likes">#{req.body.likes}</div> <div id="green">#{req.body.green}</div> <div id="brains">#{req.body.brains}</div> <div id="looks">#{req.body.looks}</div> <div id="hungry">#{JSON.stringify(req.body.hungry)}</div> <div id="state">#{req.body.state}</div> <div id="scary">#{req.body.scary}</div> <div id="state">#{req.body.state}</div> <div id="unselected_state">#{req.body.unselected_state}</div> <div id="hobbies">#{JSON.stringify(req.body.hobbies)}</div> <div id="addresses">#{JSON.stringify(req.body.addresses)}</div> <div id="unknown">#{req.body.unknown}</div> <div id="clicked">#{req.body.button}</div> <div id="image_clicked">#{req.body.image}</div> </body> </html> """ "fill field": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> for field in ["email", "likes", "name", "password", "invalidtype", "email2"] do (field)-> browser.querySelector("#field-#{field}").addEventListener "change", -> browser["#{field}Changed"] = true @callback null, browser "text input enclosed in label": topic: (browser)-> browser.fill "Name", "<NAME>" "should set text field": (browser)-> assert.equal browser.querySelector("#field-name").value, "<NAME>" "should fire change event": (browser)-> assert.ok browser.nameChanged "email input referenced from label": topic: (browser)-> browser.fill "Email", "<EMAIL>" "should set email field": (browser)-> assert.equal browser.querySelector("#field-email").value, "<EMAIL>" "should fire change event": (browser)-> assert.ok browser.emailChanged "textarea by field name": topic: (browser)-> browser.fill "likes", "<NAME>" "should set textarea": (browser)-> assert.equal browser.querySelector("#field-likes").value, "<NAME>" "should fire change event": (browser)-> assert.ok browser.likesChanged "password input by selector": topic: (browser)-> browser.fill ":password[name=password]", "<PASSWORD>" "should set password": (browser)-> assert.equal browser.querySelector("#field-password").value, "<PASSWORD>" "should fire change event": (browser)-> assert.ok browser.passwordChanged "input without a valid type": topic: (browser)-> browser.fill ":input[name=invalidtype]", "some value" "should set value": (browser)-> assert.equal browser.querySelector("#field-invalidtype").value, "some value" "should fire change event": (browser)-> assert.ok browser.invalidtypeChanged "email2 input by node": topic: (browser)-> browser.fill browser.querySelector("#field-email2"), "<EMAIL>" "should set email2 field": (browser)-> assert.equal browser.querySelector("#field-email2").value, "<EMAIL>" "should fire change event": (browser)-> assert.ok browser.email2Changed "should callback": topic: (browser)-> browser.fill browser.querySelector("#field-email3"), "<EMAIL>", @callback "should fire the callback": (_, browser)-> assert.equal browser.querySelector("#field-email3").value, "<EMAIL>" "check box": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> for field in ["hungry", "brains", "green"] do (field)-> browser.querySelector("#field-#{field}").addEventListener "click", -> browser["#{field}Clicked"] = true browser.querySelector("#field-#{field}").addEventListener "change", -> browser["#{field}Changed"] = true @callback null, browser "checkbox enclosed in label": topic: (browser)-> browser.check "You bet" browser.wait @callback "should check checkbox": (browser)-> assert.ok browser.querySelector("#field-hungry").checked "should fire change event": (browser)-> assert.ok browser.hungryChanged "should fire clicked event": (browser)-> assert.ok browser.hungryClicked "with callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.check "Brains?", @callback "should callback": (_, browser)-> assert.ok browser.querySelector("#field-brains").checked "checkbox referenced from label": topic: (browser)-> browser.check "Brains?" browser.wait @callback "should check checkbox": (browser)-> assert.ok browser.querySelector("#field-brains").checked "should fire change event": (browser)-> assert.ok browser.brainsChanged "uncheck with callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.check "Brains?" browser.uncheck "Brains?", @callback "should callback": (_, browser)-> assert.ok !browser.querySelector("#field-brains").checked "checkbox by name": topic: (browser)-> browser.check "green" browser["greenChanged"] = false browser.uncheck "green" browser.wait @callback "should uncheck checkbox": (browser)-> assert.ok !browser.querySelector("#field-green").checked "should fire change event": (browser)-> assert.ok browser.greenChanged "check callback": topic: (browser)-> browser.check "uncheck", @callback "should callback": (_, browser)-> assert.ok browser.querySelector("#field-uncheck").checked "uncheck callback": topic: (browser)-> browser.uncheck "check", @callback "should callback": (_, browser)-> assert.ok !browser.querySelector("#field-check").checked "radio buttons": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> for field in ["scary", "notscary"] do (field)-> browser.querySelector("#field-#{field}").addEventListener "click", -> browser["#{field}Clicked"] = true browser.querySelector("#field-#{field}").addEventListener "change", -> browser["#{field}Changed"] = true @callback null, browser "radio button enclosed in label": topic: (browser)-> browser.choose "Scary" "should check radio": (browser)-> assert.ok browser.querySelector("#field-scary").checked "should fire click event": (browser)-> assert.ok browser.scaryClicked "should fire change event": (browser)-> assert.ok browser.scaryChanged "with callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.choose "Scary", @callback "should callback": (_, browser)-> assert.ok browser.querySelector("#field-scary").checked "radio button by value": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.choose "no" "should check radio": (browser)-> assert.ok browser.querySelector("#field-notscary").checked "should uncheck other radio": (browser)-> assert.ok !browser.querySelector("#field-scary").checked "select option": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> for field in ["looks", "state", "kills"] do (field)-> browser.querySelector("#field-#{field}").addEventListener "change", -> browser["#{field}Changed"] = true @callback null, browser "enclosed in label using option label": topic: (browser)-> browser.select "Looks", "Bloody" "should set value": (browser)-> assert.equal browser.querySelector("#field-looks").value, "blood" "should select first option": (browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-looks").options) assert.deepEqual selected, [true, false, false] "should fire change event": (browser)-> assert.ok browser.looksChanged "select name using option value": topic: (browser)-> browser.select "state", "dead" "should set value": (browser)-> assert.equal browser.querySelector("#field-state").value, "dead" "should select second option": (browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-state").options) assert.deepEqual selected, [false, true, false] "should fire change event": (browser)-> assert.ok browser.stateChanged "select option value directly": topic: (browser)-> browser.selectOption browser.querySelector("#option-killed-thousands") "should set value": (browser)-> assert.equal browser.querySelector("#field-kills").value, "Thousands" "should select second option": (browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-kills").options) assert.deepEqual selected, [false, false, true] "should fire change event": (browser)-> assert.ok browser.killsChanged "select callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.select "unselected_state", "dead", @callback "should callback": (_, browser)-> assert.equal browser.querySelector("#field-unselected-state").value, "dead" "select option callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.selectOption browser.querySelector("#option-killed-thousands"), @callback "should callback": (_, browser)-> assert.equal browser.querySelector("#field-kills").value, "Thousands" "multiple select option": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.querySelector("#field-hobbies").addEventListener "change", -> browser["hobbiesChanged"] = true @callback null, browser "select name using option value": topic: (browser)-> browser.select "#field-hobbies", "Eat Brains" browser.select "#field-hobbies", "Sleep" "should select first and second options": (browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options) assert.deepEqual selected, [true, false, true] "should fire change event": (browser)-> assert.ok browser.hobbiesChanged "should not fire change event if nothing changed": (browser)-> browser["hobbiesChanged"] = false browser.select "#field-hobbies", "Eat Brains" assert.ok !browser.hobbiesChanged "unselect name using option value": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.select "#field-hobbies", "Eat Brains" browser.select "#field-hobbies", "Sleep" browser.unselect "#field-hobbies", "Sleep" "should unselect items": (browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options) assert.deepEqual selected, [true, false, false] "with callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.unselect "#field-hobbies", "Eat Brains" browser.unselect "#field-hobbies", "Sleep" browser.select "#field-hobbies", "Eat Brains", @callback "should unselect callback": (_, browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options) assert.deepEqual selected, [true, false, false] "reset form": "by calling reset": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "<NAME>").fill("likes", "<NAME>"). check("You bet").choose("Scary").select("state", "dead") browser.querySelector("form").reset() @callback null, browser "should reset input field to original value": (browser)-> assert.equal browser.querySelector("#field-name").value, "" "should reset textarea to original value": (browser)-> assert.equal browser.querySelector("#field-likes").value, "Warm brains" "should reset checkbox to original value": (browser)-> assert.ok !browser.querySelector("#field-hungry").value "should reset radio to original value": (browser)-> assert.ok !browser.querySelector("#field-scary").checked assert.ok browser.querySelector("#field-notscary").checked "should reset select to original option": (browser)-> assert.equal browser.querySelector("#field-state").value, "alive" "with event handler": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.querySelector("form :reset").addEventListener "click", (event)=> @callback null, event browser.querySelector("form :reset").click() "should fire click event": (event)-> assert.equal event.type, "click" "with preventDefault": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "<NAME>") browser.querySelector("form :reset").addEventListener "click", (event)-> event.preventDefault() browser.querySelector("form :reset").click() @callback null, browser "should not reset input field": (browser)-> assert.equal browser.querySelector("#field-name").value, "<NAME>" "by clicking reset input": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "<NAME>") browser.querySelector("form :reset").click() @callback null, browser "should reset input field to original value": (browser)-> assert.equal browser.querySelector("#field-name").value, "" # Submitting form "submit form": "by calling submit": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "<NAME>").fill("likes", "Arm Biting").check("You bet"). check("Certainly").choose("Scary").select("state", "dead").select("looks", "Choose one"). select("#field-hobbies", "Eat Brains").select("#field-hobbies", "Sleep").check("Brains?"). fill('#address1_city', 'Paris').fill('#address1_street', 'CDG'). fill('#address2_city', 'Mikolaiv').fill('#address2_street', 'PGS') browser.querySelector("form").submit() browser.wait @callback "should open new page": (browser)-> assert.equal browser.location, "http://localhost:3003/forms/submit" "should add location to history": (browser)-> assert.lengthOf browser.window.history, 2 "should send text input values to server": (browser)-> assert.equal browser.text("#name"), "<NAME>" "should send textarea values to server": (browser)-> assert.equal browser.text("#likes"), "Arm Biting" "should send radio button to server": (browser)-> assert.equal browser.text("#scary"), "yes" "should send unknown types to server": (browser)-> assert.equal browser.text("#unknown"), "yes" "should send checkbox with default value to server": (browser)-> assert.equal browser.text("#brains"), "yes" "should send checkbox with default value to server": (browser)-> assert.equal browser.text("#green"), "Super green!" "should send multiple checkbox values to server": (browser)-> assert.equal browser.text("#hungry"), '["you bet","certainly"]' "should send selected option to server": (browser)-> assert.equal browser.text("#state"), "dead" "should send first selected option if none was chosen to server": (browser)-> assert.equal browser.text("#unselected_state"), "alive" assert.equal browser.text("#looks"), "" "should send multiple selected options to server": (browser)-> assert.equal browser.text("#hobbies"), '["Eat Brains","Sleep"]' "should send nested attributes in the order they are declared": (browser) -> assert.equal browser.text("#addresses"), '["CDG","Paris","PGS","Mikolaiv"]' "by clicking button": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "<NAME>").fill("likes", "Arm Biting").pressButton "Hit Me", @callback "should open new page": (browser)-> assert.equal browser.location, "http://localhost:3003/forms/submit" "should add location to history": (browser)-> assert.lengthOf browser.window.history, 2 "should send button value to server": (browser)-> assert.equal browser.text("#clicked"), "hit-me" "should send input values to server": (browser)-> assert.equal browser.text("#name"), "<NAME>" assert.equal browser.text("#likes"), "Arm Biting" "should not send other button values to server": (browser)-> assert.equal browser.text("#image_clicked"), "undefined" "by clicking image button": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "<NAME>").fill("likes", "<NAME>").pressButton "#image_submit", @callback "should open new page": (browser)-> assert.equal browser.location, "http://localhost:3003/forms/submit" "should add location to history": (browser)-> assert.lengthOf browser.window.history, 2 "should send image value to server": (browser)-> assert.equal browser.text("#image_clicked"), "Image Submit" "should send input values to server": (browser)-> assert.equal browser.text("#name"), "<NAME>" assert.equal browser.text("#likes"), "Arm Biting" "should not send other button values to server": (browser)-> assert.equal browser.text("#clicked"), "undefined" "by clicking input": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "<NAME>").fill("likes", "<NAME>").pressButton "Submit", @callback "should open new page": (browser)-> assert.equal browser.location, "http://localhost:3003/forms/submit" "should add location to history": (browser)-> assert.lengthOf browser.window.history, 2 "should send submit value to server": (browser)-> assert.equal browser.text("#clicked"), "Submit" "should send input values to server": (browser)-> assert.equal browser.text("#name"), "ArmBiter" assert.equal browser.text("#likes"), "<NAME> Biting" # File upload "file upload": topic: -> brains.get "/forms/upload", (req, res)-> res.send """ <html> <body> <form method="post" enctype="multipart/form-data"> <input name="text" type="file"> <input name="image" type="file"> <button>Upload</button> </form> <form> <input name="get_file" type="file"> <input type="submit" value="Get Upload"> </form> </body> </html> """ brains.post "/forms/upload", (req, res)-> if req.files [text, image] = [req.files.text, req.files.image] data = File.readFileSync((text || image).path) if image digest = Crypto.createHash("md5").update(data).digest("hex") res.send """ <html> <head><title>#{(text || image).filename}</title></head> <body>#{digest || data}</body> </html> """ else res.send """ <html> <body>nothing</body> </html> """ "text": Browser.wants "http://localhost:3003/forms/upload" topic: (browser)-> filename = __dirname + "/data/random.txt" browser.attach("text", filename).pressButton "Upload", @callback "should upload file": (browser)-> assert.equal browser.text("body").trim(), "Random text" "should upload include name": (browser)-> assert.equal browser.text("title"), "random.txt" "binary": Browser.wants "http://localhost:3003/forms/upload" topic: (browser)-> @filename = __dirname + "/data/zombie.jpg" browser.attach("image", @filename).pressButton "Upload", @callback "should upload include name": (browser)-> assert.equal browser.text("title"), "zombie.jpg" "should upload file": (browser)-> digest = Crypto.createHash("md5").update(File.readFileSync(@filename)).digest("hex") assert.equal browser.text("body").trim(), digest "empty": Browser.wants "http://localhost:3003/forms/upload" topic: (browser)-> browser.attach "text", "" browser.pressButton "Upload", @callback "should not upload any file": (browser)-> assert.equal browser.text("body").trim(), "nothing" "not set": Browser.wants "http://localhost:3003/forms/upload" topic: (browser)-> browser.pressButton "Upload", @callback "should not send inputs without names": (browser)-> assert.equal browser.text("body").trim(), "nothing" "get": Browser.wants "http://localhost:3003/forms/upload" topic: (browser)-> filename = __dirname + "/data/random.txt" browser.attach("get_file", filename).pressButton "Get Upload", @callback "should send just the file basename": (browser)-> assert.equal browser.location.search, "?get_file=random.txt" "content length": topic: -> brains.get "/forms/urlencoded", (req, res)-> res.send """ <html> <body> <form method="post"> <input name="text" type="text"> <input type="submit" value="submit"> </form> </body> </html> """ brains.post "/forms/urlencoded", (req, res)-> text = req.body.text res.send """ <html> <head><title>bite back</title></head> <body>#{text}</body> </html> """ "post form urlencoded having content": Browser.wants "http://localhost:3003/forms/urlencoded" topic: (browser)-> browser.fill("text", "bite").pressButton "submit", @callback "should send content-length header": (browser) -> assert.include browser.lastRequest.headers, "content-length" "should match expected content-length": (browser) -> assert.equal browser.lastRequest.headers["content-length"], "text=bite".length "should have body with content of input field": (browser) -> assert.equal browser.text("body"), "bite" "post form urlencoded being empty": Browser.wants "http://localhost:3003/forms/urlencoded" topic: (browser)-> browser.pressButton "submit", @callback "should send content-length header": (browser) -> assert.include browser.lastRequest.headers, "content-length" "should have size of 0": (browser) -> assert.equal browser.lastRequest.headers["content-length"], 0 ).export(module)
true
{ Vows, assert, brains, Browser } = require("./helpers") File = require("fs") Crypto = require("crypto") Vows.describe("Forms").addBatch( "standard": topic: -> brains.get "/forms/form", (req, res)-> res.send """ <html> <body> <form action="/forms/submit" method="post"> <label>Name <input type="text" name="name" id="field-name"></label> <label for="field-email">Email</label> <input type="text" name="email" id="field-email"></label> <textarea name="likes" id="field-likes">Warm brains</textarea> <input type="password" name="password" id="field-password"> <input type="badtype" name="invalidtype" id="field-invalidtype" /> <input type="text" name="email2" id="field-email2" /> <input type="text" name="email3" id="field-email3" /> <label>Hungry</label> <label>You bet<input type="checkbox" name="hungry[]" value="you bet" id="field-hungry"></label> <label>Certainly<input type="checkbox" name="hungry[]" value="certainly" id="field-hungry-certainly"></label> <label for="field-brains">Brains?</label> <input type="checkbox" name="brains" value="yes" id="field-brains"> <input type="checkbox" name="green" id="field-green" value="Super green!" checked="checked"> <input type="checkbox" name="check" id="field-check" value="Huh?" checked="checked"> <input type="checkbox" name="uncheck" id="field-uncheck" value="Yeah!"> <label>Looks <select name="looks" id="field-looks"> <option value="blood" label="Bloody"></option> <option value="clean" label="Clean"></option> <option value="" label="Choose one"></option> </select> </label> <label>Scary <input name="scary" type="radio" value="yes" id="field-scary"></label> <label>Not scary <input name="scary" type="radio" value="no" id="field-notscary" checked="checked"></label> <select name="state" id="field-state"> <option>alive</option> <option>dead</option> <option>neither</option> </select> <span>First address</span> <label for='address1_street'>Street</label> <input type="text" name="addresses[][street]" value="" id="address1_street"> <label for='address1_city'>City</label> <input type="text" name="addresses[][city]" value="" id="address1_city"> <span>Second address</span> <label for='address2_street'>Street</label> <input type="text" name="addresses[][street]" value="" id="address2_street"> <label for='address2_city'>City</label> <input type="text" name="addresses[][city]" value="" id="address2_city"> <select name="kills" id="field-kills"> <option>Five</option> <option>Seventeen</option> <option id="option-killed-thousands">Thousands</option> </select> <select name="unselected_state" id="field-unselected-state"> <option>alive</option> <option>dead</option> </select> <select name="hobbies[]" id="field-hobbies" multiple="multiple"> <option>Eat Brains</option> <option id="hobbies-messy">Make Messy</option> <option>Sleep</option> </select> <input type="unknown" name="unknown" value="yes"> <input type="reset" value="Reset"> <input type="submit" name="button" value="Submit"> <input type="image" name="image" id="image_submit" value="Image Submit"> <button name="button" value="hit-me">Hit Me</button> </form> </body> </html> """ brains.post "/forms/submit", (req, res)-> res.send """ <html> <body> <div id="name">#{req.body.name}</div> <div id="likes">#{req.body.likes}</div> <div id="green">#{req.body.green}</div> <div id="brains">#{req.body.brains}</div> <div id="looks">#{req.body.looks}</div> <div id="hungry">#{JSON.stringify(req.body.hungry)}</div> <div id="state">#{req.body.state}</div> <div id="scary">#{req.body.scary}</div> <div id="state">#{req.body.state}</div> <div id="unselected_state">#{req.body.unselected_state}</div> <div id="hobbies">#{JSON.stringify(req.body.hobbies)}</div> <div id="addresses">#{JSON.stringify(req.body.addresses)}</div> <div id="unknown">#{req.body.unknown}</div> <div id="clicked">#{req.body.button}</div> <div id="image_clicked">#{req.body.image}</div> </body> </html> """ "fill field": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> for field in ["email", "likes", "name", "password", "invalidtype", "email2"] do (field)-> browser.querySelector("#field-#{field}").addEventListener "change", -> browser["#{field}Changed"] = true @callback null, browser "text input enclosed in label": topic: (browser)-> browser.fill "Name", "PI:NAME:<NAME>END_PI" "should set text field": (browser)-> assert.equal browser.querySelector("#field-name").value, "PI:NAME:<NAME>END_PI" "should fire change event": (browser)-> assert.ok browser.nameChanged "email input referenced from label": topic: (browser)-> browser.fill "Email", "PI:EMAIL:<EMAIL>END_PI" "should set email field": (browser)-> assert.equal browser.querySelector("#field-email").value, "PI:EMAIL:<EMAIL>END_PI" "should fire change event": (browser)-> assert.ok browser.emailChanged "textarea by field name": topic: (browser)-> browser.fill "likes", "PI:NAME:<NAME>END_PI" "should set textarea": (browser)-> assert.equal browser.querySelector("#field-likes").value, "PI:NAME:<NAME>END_PI" "should fire change event": (browser)-> assert.ok browser.likesChanged "password input by selector": topic: (browser)-> browser.fill ":password[name=password]", "PI:PASSWORD:<PASSWORD>END_PI" "should set password": (browser)-> assert.equal browser.querySelector("#field-password").value, "PI:PASSWORD:<PASSWORD>END_PI" "should fire change event": (browser)-> assert.ok browser.passwordChanged "input without a valid type": topic: (browser)-> browser.fill ":input[name=invalidtype]", "some value" "should set value": (browser)-> assert.equal browser.querySelector("#field-invalidtype").value, "some value" "should fire change event": (browser)-> assert.ok browser.invalidtypeChanged "email2 input by node": topic: (browser)-> browser.fill browser.querySelector("#field-email2"), "PI:EMAIL:<EMAIL>END_PI" "should set email2 field": (browser)-> assert.equal browser.querySelector("#field-email2").value, "PI:EMAIL:<EMAIL>END_PI" "should fire change event": (browser)-> assert.ok browser.email2Changed "should callback": topic: (browser)-> browser.fill browser.querySelector("#field-email3"), "PI:EMAIL:<EMAIL>END_PI", @callback "should fire the callback": (_, browser)-> assert.equal browser.querySelector("#field-email3").value, "PI:EMAIL:<EMAIL>END_PI" "check box": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> for field in ["hungry", "brains", "green"] do (field)-> browser.querySelector("#field-#{field}").addEventListener "click", -> browser["#{field}Clicked"] = true browser.querySelector("#field-#{field}").addEventListener "change", -> browser["#{field}Changed"] = true @callback null, browser "checkbox enclosed in label": topic: (browser)-> browser.check "You bet" browser.wait @callback "should check checkbox": (browser)-> assert.ok browser.querySelector("#field-hungry").checked "should fire change event": (browser)-> assert.ok browser.hungryChanged "should fire clicked event": (browser)-> assert.ok browser.hungryClicked "with callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.check "Brains?", @callback "should callback": (_, browser)-> assert.ok browser.querySelector("#field-brains").checked "checkbox referenced from label": topic: (browser)-> browser.check "Brains?" browser.wait @callback "should check checkbox": (browser)-> assert.ok browser.querySelector("#field-brains").checked "should fire change event": (browser)-> assert.ok browser.brainsChanged "uncheck with callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.check "Brains?" browser.uncheck "Brains?", @callback "should callback": (_, browser)-> assert.ok !browser.querySelector("#field-brains").checked "checkbox by name": topic: (browser)-> browser.check "green" browser["greenChanged"] = false browser.uncheck "green" browser.wait @callback "should uncheck checkbox": (browser)-> assert.ok !browser.querySelector("#field-green").checked "should fire change event": (browser)-> assert.ok browser.greenChanged "check callback": topic: (browser)-> browser.check "uncheck", @callback "should callback": (_, browser)-> assert.ok browser.querySelector("#field-uncheck").checked "uncheck callback": topic: (browser)-> browser.uncheck "check", @callback "should callback": (_, browser)-> assert.ok !browser.querySelector("#field-check").checked "radio buttons": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> for field in ["scary", "notscary"] do (field)-> browser.querySelector("#field-#{field}").addEventListener "click", -> browser["#{field}Clicked"] = true browser.querySelector("#field-#{field}").addEventListener "change", -> browser["#{field}Changed"] = true @callback null, browser "radio button enclosed in label": topic: (browser)-> browser.choose "Scary" "should check radio": (browser)-> assert.ok browser.querySelector("#field-scary").checked "should fire click event": (browser)-> assert.ok browser.scaryClicked "should fire change event": (browser)-> assert.ok browser.scaryChanged "with callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.choose "Scary", @callback "should callback": (_, browser)-> assert.ok browser.querySelector("#field-scary").checked "radio button by value": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.choose "no" "should check radio": (browser)-> assert.ok browser.querySelector("#field-notscary").checked "should uncheck other radio": (browser)-> assert.ok !browser.querySelector("#field-scary").checked "select option": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> for field in ["looks", "state", "kills"] do (field)-> browser.querySelector("#field-#{field}").addEventListener "change", -> browser["#{field}Changed"] = true @callback null, browser "enclosed in label using option label": topic: (browser)-> browser.select "Looks", "Bloody" "should set value": (browser)-> assert.equal browser.querySelector("#field-looks").value, "blood" "should select first option": (browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-looks").options) assert.deepEqual selected, [true, false, false] "should fire change event": (browser)-> assert.ok browser.looksChanged "select name using option value": topic: (browser)-> browser.select "state", "dead" "should set value": (browser)-> assert.equal browser.querySelector("#field-state").value, "dead" "should select second option": (browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-state").options) assert.deepEqual selected, [false, true, false] "should fire change event": (browser)-> assert.ok browser.stateChanged "select option value directly": topic: (browser)-> browser.selectOption browser.querySelector("#option-killed-thousands") "should set value": (browser)-> assert.equal browser.querySelector("#field-kills").value, "Thousands" "should select second option": (browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-kills").options) assert.deepEqual selected, [false, false, true] "should fire change event": (browser)-> assert.ok browser.killsChanged "select callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.select "unselected_state", "dead", @callback "should callback": (_, browser)-> assert.equal browser.querySelector("#field-unselected-state").value, "dead" "select option callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.selectOption browser.querySelector("#option-killed-thousands"), @callback "should callback": (_, browser)-> assert.equal browser.querySelector("#field-kills").value, "Thousands" "multiple select option": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.querySelector("#field-hobbies").addEventListener "change", -> browser["hobbiesChanged"] = true @callback null, browser "select name using option value": topic: (browser)-> browser.select "#field-hobbies", "Eat Brains" browser.select "#field-hobbies", "Sleep" "should select first and second options": (browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options) assert.deepEqual selected, [true, false, true] "should fire change event": (browser)-> assert.ok browser.hobbiesChanged "should not fire change event if nothing changed": (browser)-> browser["hobbiesChanged"] = false browser.select "#field-hobbies", "Eat Brains" assert.ok !browser.hobbiesChanged "unselect name using option value": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.select "#field-hobbies", "Eat Brains" browser.select "#field-hobbies", "Sleep" browser.unselect "#field-hobbies", "Sleep" "should unselect items": (browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options) assert.deepEqual selected, [true, false, false] "with callback": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.unselect "#field-hobbies", "Eat Brains" browser.unselect "#field-hobbies", "Sleep" browser.select "#field-hobbies", "Eat Brains", @callback "should unselect callback": (_, browser)-> selected = (!!option.getAttribute("selected") for option in browser.querySelector("#field-hobbies").options) assert.deepEqual selected, [true, false, false] "reset form": "by calling reset": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "PI:NAME:<NAME>END_PI").fill("likes", "PI:NAME:<NAME>END_PI"). check("You bet").choose("Scary").select("state", "dead") browser.querySelector("form").reset() @callback null, browser "should reset input field to original value": (browser)-> assert.equal browser.querySelector("#field-name").value, "" "should reset textarea to original value": (browser)-> assert.equal browser.querySelector("#field-likes").value, "Warm brains" "should reset checkbox to original value": (browser)-> assert.ok !browser.querySelector("#field-hungry").value "should reset radio to original value": (browser)-> assert.ok !browser.querySelector("#field-scary").checked assert.ok browser.querySelector("#field-notscary").checked "should reset select to original option": (browser)-> assert.equal browser.querySelector("#field-state").value, "alive" "with event handler": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.querySelector("form :reset").addEventListener "click", (event)=> @callback null, event browser.querySelector("form :reset").click() "should fire click event": (event)-> assert.equal event.type, "click" "with preventDefault": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "PI:NAME:<NAME>END_PI") browser.querySelector("form :reset").addEventListener "click", (event)-> event.preventDefault() browser.querySelector("form :reset").click() @callback null, browser "should not reset input field": (browser)-> assert.equal browser.querySelector("#field-name").value, "PI:NAME:<NAME>END_PI" "by clicking reset input": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "PI:NAME:<NAME>END_PI") browser.querySelector("form :reset").click() @callback null, browser "should reset input field to original value": (browser)-> assert.equal browser.querySelector("#field-name").value, "" # Submitting form "submit form": "by calling submit": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "PI:NAME:<NAME>END_PI").fill("likes", "Arm Biting").check("You bet"). check("Certainly").choose("Scary").select("state", "dead").select("looks", "Choose one"). select("#field-hobbies", "Eat Brains").select("#field-hobbies", "Sleep").check("Brains?"). fill('#address1_city', 'Paris').fill('#address1_street', 'CDG'). fill('#address2_city', 'Mikolaiv').fill('#address2_street', 'PGS') browser.querySelector("form").submit() browser.wait @callback "should open new page": (browser)-> assert.equal browser.location, "http://localhost:3003/forms/submit" "should add location to history": (browser)-> assert.lengthOf browser.window.history, 2 "should send text input values to server": (browser)-> assert.equal browser.text("#name"), "PI:NAME:<NAME>END_PI" "should send textarea values to server": (browser)-> assert.equal browser.text("#likes"), "Arm Biting" "should send radio button to server": (browser)-> assert.equal browser.text("#scary"), "yes" "should send unknown types to server": (browser)-> assert.equal browser.text("#unknown"), "yes" "should send checkbox with default value to server": (browser)-> assert.equal browser.text("#brains"), "yes" "should send checkbox with default value to server": (browser)-> assert.equal browser.text("#green"), "Super green!" "should send multiple checkbox values to server": (browser)-> assert.equal browser.text("#hungry"), '["you bet","certainly"]' "should send selected option to server": (browser)-> assert.equal browser.text("#state"), "dead" "should send first selected option if none was chosen to server": (browser)-> assert.equal browser.text("#unselected_state"), "alive" assert.equal browser.text("#looks"), "" "should send multiple selected options to server": (browser)-> assert.equal browser.text("#hobbies"), '["Eat Brains","Sleep"]' "should send nested attributes in the order they are declared": (browser) -> assert.equal browser.text("#addresses"), '["CDG","Paris","PGS","Mikolaiv"]' "by clicking button": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "PI:NAME:<NAME>END_PI").fill("likes", "Arm Biting").pressButton "Hit Me", @callback "should open new page": (browser)-> assert.equal browser.location, "http://localhost:3003/forms/submit" "should add location to history": (browser)-> assert.lengthOf browser.window.history, 2 "should send button value to server": (browser)-> assert.equal browser.text("#clicked"), "hit-me" "should send input values to server": (browser)-> assert.equal browser.text("#name"), "PI:NAME:<NAME>END_PI" assert.equal browser.text("#likes"), "Arm Biting" "should not send other button values to server": (browser)-> assert.equal browser.text("#image_clicked"), "undefined" "by clicking image button": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "PI:NAME:<NAME>END_PI").fill("likes", "PI:NAME:<NAME>END_PI").pressButton "#image_submit", @callback "should open new page": (browser)-> assert.equal browser.location, "http://localhost:3003/forms/submit" "should add location to history": (browser)-> assert.lengthOf browser.window.history, 2 "should send image value to server": (browser)-> assert.equal browser.text("#image_clicked"), "Image Submit" "should send input values to server": (browser)-> assert.equal browser.text("#name"), "PI:NAME:<NAME>END_PI" assert.equal browser.text("#likes"), "Arm Biting" "should not send other button values to server": (browser)-> assert.equal browser.text("#clicked"), "undefined" "by clicking input": Browser.wants "http://localhost:3003/forms/form" topic: (browser)-> browser.fill("Name", "PI:NAME:<NAME>END_PI").fill("likes", "PI:NAME:<NAME>END_PI").pressButton "Submit", @callback "should open new page": (browser)-> assert.equal browser.location, "http://localhost:3003/forms/submit" "should add location to history": (browser)-> assert.lengthOf browser.window.history, 2 "should send submit value to server": (browser)-> assert.equal browser.text("#clicked"), "Submit" "should send input values to server": (browser)-> assert.equal browser.text("#name"), "ArmBiter" assert.equal browser.text("#likes"), "PI:NAME:<NAME>END_PI Biting" # File upload "file upload": topic: -> brains.get "/forms/upload", (req, res)-> res.send """ <html> <body> <form method="post" enctype="multipart/form-data"> <input name="text" type="file"> <input name="image" type="file"> <button>Upload</button> </form> <form> <input name="get_file" type="file"> <input type="submit" value="Get Upload"> </form> </body> </html> """ brains.post "/forms/upload", (req, res)-> if req.files [text, image] = [req.files.text, req.files.image] data = File.readFileSync((text || image).path) if image digest = Crypto.createHash("md5").update(data).digest("hex") res.send """ <html> <head><title>#{(text || image).filename}</title></head> <body>#{digest || data}</body> </html> """ else res.send """ <html> <body>nothing</body> </html> """ "text": Browser.wants "http://localhost:3003/forms/upload" topic: (browser)-> filename = __dirname + "/data/random.txt" browser.attach("text", filename).pressButton "Upload", @callback "should upload file": (browser)-> assert.equal browser.text("body").trim(), "Random text" "should upload include name": (browser)-> assert.equal browser.text("title"), "random.txt" "binary": Browser.wants "http://localhost:3003/forms/upload" topic: (browser)-> @filename = __dirname + "/data/zombie.jpg" browser.attach("image", @filename).pressButton "Upload", @callback "should upload include name": (browser)-> assert.equal browser.text("title"), "zombie.jpg" "should upload file": (browser)-> digest = Crypto.createHash("md5").update(File.readFileSync(@filename)).digest("hex") assert.equal browser.text("body").trim(), digest "empty": Browser.wants "http://localhost:3003/forms/upload" topic: (browser)-> browser.attach "text", "" browser.pressButton "Upload", @callback "should not upload any file": (browser)-> assert.equal browser.text("body").trim(), "nothing" "not set": Browser.wants "http://localhost:3003/forms/upload" topic: (browser)-> browser.pressButton "Upload", @callback "should not send inputs without names": (browser)-> assert.equal browser.text("body").trim(), "nothing" "get": Browser.wants "http://localhost:3003/forms/upload" topic: (browser)-> filename = __dirname + "/data/random.txt" browser.attach("get_file", filename).pressButton "Get Upload", @callback "should send just the file basename": (browser)-> assert.equal browser.location.search, "?get_file=random.txt" "content length": topic: -> brains.get "/forms/urlencoded", (req, res)-> res.send """ <html> <body> <form method="post"> <input name="text" type="text"> <input type="submit" value="submit"> </form> </body> </html> """ brains.post "/forms/urlencoded", (req, res)-> text = req.body.text res.send """ <html> <head><title>bite back</title></head> <body>#{text}</body> </html> """ "post form urlencoded having content": Browser.wants "http://localhost:3003/forms/urlencoded" topic: (browser)-> browser.fill("text", "bite").pressButton "submit", @callback "should send content-length header": (browser) -> assert.include browser.lastRequest.headers, "content-length" "should match expected content-length": (browser) -> assert.equal browser.lastRequest.headers["content-length"], "text=bite".length "should have body with content of input field": (browser) -> assert.equal browser.text("body"), "bite" "post form urlencoded being empty": Browser.wants "http://localhost:3003/forms/urlencoded" topic: (browser)-> browser.pressButton "submit", @callback "should send content-length header": (browser) -> assert.include browser.lastRequest.headers, "content-length" "should have size of 0": (browser) -> assert.equal browser.lastRequest.headers["content-length"], 0 ).export(module)
[ { "context": "es:\n# https://haveibeenpwned.com/\n#\n# Author:\n# Jordan Neufeld <myjc.niv@gmail.com> https://github.com/neufeldte", "end": 216, "score": 0.9998758435249329, "start": 202, "tag": "NAME", "value": "Jordan Neufeld" }, { "context": "veibeenpwned.com/\n#\n# Author:\n# Jordan Neufeld <myjc.niv@gmail.com> https://github.com/neufeldtech\n#\n\nmodule.exports", "end": 236, "score": 0.9999315738677979, "start": 218, "tag": "EMAIL", "value": "myjc.niv@gmail.com" }, { "context": "n Neufeld <myjc.niv@gmail.com> https://github.com/neufeldtech\n#\n\nmodule.exports = (robot) ->\n robot.hear /(?:h", "end": 268, "score": 0.9992669820785522, "start": 257, "tag": "USERNAME", "value": "neufeldtech" } ]
scripts/pwned.coffee
neufeldtech/hubot-pwned
0
# Description: # Find out if an email address has been pwned # # Configuration: # # Commands: # has <email> been pwned? # is <email> pwned? # # Notes: # https://haveibeenpwned.com/ # # Author: # Jordan Neufeld <myjc.niv@gmail.com> https://github.com/neufeldtech # module.exports = (robot) -> robot.hear /(?:has|is) (\S+@\w+\.\w+) (?:been )?pwned\??/i, (msg) -> email = msg.match[1] robot.http("https://haveibeenpwned.com/api/v2/breachedaccount/"+email) .get() (err, res, body) -> if err res.send "Encountered an error :( #{err}" return else if res.statusCode == 200 body = JSON.parse(body) pwnedSites = "" i = 0 while i < body.length pwnedSites += "#{body[i].Domain}\n" i++ msg.send "Yes, #{email} has been pwned :sob:\n```#{pwnedSites}```" return else if res.statusCode == 404 msg.send "Nope, #{email} has not been pwned :tada:" return else msg.send "Encountered an error :(" return
9707
# Description: # Find out if an email address has been pwned # # Configuration: # # Commands: # has <email> been pwned? # is <email> pwned? # # Notes: # https://haveibeenpwned.com/ # # Author: # <NAME> <<EMAIL>> https://github.com/neufeldtech # module.exports = (robot) -> robot.hear /(?:has|is) (\S+@\w+\.\w+) (?:been )?pwned\??/i, (msg) -> email = msg.match[1] robot.http("https://haveibeenpwned.com/api/v2/breachedaccount/"+email) .get() (err, res, body) -> if err res.send "Encountered an error :( #{err}" return else if res.statusCode == 200 body = JSON.parse(body) pwnedSites = "" i = 0 while i < body.length pwnedSites += "#{body[i].Domain}\n" i++ msg.send "Yes, #{email} has been pwned :sob:\n```#{pwnedSites}```" return else if res.statusCode == 404 msg.send "Nope, #{email} has not been pwned :tada:" return else msg.send "Encountered an error :(" return
true
# Description: # Find out if an email address has been pwned # # Configuration: # # Commands: # has <email> been pwned? # is <email> pwned? # # Notes: # https://haveibeenpwned.com/ # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> https://github.com/neufeldtech # module.exports = (robot) -> robot.hear /(?:has|is) (\S+@\w+\.\w+) (?:been )?pwned\??/i, (msg) -> email = msg.match[1] robot.http("https://haveibeenpwned.com/api/v2/breachedaccount/"+email) .get() (err, res, body) -> if err res.send "Encountered an error :( #{err}" return else if res.statusCode == 200 body = JSON.parse(body) pwnedSites = "" i = 0 while i < body.length pwnedSites += "#{body[i].Domain}\n" i++ msg.send "Yes, #{email} has been pwned :sob:\n```#{pwnedSites}```" return else if res.statusCode == 404 msg.send "Nope, #{email} has not been pwned :tada:" return else msg.send "Encountered an error :(" return
[ { "context": "ne:\n https://docs.google.com/spreadsheet/ccc?key=0AgpC5gsTSm_4dDRVOEprRkVuSFZUWTlvclJ6UFRvdFE#gid=0\n###\n\n_ = require 'underscore'\nBackbone = re", "end": 313, "score": 0.9994955658912659, "start": 269, "tag": "KEY", "value": "0AgpC5gsTSm_4dDRVOEprRkVuSFZUWTlvclJ6UFRvdFE" }, { "context": "\"\n default: false\n username:\n name: \"username\"\n label: \"username\"\n description: \"incl", "end": 918, "score": 0.9967166185379028, "start": 910, "tag": "USERNAME", "value": "username" }, { "context": " username:\n name: \"username\"\n label: \"username\"\n description: \"includes interviewer's usern", "end": 942, "score": 0.8837321996688843, "start": 934, "tag": "USERNAME", "value": "username" } ]
kobo-docker/.vols/static/kpi/xlform/src/model.configs.coffee
OpenOPx/kobotoolbox
0
### defaultSurveyDetails -------------------- These values will be populated in the form builder and the user will have the option to turn them on or off. Details pulled from ODK documents / google docs. Notably this one: https://docs.google.com/spreadsheet/ccc?key=0AgpC5gsTSm_4dDRVOEprRkVuSFZUWTlvclJ6UFRvdFE#gid=0 ### _ = require 'underscore' Backbone = require 'backbone' $utils = require './model.utils' module.exports = do -> configs = {} configs.defaultSurveyDetails = start_time: name: "start" label: "start time" description: "Records when the survey was begun" default: true end_time: name: "end" label: "end time" description: "records when the survey was marked as completed" default: true today: name: "today" label: "today" description: "includes today's date" default: false username: name: "username" label: "username" description: "includes interviewer's username" default: false simserial: name: "simserial" label: "sim serial" description: "records the serial number of the network sim card" default: false subscriberid: name: "subscriberid" label: "subscriber id" description: "records the subscriber id of the sim card" default: false deviceid: name: "deviceid" label: "device id" aliases: ["imei"] description: "Records the internal device ID number (works on Android phones)" default: false phoneNumber: name: "phonenumber" label: "phone number" description: "Records the device's phone number, when available" default: false audit: name: "audit" label: "audit" description: "Records the behavior of enumerators as they navigate through a form" default: false do -> class SurveyDetailSchemaItem extends Backbone.Model _forSurvey: ()-> name: @get("name") label: @get("label") description: @get("description") class configs.SurveyDetailSchema extends Backbone.Collection model: SurveyDetailSchemaItem typeList: ()-> unless @_typeList @_typeList = (item.get("name") for item in @models) @_typeList configs.surveyDetailSchema = new configs.SurveyDetailSchema(_.values(configs.defaultSurveyDetails)) ### Default values for rows of each question type ### configs.defaultsGeneral = label: value: 'New Question' configs.defaultsForType = geotrace: label: value: "Record a line" required: value: false _hideUnlessChanged: true geoshape: label: value: "Record an area" required: value: false _hideUnlessChanged: true geopoint: label: value: "Record your current location" required: value: false _hideUnlessChanged: true image: label: value: "Point and shoot! Use the camera to take a photo" video: label: value: "Use the camera to record a video" audio: label: value: "Use the camera's microphone to record a sound" file: label: value: "Upload a file" note: label: value: "This note can be read out loud" required: value: false _hideUnlessChanged: true integer: label: value: "Enter a number" barcode: label: value: "Use the camera to scan a barcode" decimal: label: value: "Enter a number" date: label: value: "Enter a date" range: label: value: "Enter a number within a specified range" calculate: calculation: value: "" label: value: "calculation" required: value: false _hideUnlessChanged: true datetime: label: value: "Enter a date and time" time: label: value: "Enter a time" acknowledge: label: value: "Acknowledge" configs.paramTypes = { number: 'number', boolean: 'boolean' } configs.questionParams = { range: { start: { type: configs.paramTypes.number defaultValue: 0 } end: { type: configs.paramTypes.number defaultValue: 10 } step: { type: configs.paramTypes.number defaultValue: 1 } } image: { 'max-pixels': { type: configs.paramTypes.number defaultValue: 1024 } } select_one: { randomize: { type: configs.paramTypes.boolean } seed: { type: configs.paramTypes.number } } select_multiple: { randomize: { type: configs.paramTypes.boolean } seed: { type: configs.paramTypes.number } } } configs.columns = [ "type", "name", "label", "hint", "guidance_hint", "required", "relevant", "default", "constraint" ] configs.lookupRowType = do-> typeLabels = [ ["note", "Note", preventRequired: true], ["acknowledge", "Acknowledge"], ["text", "Text"], # expects text ["integer", "Integer"], #e.g. 42 ["decimal", "Decimal"], #e.g. 3.14 ["range", "Range"], #e.g. 1-5 ["geopoint", "Geopoint (GPS)"], # Can use satelite GPS coordinates ["geotrace", "Geotrace (GPS)"], # Can use satelite GPS coordinates ["geoshape", "Geoshape (GPS)"], # Can use satelite GPS coordinates ["image", "Image", isMedia: true], # Can use phone camera, for example ["barcode", "Barcode / QR code"], # Can scan a barcode using the phone camera ["date", "Date"], #e.g. (4 July, 1776) ["time", "Time"], #e.g. (4 July, 1776) ["datetime", "Date and Time"], #e.g. (2012-Jan-4 3:04PM) ["audio", "Audio", isMedia: true], # Can use phone microphone to record audio ["video", "Video", isMedia: true], # Can use phone camera to record video ["file", "File"], ["calculate", "Calculate"], ["select_one", "Select", orOtherOption: true, specifyChoice: true], ["score", "Score"], ["score__row", "Score Row"], ["rank", "Rank"], ["kobomatrix", "Advanced Matrix"], ["rank__level", "Rank Level"], ["select_multiple", "Multiple choice", orOtherOption: true, specifyChoice: true] ] class Type constructor: ([@name, @label, opts])-> opts = {} unless opts _.extend(@, opts) types = (new Type(arr) for arr in typeLabels) exp = (typeId)-> for tp in types when tp.name is typeId output = tp output exp.typeSelectList = do -> () -> types exp configs.autoset_kuid = true configs.columnOrder = do -> (key)-> if -1 is configs.columns.indexOf key configs.columns.push(key) configs.columns.indexOf key configs.newRowDetails = name: value: "" type: value: "text" hint: value: "" _hideUnlessChanged: true guidance_hint: value: "" required: value: false _hideUnlessChanged: true relevant: value: "" _hideUnlessChanged: true default: value: "" _hideUnlessChanged: true constraint: value: "" _hideUnlessChanged: true constraint_message: value: "" _hideUnlessChanged: true tags: value: '' _hideUnlessChanged: true appearance: value: '' _hideUnlessChanged: true configs.newGroupDetails = name: value: -> "group_#{$utils.txtid()}" label: value: "Group" type: value: "group" _isRepeat: value: false relevant: value: "" _hideUnlessChanged: true appearance: value: '' _hideUnlessChanged: true configs.question_types = {} ### String representations of boolean values which are accepted as true from the XLSForm. ### configs.truthyValues = [ "yes", "YES", "true", "true()", "TRUE", ] configs.falsyValues = [ "no", "NO", "false", "false()", "FALSE", ] # Alternative: XLF.configs.boolOutputs = {"true": "yes", "false": "no"} configs.boolOutputs = {"true": "true", "false": "false"} configs
155465
### defaultSurveyDetails -------------------- These values will be populated in the form builder and the user will have the option to turn them on or off. Details pulled from ODK documents / google docs. Notably this one: https://docs.google.com/spreadsheet/ccc?key=<KEY>#gid=0 ### _ = require 'underscore' Backbone = require 'backbone' $utils = require './model.utils' module.exports = do -> configs = {} configs.defaultSurveyDetails = start_time: name: "start" label: "start time" description: "Records when the survey was begun" default: true end_time: name: "end" label: "end time" description: "records when the survey was marked as completed" default: true today: name: "today" label: "today" description: "includes today's date" default: false username: name: "username" label: "username" description: "includes interviewer's username" default: false simserial: name: "simserial" label: "sim serial" description: "records the serial number of the network sim card" default: false subscriberid: name: "subscriberid" label: "subscriber id" description: "records the subscriber id of the sim card" default: false deviceid: name: "deviceid" label: "device id" aliases: ["imei"] description: "Records the internal device ID number (works on Android phones)" default: false phoneNumber: name: "phonenumber" label: "phone number" description: "Records the device's phone number, when available" default: false audit: name: "audit" label: "audit" description: "Records the behavior of enumerators as they navigate through a form" default: false do -> class SurveyDetailSchemaItem extends Backbone.Model _forSurvey: ()-> name: @get("name") label: @get("label") description: @get("description") class configs.SurveyDetailSchema extends Backbone.Collection model: SurveyDetailSchemaItem typeList: ()-> unless @_typeList @_typeList = (item.get("name") for item in @models) @_typeList configs.surveyDetailSchema = new configs.SurveyDetailSchema(_.values(configs.defaultSurveyDetails)) ### Default values for rows of each question type ### configs.defaultsGeneral = label: value: 'New Question' configs.defaultsForType = geotrace: label: value: "Record a line" required: value: false _hideUnlessChanged: true geoshape: label: value: "Record an area" required: value: false _hideUnlessChanged: true geopoint: label: value: "Record your current location" required: value: false _hideUnlessChanged: true image: label: value: "Point and shoot! Use the camera to take a photo" video: label: value: "Use the camera to record a video" audio: label: value: "Use the camera's microphone to record a sound" file: label: value: "Upload a file" note: label: value: "This note can be read out loud" required: value: false _hideUnlessChanged: true integer: label: value: "Enter a number" barcode: label: value: "Use the camera to scan a barcode" decimal: label: value: "Enter a number" date: label: value: "Enter a date" range: label: value: "Enter a number within a specified range" calculate: calculation: value: "" label: value: "calculation" required: value: false _hideUnlessChanged: true datetime: label: value: "Enter a date and time" time: label: value: "Enter a time" acknowledge: label: value: "Acknowledge" configs.paramTypes = { number: 'number', boolean: 'boolean' } configs.questionParams = { range: { start: { type: configs.paramTypes.number defaultValue: 0 } end: { type: configs.paramTypes.number defaultValue: 10 } step: { type: configs.paramTypes.number defaultValue: 1 } } image: { 'max-pixels': { type: configs.paramTypes.number defaultValue: 1024 } } select_one: { randomize: { type: configs.paramTypes.boolean } seed: { type: configs.paramTypes.number } } select_multiple: { randomize: { type: configs.paramTypes.boolean } seed: { type: configs.paramTypes.number } } } configs.columns = [ "type", "name", "label", "hint", "guidance_hint", "required", "relevant", "default", "constraint" ] configs.lookupRowType = do-> typeLabels = [ ["note", "Note", preventRequired: true], ["acknowledge", "Acknowledge"], ["text", "Text"], # expects text ["integer", "Integer"], #e.g. 42 ["decimal", "Decimal"], #e.g. 3.14 ["range", "Range"], #e.g. 1-5 ["geopoint", "Geopoint (GPS)"], # Can use satelite GPS coordinates ["geotrace", "Geotrace (GPS)"], # Can use satelite GPS coordinates ["geoshape", "Geoshape (GPS)"], # Can use satelite GPS coordinates ["image", "Image", isMedia: true], # Can use phone camera, for example ["barcode", "Barcode / QR code"], # Can scan a barcode using the phone camera ["date", "Date"], #e.g. (4 July, 1776) ["time", "Time"], #e.g. (4 July, 1776) ["datetime", "Date and Time"], #e.g. (2012-Jan-4 3:04PM) ["audio", "Audio", isMedia: true], # Can use phone microphone to record audio ["video", "Video", isMedia: true], # Can use phone camera to record video ["file", "File"], ["calculate", "Calculate"], ["select_one", "Select", orOtherOption: true, specifyChoice: true], ["score", "Score"], ["score__row", "Score Row"], ["rank", "Rank"], ["kobomatrix", "Advanced Matrix"], ["rank__level", "Rank Level"], ["select_multiple", "Multiple choice", orOtherOption: true, specifyChoice: true] ] class Type constructor: ([@name, @label, opts])-> opts = {} unless opts _.extend(@, opts) types = (new Type(arr) for arr in typeLabels) exp = (typeId)-> for tp in types when tp.name is typeId output = tp output exp.typeSelectList = do -> () -> types exp configs.autoset_kuid = true configs.columnOrder = do -> (key)-> if -1 is configs.columns.indexOf key configs.columns.push(key) configs.columns.indexOf key configs.newRowDetails = name: value: "" type: value: "text" hint: value: "" _hideUnlessChanged: true guidance_hint: value: "" required: value: false _hideUnlessChanged: true relevant: value: "" _hideUnlessChanged: true default: value: "" _hideUnlessChanged: true constraint: value: "" _hideUnlessChanged: true constraint_message: value: "" _hideUnlessChanged: true tags: value: '' _hideUnlessChanged: true appearance: value: '' _hideUnlessChanged: true configs.newGroupDetails = name: value: -> "group_#{$utils.txtid()}" label: value: "Group" type: value: "group" _isRepeat: value: false relevant: value: "" _hideUnlessChanged: true appearance: value: '' _hideUnlessChanged: true configs.question_types = {} ### String representations of boolean values which are accepted as true from the XLSForm. ### configs.truthyValues = [ "yes", "YES", "true", "true()", "TRUE", ] configs.falsyValues = [ "no", "NO", "false", "false()", "FALSE", ] # Alternative: XLF.configs.boolOutputs = {"true": "yes", "false": "no"} configs.boolOutputs = {"true": "true", "false": "false"} configs
true
### defaultSurveyDetails -------------------- These values will be populated in the form builder and the user will have the option to turn them on or off. Details pulled from ODK documents / google docs. Notably this one: https://docs.google.com/spreadsheet/ccc?key=PI:KEY:<KEY>END_PI#gid=0 ### _ = require 'underscore' Backbone = require 'backbone' $utils = require './model.utils' module.exports = do -> configs = {} configs.defaultSurveyDetails = start_time: name: "start" label: "start time" description: "Records when the survey was begun" default: true end_time: name: "end" label: "end time" description: "records when the survey was marked as completed" default: true today: name: "today" label: "today" description: "includes today's date" default: false username: name: "username" label: "username" description: "includes interviewer's username" default: false simserial: name: "simserial" label: "sim serial" description: "records the serial number of the network sim card" default: false subscriberid: name: "subscriberid" label: "subscriber id" description: "records the subscriber id of the sim card" default: false deviceid: name: "deviceid" label: "device id" aliases: ["imei"] description: "Records the internal device ID number (works on Android phones)" default: false phoneNumber: name: "phonenumber" label: "phone number" description: "Records the device's phone number, when available" default: false audit: name: "audit" label: "audit" description: "Records the behavior of enumerators as they navigate through a form" default: false do -> class SurveyDetailSchemaItem extends Backbone.Model _forSurvey: ()-> name: @get("name") label: @get("label") description: @get("description") class configs.SurveyDetailSchema extends Backbone.Collection model: SurveyDetailSchemaItem typeList: ()-> unless @_typeList @_typeList = (item.get("name") for item in @models) @_typeList configs.surveyDetailSchema = new configs.SurveyDetailSchema(_.values(configs.defaultSurveyDetails)) ### Default values for rows of each question type ### configs.defaultsGeneral = label: value: 'New Question' configs.defaultsForType = geotrace: label: value: "Record a line" required: value: false _hideUnlessChanged: true geoshape: label: value: "Record an area" required: value: false _hideUnlessChanged: true geopoint: label: value: "Record your current location" required: value: false _hideUnlessChanged: true image: label: value: "Point and shoot! Use the camera to take a photo" video: label: value: "Use the camera to record a video" audio: label: value: "Use the camera's microphone to record a sound" file: label: value: "Upload a file" note: label: value: "This note can be read out loud" required: value: false _hideUnlessChanged: true integer: label: value: "Enter a number" barcode: label: value: "Use the camera to scan a barcode" decimal: label: value: "Enter a number" date: label: value: "Enter a date" range: label: value: "Enter a number within a specified range" calculate: calculation: value: "" label: value: "calculation" required: value: false _hideUnlessChanged: true datetime: label: value: "Enter a date and time" time: label: value: "Enter a time" acknowledge: label: value: "Acknowledge" configs.paramTypes = { number: 'number', boolean: 'boolean' } configs.questionParams = { range: { start: { type: configs.paramTypes.number defaultValue: 0 } end: { type: configs.paramTypes.number defaultValue: 10 } step: { type: configs.paramTypes.number defaultValue: 1 } } image: { 'max-pixels': { type: configs.paramTypes.number defaultValue: 1024 } } select_one: { randomize: { type: configs.paramTypes.boolean } seed: { type: configs.paramTypes.number } } select_multiple: { randomize: { type: configs.paramTypes.boolean } seed: { type: configs.paramTypes.number } } } configs.columns = [ "type", "name", "label", "hint", "guidance_hint", "required", "relevant", "default", "constraint" ] configs.lookupRowType = do-> typeLabels = [ ["note", "Note", preventRequired: true], ["acknowledge", "Acknowledge"], ["text", "Text"], # expects text ["integer", "Integer"], #e.g. 42 ["decimal", "Decimal"], #e.g. 3.14 ["range", "Range"], #e.g. 1-5 ["geopoint", "Geopoint (GPS)"], # Can use satelite GPS coordinates ["geotrace", "Geotrace (GPS)"], # Can use satelite GPS coordinates ["geoshape", "Geoshape (GPS)"], # Can use satelite GPS coordinates ["image", "Image", isMedia: true], # Can use phone camera, for example ["barcode", "Barcode / QR code"], # Can scan a barcode using the phone camera ["date", "Date"], #e.g. (4 July, 1776) ["time", "Time"], #e.g. (4 July, 1776) ["datetime", "Date and Time"], #e.g. (2012-Jan-4 3:04PM) ["audio", "Audio", isMedia: true], # Can use phone microphone to record audio ["video", "Video", isMedia: true], # Can use phone camera to record video ["file", "File"], ["calculate", "Calculate"], ["select_one", "Select", orOtherOption: true, specifyChoice: true], ["score", "Score"], ["score__row", "Score Row"], ["rank", "Rank"], ["kobomatrix", "Advanced Matrix"], ["rank__level", "Rank Level"], ["select_multiple", "Multiple choice", orOtherOption: true, specifyChoice: true] ] class Type constructor: ([@name, @label, opts])-> opts = {} unless opts _.extend(@, opts) types = (new Type(arr) for arr in typeLabels) exp = (typeId)-> for tp in types when tp.name is typeId output = tp output exp.typeSelectList = do -> () -> types exp configs.autoset_kuid = true configs.columnOrder = do -> (key)-> if -1 is configs.columns.indexOf key configs.columns.push(key) configs.columns.indexOf key configs.newRowDetails = name: value: "" type: value: "text" hint: value: "" _hideUnlessChanged: true guidance_hint: value: "" required: value: false _hideUnlessChanged: true relevant: value: "" _hideUnlessChanged: true default: value: "" _hideUnlessChanged: true constraint: value: "" _hideUnlessChanged: true constraint_message: value: "" _hideUnlessChanged: true tags: value: '' _hideUnlessChanged: true appearance: value: '' _hideUnlessChanged: true configs.newGroupDetails = name: value: -> "group_#{$utils.txtid()}" label: value: "Group" type: value: "group" _isRepeat: value: false relevant: value: "" _hideUnlessChanged: true appearance: value: '' _hideUnlessChanged: true configs.question_types = {} ### String representations of boolean values which are accepted as true from the XLSForm. ### configs.truthyValues = [ "yes", "YES", "true", "true()", "TRUE", ] configs.falsyValues = [ "no", "NO", "false", "false()", "FALSE", ] # Alternative: XLF.configs.boolOutputs = {"true": "yes", "false": "no"} configs.boolOutputs = {"true": "true", "false": "false"} configs
[ { "context": " unit-tests\n\n echo '#---> BUILDING GO WORKERS (@farslan) <---#'\n $KONFIG_PROJECTROOT/go/build.sh\n\n ", "end": 595, "score": 0.9997137188911438, "start": 586, "tag": "USERNAME", "value": "(@farslan" }, { "context": "/go/build.sh\n\n echo '#---> BUILDING SOCIALAPI (@cihangir) <---#'\n pushd $KONFIG_PROJECTROOT/go/src/so", "end": 690, "score": 0.9996910095214844, "start": 680, "tag": "USERNAME", "value": "(@cihangir" }, { "context": "> AUTHORIZING THIS COMPUTER WITH MATCHING KITE.KEY (@farslan) <---#'\n KITE_KEY=$KONFIG_KITEHOME/kite.key\n", "end": 896, "score": 0.9997173547744751, "start": 887, "tag": "USERNAME", "value": "(@farslan" }, { "context": "still need this?)\n export PGPASSWORD=$KONFIG_POSTGRES_PASSWORD\n PSQL_COMMAND=\"psql -tA -h $KONFIG_", "end": 2897, "score": 0.5339558124542236, "start": 2889, "tag": "PASSWORD", "value": "POSTGRES" }, { "context": "IG_POSTGRES_DBNAME?user=social_superuser&password=social_superuser\" -path \"$KONFIG_PROJECTROOT/go/src/socialapi/db/s", "end": 8679, "score": 0.9993064403533936, "start": 8663, "tag": "PASSWORD", "value": "social_superuser" }, { "context": "ol\n cp $KONFIG_PROJECTROOT/go/src/github.com/koding/kite/kontrol/*.sql kontrol/\n sed -i -e \"s/so", "end": 12723, "score": 0.9993326663970947, "start": 12717, "tag": "USERNAME", "value": "koding" }, { "context": "odump\n\n echo \"#---> CLEARING ALGOLIA INDEXES: @chris <---#\"\n pushd $KONFIG_PROJECTROOT\n ./sc", "end": 13639, "score": 0.9830367565155029, "start": 13633, "tag": "USERNAME", "value": "@chris" }, { "context": "ho '#---> UPDATING MONGO DB TO WORK WITH SOCIALAPI @cihangir <---#'\n mongo $KONFIG_MONGO --eval='db.jAcco", "end": 14689, "score": 0.906695544719696, "start": 14680, "tag": "USERNAME", "value": "@cihangir" }, { "context": " --eval='db.jAccounts.update({\"profile.nickname\":\"guestuser\"},{$set:{type:\"unregistered\", socialApiId:0}});'\n", "end": 15100, "score": 0.999456524848938, "start": 15091, "tag": "USERNAME", "value": "guestuser" }, { "context": "() {\n\n echo '#---> CREATING VANILLA KODING DB @gokmen <---#'\n\n mongo $KONFIG_MONGO --eval \"db.drop", "end": 15253, "score": 0.9940228462219238, "start": 15246, "tag": "USERNAME", "value": "@gokmen" }, { "context": "DING TO LATEST CHANGES IN CODE (UPDATE PERMISSIONS @gokmen) <---#'\n node $KONFIG_PROJECTROOT/scripts/pe", "end": 15976, "score": 0.9971160888671875, "start": 15969, "tag": "USERNAME", "value": "@gokmen" }, { "context": "== \"--yes\" ]; then\n\n env PGPASSWORD=social_superuser psql -tA -h $KONFIG_POSTGRES_HOST $KONFIG_POSTGRE", "end": 17363, "score": 0.5515819191932678, "start": 17354, "tag": "USERNAME", "value": "superuser" } ]
config/generateRunFile.coffee
ezgikaysi/koding
1
traverse = require 'traverse' log = console.log fs = require 'fs' os = require 'os' path = require 'path' { isAllowed } = require '../deployment/grouptoenvmapping' generateDev = (KONFIG, options) -> options.requirementCommands ?= [] installScript = """ pushd $KONFIG_PROJECTROOT git submodule update --init npm install --unsafe-perm echo '#---> BUILDING CLIENT <---#' make -C $KONFIG_PROJECTROOT/client unit-tests echo '#---> BUILDING GO WORKERS (@farslan) <---#' $KONFIG_PROJECTROOT/go/build.sh echo '#---> BUILDING SOCIALAPI (@cihangir) <---#' pushd $KONFIG_PROJECTROOT/go/src/socialapi make configure # make install cleanchatnotifications echo '#---> AUTHORIZING THIS COMPUTER WITH MATCHING KITE.KEY (@farslan) <---#' KITE_KEY=$KONFIG_KITEHOME/kite.key mkdir $HOME/.kite &>/dev/null echo copying $KITE_KEY to $HOME/.kite/kite.key cp -f $KITE_KEY $HOME/.kite/kite.key echo echo echo 'ALL DONE. Enjoy! :)' echo echo """ run = """ #!/bin/bash # ------ THIS FILE IS AUTO-GENERATED ON EACH BUILD ----- # export KONFIG_PROJECTROOT=$(cd $(dirname $0); pwd) ENV_SHELL_FILE=${ENV_SHELL_FILE:-$(dirname $0)/.env.sh} if [ -f "$ENV_SHELL_FILE" ]; then source $ENV_SHELL_FILE else echo "error: shell environment file does not exist" exit 1 fi mkdir $KONFIG_PROJECTROOT/.logs &>/dev/null SERVICES="mongo redis postgres rabbitmq imply" NGINX_CONF="$KONFIG_PROJECTROOT/nginx.conf" NGINX_PID="$KONFIG_PROJECTROOT/nginx.pid" #{options.requirementCommands?.join "\n"} trap ctrl_c INT function ctrl_c () { supervisorctl shutdown } function nginxstop () { if [ -a $NGINX_PID ]; then echo "stopping nginx" nginx -c $NGINX_CONF -g "pid $NGINX_PID;" -s quit fi } function nginxrun () { nginxstop echo "starting nginx" nginx -c $NGINX_CONF -g "pid $NGINX_PID;" } function checkrunfile () { if [ "$KONFIG_PROJECTROOT/run" -ot "$KONFIG_PROJECTROOT/config/main.$KONFIG_CONFIGNAME.coffee" ]; then echo your run file is older than your config file. doing ./configure. sleep 1 ./configure echo -e "\n\nPlease do ./run again\n" exit 1; fi if [ "$KONFIG_PROJECTROOT/run" -ot "$KONFIG_PROJECTROOT/configure" ]; then echo your run file is older than your configure file. doing ./configure. sleep 1 ./configure echo -e "\n\nPlease do ./run again\n" exit 1; fi } function migrations () { # a temporary migration line (do we still need this?) export PGPASSWORD=$KONFIG_POSTGRES_PASSWORD PSQL_COMMAND="psql -tA -h $KONFIG_POSTGRES_HOST $KONFIG_POSTGRES_DBNAME -U $KONFIG_POSTGRES_USERNAME" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_type_constant_enum\" ADD VALUE IF NOT EXISTS 'collaboration';" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_participant_status_constant_enum\" ADD VALUE IF NOT EXISTS 'blocked';" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_type_constant_enum\" ADD VALUE IF NOT EXISTS 'linkedtopic';" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_type_constant_enum\" ADD VALUE IF NOT EXISTS 'bot';" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_message_type_constant_enum\" ADD VALUE IF NOT EXISTS 'bot';" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_message_type_constant_enum\" ADD VALUE IF NOT EXISTS 'system';" $PSQL_COMMAND -c "ALTER TYPE \"payment\".\"plan_title_enum\" ADD VALUE IF NOT EXISTS 'bootstrap';" $PSQL_COMMAND -c "ALTER TYPE \"payment\".\"plan_title_enum\" ADD VALUE IF NOT EXISTS 'startup';" $PSQL_COMMAND -c "ALTER TYPE \"payment\".\"plan_title_enum\" ADD VALUE IF NOT EXISTS 'enterprise';" $PSQL_COMMAND -c "ALTER TYPE \"payment\".\"plan_title_enum\" ADD VALUE IF NOT EXISTS 'team_base';" $PSQL_COMMAND -c "ALTER TYPE \"payment\".\"plan_title_enum\" ADD VALUE IF NOT EXISTS 'team_free';" } function run () { # Check if PG DB schema update required go run $KONFIG_PROJECTROOT/go/src/socialapi/tests/pg-update.go $KONFIG_POSTGRES_HOST $KONFIG_POSTGRES_PORT RESULT=$? if [ $RESULT -ne 0 ]; then exit 1 fi # Update node modules if ! scripts/check-node_modules.sh; then npm install --silent fi # Check everything else check # Remove old watcher files (do we still need this?) rm -rf $KONFIG_PROJECTROOT/go/bin/goldorf-main-* rm -rf $KONFIG_PROJECTROOT/go/bin/watcher-* # Run Go builder $KONFIG_PROJECTROOT/go/build.sh # Run Social Api builder make -C $KONFIG_PROJECTROOT/go/src/socialapi configure # Do PG Migration if necessary migrate up # Create default workspaces node scripts/create-default-workspace # Sanitize email addresses node $KONFIG_PROJECTROOT/scripts/sanitize-email supervisord && sleep 1 # Show the all logs of workers tail -fq ./.logs/*.log } function docker_compose() { if ! which docker-compose; then echo 'error: docker-compose is not found' echo '$ pip install docker-compose' exit 1 fi local ENTRYPOINT="/opt/koding/scripts/bootstrap-container $@" docker-compose run --entrypoint $ENTRYPOINT backend } function printHelp (){ echo "Usage: " echo "" echo " run : to start koding" echo " run docker-compose : to start koding in docker-compose environment" echo " run exec : to exec arbitrary commands" echo " run install : to compile/install client and " echo " run buildclient : to see of specified worker logs only" echo " run logs : to see all workers logs" echo " run log [worker] : to see of specified worker logs only" echo " run buildservices : to initialize and start services" echo " run resetdb : to reset databases" echo " run services : to stop and restart services" echo " run worker : to list workers" echo " run printconfig : to print koding config environment variables (output in json via --json flag)" echo " run worker [worker] : to run a single worker" echo " run migrate [command] : to apply/revert database changes (command: [create|up|down|version|reset|redo|to|goto])" echo " run importusers : to import koding user data" echo " run nodeservertests : to run tests for node.js web server" echo " run socialworkertests : to run tests for social worker" echo " run nodetestfiles : to run a single test or all test files in a directory" echo " run sanitize-email : to sanitize email" echo " run help : to show this list" echo "" } function migrate () { migrations params=(create up down version reset redo to goto) param=$1 case "${params[@]}" in *"$param"*) ;; *) echo "Error: Command not found: $param" echo "Usage: run migrate COMMAND [arg]" echo "" echo "Commands: " echo " create [filename] : create new migration file in path" echo " up : apply all available migrations" echo " down : roll back all migrations" echo " redo : roll back the most recently applied migration, then run it again" echo " reset : run down and then up command" echo " version : show the current migration version" echo " to [n] : (+n) apply the next n / (-n) roll back the previous n migrations" echo " goto [n] : go to specific migration" echo "" exit 1 ;; esac if [ "$param" == "to" ]; then param="migrate" elif [ "$param" == "create" ] && [ -z "$2" ]; then echo "Please choose a migration file name. (ex. add_created_at_column_account)" echo "Usage: run migrate create [filename]" echo "" exit 1 fi $GOBIN/migrate -url "postgres://$KONFIG_POSTGRES_HOST:$KONFIG_POSTGRES_PORT/$KONFIG_POSTGRES_DBNAME?user=social_superuser&password=social_superuser" -path "$KONFIG_PROJECTROOT/go/src/socialapi/db/sql/migrations" $param $2 if [ "$param" == "create" ]; then echo "Please edit created script files and add them to your repository." fi } function check (){ check_service_dependencies if [[ `uname` == 'Darwin' ]]; then if [ -z "$DOCKER_HOST" ]; then echo "You need to export DOCKER_HOST, run 'boot2docker up' and follow the instructions." exit 1 fi fi mongo $KONFIG_MONGO --eval "db.stats()" > /dev/null # do a simple harmless command of some sort RESULT=$? # returns 0 if mongo eval succeeds if [ $RESULT -ne 0 ]; then echo "" echo "Can't talk to mongodb at $KONFIG_MONGO, is it not running? exiting." exit 1 fi EXISTS=$(PGPASSWORD=$KONFIG_POSTGRES_PASSWORD psql -tA -h $KONFIG_POSTGRES_HOST social -U $KONFIG_POSTGRES_USERNAME -c "Select 1 from pg_tables where tablename = 'key' AND schemaname = 'kite';") if [[ $EXISTS != '1' ]]; then echo "" echo "You don't have the new Kontrol Postgres. Please call ./run buildservices." exit 1 fi } function check_psql () { command -v psql >/dev/null 2>&1 || { echo >&2 "I require psql but it's not installed. (brew install postgresql) Aborting."; exit 1; } } function check_service_dependencies () { echo "checking required services: nginx, docker, mongo, graphicsmagick..." command -v go >/dev/null 2>&1 || { echo >&2 "I require go but it's not installed. Aborting."; exit 1; } command -v docker >/dev/null 2>&1 || { echo >&2 "I require docker but it's not installed. Aborting."; exit 1; } command -v nginx >/dev/null 2>&1 || { echo >&2 "I require nginx but it's not installed. (brew install nginx maybe?) Aborting."; exit 1; } command -v mongorestore >/dev/null 2>&1 || { echo >&2 "I require mongorestore but it's not installed. Aborting."; exit 1; } command -v node >/dev/null 2>&1 || { echo >&2 "I require node but it's not installed. Aborting."; exit 1; } command -v npm >/dev/null 2>&1 || { echo >&2 "I require npm but it's not installed. Aborting."; exit 1; } command -v gulp >/dev/null 2>&1 || { echo >&2 "I require gulp but it's not installed. (npm i gulp -g) Aborting."; exit 1; } # command -v stylus >/dev/null 2>&1 || { echo >&2 "I require stylus but it's not installed. (npm i stylus -g) Aborting."; exit 1; } command -v coffee >/dev/null 2>&1 || { echo >&2 "I require coffee-script but it's not installed. (npm i coffee-script -g) Aborting."; exit 1; } check_psql if [[ `uname` == 'Darwin' ]]; then brew info graphicsmagick >/dev/null 2>&1 || { echo >&2 "I require graphicsmagick but it's not installed. Aborting."; exit 1; } command -v boot2docker >/dev/null 2>&1 || { echo >&2 "I require boot2docker but it's not installed. Aborting."; exit 1; } elif [[ `uname` == 'Linux' ]]; then command -v gm >/dev/null 2>&1 || { echo >&2 "I require graphicsmagick but it's not installed. Aborting."; exit 1; } fi set -o errexit scripts/check-node-version.sh scripts/check-npm-version.sh scripts/check-gulp-version.sh scripts/check-go-version.sh scripts/check-supervisor.sh set +o errexit } function build_services () { if [[ `uname` == 'Darwin' ]]; then boot2docker up fi echo "Stopping services: $SERVICES" docker stop $SERVICES echo "Removing services: $SERVICES" docker rm $SERVICES # Build Mongo service pushd $KONFIG_PROJECTROOT/install/docker-mongo docker build -t koding/mongo . # Build postgres pushd $KONFIG_PROJECTROOT/go/src/socialapi/db/sql # Include this to dockerfile before we continute with building mkdir -p kontrol cp $KONFIG_PROJECTROOT/go/src/github.com/koding/kite/kontrol/*.sql kontrol/ sed -i -e "s/somerandompassword/$KONFIG_KONTROL_POSTGRES_PASSWORD/" kontrol/001-schema.sql sed -i -e "s/kontrolapplication/$KONFIG_KONTROL_POSTGRES_USERNAME/" kontrol/001-schema.sql docker build -t koding/postgres . docker run -d -p 27017:27017 --name=mongo koding/mongo --dbpath /data/db --smallfiles --nojournal docker run -d -p 5672:5672 -p 15672:15672 --name=rabbitmq rabbitmq:3-management docker run -d -p 6379:6379 --name=redis redis docker run -d -p 5432:5432 --name=postgres koding/postgres docker run -d -p 18081-18110:8081-8110 -p 18200:8200 -p 19095:9095 --name=imply imply/imply:1.2.1 restoredefaultmongodump echo "#---> CLEARING ALGOLIA INDEXES: @chris <---#" pushd $KONFIG_PROJECTROOT ./scripts/clear-algolia-index.sh -i "accounts$KONFIG_SOCIALAPI_ALGOLIA_INDEXSUFFIX" ./scripts/clear-algolia-index.sh -i "topics$KONFIG_SOCIALAPI_ALGOLIA_INDEXSUFFIX" ./scripts/clear-algolia-index.sh -i "messages$KONFIG_SOCIALAPI_ALGOLIA_INDEXSUFFIX" migrate up } function services () { if [[ `uname` == 'Darwin' ]]; then boot2docker up fi EXISTS=$(docker inspect --format="{{ .State.Running }}" $SERVICES 2> /dev/null) if [ $? -eq 1 ]; then echo "" echo "Some of containers are missing, please do ./run buildservices" exit 1 fi echo "Stopping services: $SERVICES" docker stop $SERVICES echo "Starting services: $SERVICES" docker start $SERVICES nginxrun } function importusers () { node $KONFIG_PROJECTROOT/scripts/user-importer -c dev migrateusers } function migrateusers () { echo '#---> UPDATING MONGO DB TO WORK WITH SOCIALAPI @cihangir <---#' mongo $KONFIG_MONGO --eval='db.jAccounts.update({},{$unset:{socialApiId:0}},{multi:true}); db.jGroups.update({},{$unset:{socialApiChannelId:0}},{multi:true});' go run $KONFIG_PROJECTROOT/go/src/socialapi/workers/cmd/migrator/main.go -c $KONFIG_SOCIALAPI_CONFIGFILEPATH # Required step for guestuser mongo $KONFIG_MONGO --eval='db.jAccounts.update({"profile.nickname":"guestuser"},{$set:{type:"unregistered", socialApiId:0}});' } function restoredefaultmongodump () { echo '#---> CREATING VANILLA KODING DB @gokmen <---#' mongo $KONFIG_MONGO --eval "db.dropDatabase()" pushd $KONFIG_PROJECTROOT/install/docker-mongo if [[ -f $KONFIG_PROJECTROOT/install/docker-mongo/custom-db-dump.tar.bz2 ]]; then tar jxvf $KONFIG_PROJECTROOT/install/docker-mongo/custom-db-dump.tar.bz2 else tar jxvf $KONFIG_PROJECTROOT/install/docker-mongo/default-db-dump.tar.bz2 fi read HOST _ DB <<<"$(echo $KONFIG_MONGO | awk -F '[:/]' '{ print $1, $2, $3}')" mongorestore --host $HOST --db $DB dump/koding rm -rf ./dump updatePermissions } function updatePermissions () { echo '#---> UPDATING MONGO DATABASE ACCORDING TO LATEST CHANGES IN CODE (UPDATE PERMISSIONS @gokmen) <---#' node $KONFIG_PROJECTROOT/scripts/permission-updater -c dev --reset } function updateusers () { node $KONFIG_PROJECTROOT/scripts/user-updater } function create_default_workspace () { node $KONFIG_PROJECTROOT/scripts/create-default-workspace } function cleanchatnotifications () { $GOBIN/notification -c $KONFIG_SOCIALAPI_CONFIGFILEPATH -h } if [ "$#" == "0" ]; then checkrunfile run $1 elif [ "$1" == "docker-compose" ]; then shift docker_compose elif [ "$1" == "exec" ]; then shift exec "$@" elif [ "$1" == "install" ]; then check_service_dependencies #{installScript} elif [ "$1" == "printconfig" ]; then printconfig $@ elif [[ "$1" == "log" || "$1" == "logs" ]]; then trap - INT trap if [ "$2" == "" ]; then tail -fq ./.logs/*.log else tail -fq ./.logs/$2.log fi elif [ "$1" == "cleanup" ]; then ./cleanup $@ elif [ "$1" == "buildclient" ]; then make -C $KONFIG_PROJECTROOT/client dist elif [ "$1" == "services" ]; then check_service_dependencies services elif [ "$1" == "updatepermissions" ]; then updatePermissions elif [ "$1" == "resetdb" ]; then if [ "$2" == "--yes" ]; then env PGPASSWORD=social_superuser psql -tA -h $KONFIG_POSTGRES_HOST $KONFIG_POSTGRES_DBNAME -U social_superuser -c "DELETE FROM \"api\".\"channel_participant\"; DELETE FROM \"api\".\"channel\";DELETE FROM \"api\".\"account\";" restoredefaultmongodump migrateusers exit 0 fi read -p "This will reset current databases, all data will be lost! (y/N)" -n 1 -r echo "" if [[ ! $REPLY =~ ^[Yy]$ ]] then exit 1 fi env PGPASSWORD=social_superuser psql -tA -h $KONFIG_POSTGRES_HOST $KONFIG_POSTGRES_DBNAME -U social_superuser -c "DELETE FROM \"api\".\"channel_participant\"; DELETE FROM \"api\".\"channel\";DELETE FROM \"api\".\"account\";" restoredefaultmongodump migrateusers elif [ "$1" == "buildservices" ]; then check_service_dependencies if [ "$2" != "force" ]; then read -p "This will destroy existing images, do you want to continue? (y/N)" -n 1 -r echo "" if [[ ! $REPLY =~ ^[Yy]$ ]]; then exit 1 fi fi build_services migrate up elif [ "$1" == "help" ]; then printHelp elif [ "$1" == "importusers" ]; then importusers elif [ "$1" == "updateusers" ]; then updateusers elif [ "$1" == "create_default_workspace" ]; then create_default_workspace elif [ "$1" == "cleanchatnotifications" ]; then cleanchatnotifications elif [ "$1" == "worker" ]; then if [ "$2" == "" ]; then echo Available workers: echo "-------------------" supervisorctl status | awk '${print $1} | sort' else trap - INT trap exec supervisorctl start $2 fi elif [ "$1" == "migrate" ]; then check_psql if [ -z "$2" ]; then echo "Please choose a migrate command [create|up|down|version|reset|redo|to|goto]" echo "" else pushd $GOPATH/src/socialapi make install-migrate migrate $2 $3 fi elif [ "$1" == "vmwatchertests" ]; then go test koding/vmwatcher -test.v=true elif [ "$1" == "janitortests" ]; then pushd $KONFIG_PROJECTROOT/go/src/koding/workers/janitor ./test.sh elif [ "$1" == "gatheringestortests" ]; then go test koding/workers/gatheringestor -test.v=true elif [ "$1" == "gomodeltests" ]; then go test koding/db/mongodb/modelhelper -test.v=true elif [ "$1" == "socialworkertests" ]; then $KONFIG_PROJECTROOT/scripts/node-testing/mocha-runner "$KONFIG_PROJECTROOT/workers/social" elif [ "$1" == "nodeservertests" ]; then $KONFIG_PROJECTROOT/scripts/node-testing/mocha-runner "$KONFIG_PROJECTROOT/servers/lib/server" # To run specific test directory or a single test file elif [ "$1" == "nodetestfiles" ]; then $KONFIG_PROJECTROOT/scripts/node-testing/mocha-runner $2 elif [ "$1" == "sanitize-email" ]; then node $KONFIG_PROJECTROOT/scripts/sanitize-email elif [ "$1" == "migrations" ]; then migrations else echo "Unknown command: $1" printHelp fi # ------ THIS FILE IS AUTO-GENERATED BY ./configure ----- #\n """ return run generateSandbox = generateRunFile = (KONFIG) -> return """ #!/bin/bash export HOME=/home/ec2-user ENV_SHELL_FILE=${ENV_SHELL_FILE:-$(dirname $0)/.env.sh} if [ -f "$ENV_SHELL_FILE" ]; then source $ENV_SHELL_FILE else echo "error: shell environment file does not exist" exit 1 fi COMMAND=$1 shift case "$COMMAND" in exec) exec "$@";; esac """ module.exports = { dev: generateDev, default: generateDev, sandbox: generateSandbox, prod: generateSandbox }
123601
traverse = require 'traverse' log = console.log fs = require 'fs' os = require 'os' path = require 'path' { isAllowed } = require '../deployment/grouptoenvmapping' generateDev = (KONFIG, options) -> options.requirementCommands ?= [] installScript = """ pushd $KONFIG_PROJECTROOT git submodule update --init npm install --unsafe-perm echo '#---> BUILDING CLIENT <---#' make -C $KONFIG_PROJECTROOT/client unit-tests echo '#---> BUILDING GO WORKERS (@farslan) <---#' $KONFIG_PROJECTROOT/go/build.sh echo '#---> BUILDING SOCIALAPI (@cihangir) <---#' pushd $KONFIG_PROJECTROOT/go/src/socialapi make configure # make install cleanchatnotifications echo '#---> AUTHORIZING THIS COMPUTER WITH MATCHING KITE.KEY (@farslan) <---#' KITE_KEY=$KONFIG_KITEHOME/kite.key mkdir $HOME/.kite &>/dev/null echo copying $KITE_KEY to $HOME/.kite/kite.key cp -f $KITE_KEY $HOME/.kite/kite.key echo echo echo 'ALL DONE. Enjoy! :)' echo echo """ run = """ #!/bin/bash # ------ THIS FILE IS AUTO-GENERATED ON EACH BUILD ----- # export KONFIG_PROJECTROOT=$(cd $(dirname $0); pwd) ENV_SHELL_FILE=${ENV_SHELL_FILE:-$(dirname $0)/.env.sh} if [ -f "$ENV_SHELL_FILE" ]; then source $ENV_SHELL_FILE else echo "error: shell environment file does not exist" exit 1 fi mkdir $KONFIG_PROJECTROOT/.logs &>/dev/null SERVICES="mongo redis postgres rabbitmq imply" NGINX_CONF="$KONFIG_PROJECTROOT/nginx.conf" NGINX_PID="$KONFIG_PROJECTROOT/nginx.pid" #{options.requirementCommands?.join "\n"} trap ctrl_c INT function ctrl_c () { supervisorctl shutdown } function nginxstop () { if [ -a $NGINX_PID ]; then echo "stopping nginx" nginx -c $NGINX_CONF -g "pid $NGINX_PID;" -s quit fi } function nginxrun () { nginxstop echo "starting nginx" nginx -c $NGINX_CONF -g "pid $NGINX_PID;" } function checkrunfile () { if [ "$KONFIG_PROJECTROOT/run" -ot "$KONFIG_PROJECTROOT/config/main.$KONFIG_CONFIGNAME.coffee" ]; then echo your run file is older than your config file. doing ./configure. sleep 1 ./configure echo -e "\n\nPlease do ./run again\n" exit 1; fi if [ "$KONFIG_PROJECTROOT/run" -ot "$KONFIG_PROJECTROOT/configure" ]; then echo your run file is older than your configure file. doing ./configure. sleep 1 ./configure echo -e "\n\nPlease do ./run again\n" exit 1; fi } function migrations () { # a temporary migration line (do we still need this?) export PGPASSWORD=$KONFIG_<PASSWORD>_PASSWORD PSQL_COMMAND="psql -tA -h $KONFIG_POSTGRES_HOST $KONFIG_POSTGRES_DBNAME -U $KONFIG_POSTGRES_USERNAME" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_type_constant_enum\" ADD VALUE IF NOT EXISTS 'collaboration';" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_participant_status_constant_enum\" ADD VALUE IF NOT EXISTS 'blocked';" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_type_constant_enum\" ADD VALUE IF NOT EXISTS 'linkedtopic';" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_type_constant_enum\" ADD VALUE IF NOT EXISTS 'bot';" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_message_type_constant_enum\" ADD VALUE IF NOT EXISTS 'bot';" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_message_type_constant_enum\" ADD VALUE IF NOT EXISTS 'system';" $PSQL_COMMAND -c "ALTER TYPE \"payment\".\"plan_title_enum\" ADD VALUE IF NOT EXISTS 'bootstrap';" $PSQL_COMMAND -c "ALTER TYPE \"payment\".\"plan_title_enum\" ADD VALUE IF NOT EXISTS 'startup';" $PSQL_COMMAND -c "ALTER TYPE \"payment\".\"plan_title_enum\" ADD VALUE IF NOT EXISTS 'enterprise';" $PSQL_COMMAND -c "ALTER TYPE \"payment\".\"plan_title_enum\" ADD VALUE IF NOT EXISTS 'team_base';" $PSQL_COMMAND -c "ALTER TYPE \"payment\".\"plan_title_enum\" ADD VALUE IF NOT EXISTS 'team_free';" } function run () { # Check if PG DB schema update required go run $KONFIG_PROJECTROOT/go/src/socialapi/tests/pg-update.go $KONFIG_POSTGRES_HOST $KONFIG_POSTGRES_PORT RESULT=$? if [ $RESULT -ne 0 ]; then exit 1 fi # Update node modules if ! scripts/check-node_modules.sh; then npm install --silent fi # Check everything else check # Remove old watcher files (do we still need this?) rm -rf $KONFIG_PROJECTROOT/go/bin/goldorf-main-* rm -rf $KONFIG_PROJECTROOT/go/bin/watcher-* # Run Go builder $KONFIG_PROJECTROOT/go/build.sh # Run Social Api builder make -C $KONFIG_PROJECTROOT/go/src/socialapi configure # Do PG Migration if necessary migrate up # Create default workspaces node scripts/create-default-workspace # Sanitize email addresses node $KONFIG_PROJECTROOT/scripts/sanitize-email supervisord && sleep 1 # Show the all logs of workers tail -fq ./.logs/*.log } function docker_compose() { if ! which docker-compose; then echo 'error: docker-compose is not found' echo '$ pip install docker-compose' exit 1 fi local ENTRYPOINT="/opt/koding/scripts/bootstrap-container $@" docker-compose run --entrypoint $ENTRYPOINT backend } function printHelp (){ echo "Usage: " echo "" echo " run : to start koding" echo " run docker-compose : to start koding in docker-compose environment" echo " run exec : to exec arbitrary commands" echo " run install : to compile/install client and " echo " run buildclient : to see of specified worker logs only" echo " run logs : to see all workers logs" echo " run log [worker] : to see of specified worker logs only" echo " run buildservices : to initialize and start services" echo " run resetdb : to reset databases" echo " run services : to stop and restart services" echo " run worker : to list workers" echo " run printconfig : to print koding config environment variables (output in json via --json flag)" echo " run worker [worker] : to run a single worker" echo " run migrate [command] : to apply/revert database changes (command: [create|up|down|version|reset|redo|to|goto])" echo " run importusers : to import koding user data" echo " run nodeservertests : to run tests for node.js web server" echo " run socialworkertests : to run tests for social worker" echo " run nodetestfiles : to run a single test or all test files in a directory" echo " run sanitize-email : to sanitize email" echo " run help : to show this list" echo "" } function migrate () { migrations params=(create up down version reset redo to goto) param=$1 case "${params[@]}" in *"$param"*) ;; *) echo "Error: Command not found: $param" echo "Usage: run migrate COMMAND [arg]" echo "" echo "Commands: " echo " create [filename] : create new migration file in path" echo " up : apply all available migrations" echo " down : roll back all migrations" echo " redo : roll back the most recently applied migration, then run it again" echo " reset : run down and then up command" echo " version : show the current migration version" echo " to [n] : (+n) apply the next n / (-n) roll back the previous n migrations" echo " goto [n] : go to specific migration" echo "" exit 1 ;; esac if [ "$param" == "to" ]; then param="migrate" elif [ "$param" == "create" ] && [ -z "$2" ]; then echo "Please choose a migration file name. (ex. add_created_at_column_account)" echo "Usage: run migrate create [filename]" echo "" exit 1 fi $GOBIN/migrate -url "postgres://$KONFIG_POSTGRES_HOST:$KONFIG_POSTGRES_PORT/$KONFIG_POSTGRES_DBNAME?user=social_superuser&password=<PASSWORD>" -path "$KONFIG_PROJECTROOT/go/src/socialapi/db/sql/migrations" $param $2 if [ "$param" == "create" ]; then echo "Please edit created script files and add them to your repository." fi } function check (){ check_service_dependencies if [[ `uname` == 'Darwin' ]]; then if [ -z "$DOCKER_HOST" ]; then echo "You need to export DOCKER_HOST, run 'boot2docker up' and follow the instructions." exit 1 fi fi mongo $KONFIG_MONGO --eval "db.stats()" > /dev/null # do a simple harmless command of some sort RESULT=$? # returns 0 if mongo eval succeeds if [ $RESULT -ne 0 ]; then echo "" echo "Can't talk to mongodb at $KONFIG_MONGO, is it not running? exiting." exit 1 fi EXISTS=$(PGPASSWORD=$KONFIG_POSTGRES_PASSWORD psql -tA -h $KONFIG_POSTGRES_HOST social -U $KONFIG_POSTGRES_USERNAME -c "Select 1 from pg_tables where tablename = 'key' AND schemaname = 'kite';") if [[ $EXISTS != '1' ]]; then echo "" echo "You don't have the new Kontrol Postgres. Please call ./run buildservices." exit 1 fi } function check_psql () { command -v psql >/dev/null 2>&1 || { echo >&2 "I require psql but it's not installed. (brew install postgresql) Aborting."; exit 1; } } function check_service_dependencies () { echo "checking required services: nginx, docker, mongo, graphicsmagick..." command -v go >/dev/null 2>&1 || { echo >&2 "I require go but it's not installed. Aborting."; exit 1; } command -v docker >/dev/null 2>&1 || { echo >&2 "I require docker but it's not installed. Aborting."; exit 1; } command -v nginx >/dev/null 2>&1 || { echo >&2 "I require nginx but it's not installed. (brew install nginx maybe?) Aborting."; exit 1; } command -v mongorestore >/dev/null 2>&1 || { echo >&2 "I require mongorestore but it's not installed. Aborting."; exit 1; } command -v node >/dev/null 2>&1 || { echo >&2 "I require node but it's not installed. Aborting."; exit 1; } command -v npm >/dev/null 2>&1 || { echo >&2 "I require npm but it's not installed. Aborting."; exit 1; } command -v gulp >/dev/null 2>&1 || { echo >&2 "I require gulp but it's not installed. (npm i gulp -g) Aborting."; exit 1; } # command -v stylus >/dev/null 2>&1 || { echo >&2 "I require stylus but it's not installed. (npm i stylus -g) Aborting."; exit 1; } command -v coffee >/dev/null 2>&1 || { echo >&2 "I require coffee-script but it's not installed. (npm i coffee-script -g) Aborting."; exit 1; } check_psql if [[ `uname` == 'Darwin' ]]; then brew info graphicsmagick >/dev/null 2>&1 || { echo >&2 "I require graphicsmagick but it's not installed. Aborting."; exit 1; } command -v boot2docker >/dev/null 2>&1 || { echo >&2 "I require boot2docker but it's not installed. Aborting."; exit 1; } elif [[ `uname` == 'Linux' ]]; then command -v gm >/dev/null 2>&1 || { echo >&2 "I require graphicsmagick but it's not installed. Aborting."; exit 1; } fi set -o errexit scripts/check-node-version.sh scripts/check-npm-version.sh scripts/check-gulp-version.sh scripts/check-go-version.sh scripts/check-supervisor.sh set +o errexit } function build_services () { if [[ `uname` == 'Darwin' ]]; then boot2docker up fi echo "Stopping services: $SERVICES" docker stop $SERVICES echo "Removing services: $SERVICES" docker rm $SERVICES # Build Mongo service pushd $KONFIG_PROJECTROOT/install/docker-mongo docker build -t koding/mongo . # Build postgres pushd $KONFIG_PROJECTROOT/go/src/socialapi/db/sql # Include this to dockerfile before we continute with building mkdir -p kontrol cp $KONFIG_PROJECTROOT/go/src/github.com/koding/kite/kontrol/*.sql kontrol/ sed -i -e "s/somerandompassword/$KONFIG_KONTROL_POSTGRES_PASSWORD/" kontrol/001-schema.sql sed -i -e "s/kontrolapplication/$KONFIG_KONTROL_POSTGRES_USERNAME/" kontrol/001-schema.sql docker build -t koding/postgres . docker run -d -p 27017:27017 --name=mongo koding/mongo --dbpath /data/db --smallfiles --nojournal docker run -d -p 5672:5672 -p 15672:15672 --name=rabbitmq rabbitmq:3-management docker run -d -p 6379:6379 --name=redis redis docker run -d -p 5432:5432 --name=postgres koding/postgres docker run -d -p 18081-18110:8081-8110 -p 18200:8200 -p 19095:9095 --name=imply imply/imply:1.2.1 restoredefaultmongodump echo "#---> CLEARING ALGOLIA INDEXES: @chris <---#" pushd $KONFIG_PROJECTROOT ./scripts/clear-algolia-index.sh -i "accounts$KONFIG_SOCIALAPI_ALGOLIA_INDEXSUFFIX" ./scripts/clear-algolia-index.sh -i "topics$KONFIG_SOCIALAPI_ALGOLIA_INDEXSUFFIX" ./scripts/clear-algolia-index.sh -i "messages$KONFIG_SOCIALAPI_ALGOLIA_INDEXSUFFIX" migrate up } function services () { if [[ `uname` == 'Darwin' ]]; then boot2docker up fi EXISTS=$(docker inspect --format="{{ .State.Running }}" $SERVICES 2> /dev/null) if [ $? -eq 1 ]; then echo "" echo "Some of containers are missing, please do ./run buildservices" exit 1 fi echo "Stopping services: $SERVICES" docker stop $SERVICES echo "Starting services: $SERVICES" docker start $SERVICES nginxrun } function importusers () { node $KONFIG_PROJECTROOT/scripts/user-importer -c dev migrateusers } function migrateusers () { echo '#---> UPDATING MONGO DB TO WORK WITH SOCIALAPI @cihangir <---#' mongo $KONFIG_MONGO --eval='db.jAccounts.update({},{$unset:{socialApiId:0}},{multi:true}); db.jGroups.update({},{$unset:{socialApiChannelId:0}},{multi:true});' go run $KONFIG_PROJECTROOT/go/src/socialapi/workers/cmd/migrator/main.go -c $KONFIG_SOCIALAPI_CONFIGFILEPATH # Required step for guestuser mongo $KONFIG_MONGO --eval='db.jAccounts.update({"profile.nickname":"guestuser"},{$set:{type:"unregistered", socialApiId:0}});' } function restoredefaultmongodump () { echo '#---> CREATING VANILLA KODING DB @gokmen <---#' mongo $KONFIG_MONGO --eval "db.dropDatabase()" pushd $KONFIG_PROJECTROOT/install/docker-mongo if [[ -f $KONFIG_PROJECTROOT/install/docker-mongo/custom-db-dump.tar.bz2 ]]; then tar jxvf $KONFIG_PROJECTROOT/install/docker-mongo/custom-db-dump.tar.bz2 else tar jxvf $KONFIG_PROJECTROOT/install/docker-mongo/default-db-dump.tar.bz2 fi read HOST _ DB <<<"$(echo $KONFIG_MONGO | awk -F '[:/]' '{ print $1, $2, $3}')" mongorestore --host $HOST --db $DB dump/koding rm -rf ./dump updatePermissions } function updatePermissions () { echo '#---> UPDATING MONGO DATABASE ACCORDING TO LATEST CHANGES IN CODE (UPDATE PERMISSIONS @gokmen) <---#' node $KONFIG_PROJECTROOT/scripts/permission-updater -c dev --reset } function updateusers () { node $KONFIG_PROJECTROOT/scripts/user-updater } function create_default_workspace () { node $KONFIG_PROJECTROOT/scripts/create-default-workspace } function cleanchatnotifications () { $GOBIN/notification -c $KONFIG_SOCIALAPI_CONFIGFILEPATH -h } if [ "$#" == "0" ]; then checkrunfile run $1 elif [ "$1" == "docker-compose" ]; then shift docker_compose elif [ "$1" == "exec" ]; then shift exec "$@" elif [ "$1" == "install" ]; then check_service_dependencies #{installScript} elif [ "$1" == "printconfig" ]; then printconfig $@ elif [[ "$1" == "log" || "$1" == "logs" ]]; then trap - INT trap if [ "$2" == "" ]; then tail -fq ./.logs/*.log else tail -fq ./.logs/$2.log fi elif [ "$1" == "cleanup" ]; then ./cleanup $@ elif [ "$1" == "buildclient" ]; then make -C $KONFIG_PROJECTROOT/client dist elif [ "$1" == "services" ]; then check_service_dependencies services elif [ "$1" == "updatepermissions" ]; then updatePermissions elif [ "$1" == "resetdb" ]; then if [ "$2" == "--yes" ]; then env PGPASSWORD=social_superuser psql -tA -h $KONFIG_POSTGRES_HOST $KONFIG_POSTGRES_DBNAME -U social_superuser -c "DELETE FROM \"api\".\"channel_participant\"; DELETE FROM \"api\".\"channel\";DELETE FROM \"api\".\"account\";" restoredefaultmongodump migrateusers exit 0 fi read -p "This will reset current databases, all data will be lost! (y/N)" -n 1 -r echo "" if [[ ! $REPLY =~ ^[Yy]$ ]] then exit 1 fi env PGPASSWORD=social_superuser psql -tA -h $KONFIG_POSTGRES_HOST $KONFIG_POSTGRES_DBNAME -U social_superuser -c "DELETE FROM \"api\".\"channel_participant\"; DELETE FROM \"api\".\"channel\";DELETE FROM \"api\".\"account\";" restoredefaultmongodump migrateusers elif [ "$1" == "buildservices" ]; then check_service_dependencies if [ "$2" != "force" ]; then read -p "This will destroy existing images, do you want to continue? (y/N)" -n 1 -r echo "" if [[ ! $REPLY =~ ^[Yy]$ ]]; then exit 1 fi fi build_services migrate up elif [ "$1" == "help" ]; then printHelp elif [ "$1" == "importusers" ]; then importusers elif [ "$1" == "updateusers" ]; then updateusers elif [ "$1" == "create_default_workspace" ]; then create_default_workspace elif [ "$1" == "cleanchatnotifications" ]; then cleanchatnotifications elif [ "$1" == "worker" ]; then if [ "$2" == "" ]; then echo Available workers: echo "-------------------" supervisorctl status | awk '${print $1} | sort' else trap - INT trap exec supervisorctl start $2 fi elif [ "$1" == "migrate" ]; then check_psql if [ -z "$2" ]; then echo "Please choose a migrate command [create|up|down|version|reset|redo|to|goto]" echo "" else pushd $GOPATH/src/socialapi make install-migrate migrate $2 $3 fi elif [ "$1" == "vmwatchertests" ]; then go test koding/vmwatcher -test.v=true elif [ "$1" == "janitortests" ]; then pushd $KONFIG_PROJECTROOT/go/src/koding/workers/janitor ./test.sh elif [ "$1" == "gatheringestortests" ]; then go test koding/workers/gatheringestor -test.v=true elif [ "$1" == "gomodeltests" ]; then go test koding/db/mongodb/modelhelper -test.v=true elif [ "$1" == "socialworkertests" ]; then $KONFIG_PROJECTROOT/scripts/node-testing/mocha-runner "$KONFIG_PROJECTROOT/workers/social" elif [ "$1" == "nodeservertests" ]; then $KONFIG_PROJECTROOT/scripts/node-testing/mocha-runner "$KONFIG_PROJECTROOT/servers/lib/server" # To run specific test directory or a single test file elif [ "$1" == "nodetestfiles" ]; then $KONFIG_PROJECTROOT/scripts/node-testing/mocha-runner $2 elif [ "$1" == "sanitize-email" ]; then node $KONFIG_PROJECTROOT/scripts/sanitize-email elif [ "$1" == "migrations" ]; then migrations else echo "Unknown command: $1" printHelp fi # ------ THIS FILE IS AUTO-GENERATED BY ./configure ----- #\n """ return run generateSandbox = generateRunFile = (KONFIG) -> return """ #!/bin/bash export HOME=/home/ec2-user ENV_SHELL_FILE=${ENV_SHELL_FILE:-$(dirname $0)/.env.sh} if [ -f "$ENV_SHELL_FILE" ]; then source $ENV_SHELL_FILE else echo "error: shell environment file does not exist" exit 1 fi COMMAND=$1 shift case "$COMMAND" in exec) exec "$@";; esac """ module.exports = { dev: generateDev, default: generateDev, sandbox: generateSandbox, prod: generateSandbox }
true
traverse = require 'traverse' log = console.log fs = require 'fs' os = require 'os' path = require 'path' { isAllowed } = require '../deployment/grouptoenvmapping' generateDev = (KONFIG, options) -> options.requirementCommands ?= [] installScript = """ pushd $KONFIG_PROJECTROOT git submodule update --init npm install --unsafe-perm echo '#---> BUILDING CLIENT <---#' make -C $KONFIG_PROJECTROOT/client unit-tests echo '#---> BUILDING GO WORKERS (@farslan) <---#' $KONFIG_PROJECTROOT/go/build.sh echo '#---> BUILDING SOCIALAPI (@cihangir) <---#' pushd $KONFIG_PROJECTROOT/go/src/socialapi make configure # make install cleanchatnotifications echo '#---> AUTHORIZING THIS COMPUTER WITH MATCHING KITE.KEY (@farslan) <---#' KITE_KEY=$KONFIG_KITEHOME/kite.key mkdir $HOME/.kite &>/dev/null echo copying $KITE_KEY to $HOME/.kite/kite.key cp -f $KITE_KEY $HOME/.kite/kite.key echo echo echo 'ALL DONE. Enjoy! :)' echo echo """ run = """ #!/bin/bash # ------ THIS FILE IS AUTO-GENERATED ON EACH BUILD ----- # export KONFIG_PROJECTROOT=$(cd $(dirname $0); pwd) ENV_SHELL_FILE=${ENV_SHELL_FILE:-$(dirname $0)/.env.sh} if [ -f "$ENV_SHELL_FILE" ]; then source $ENV_SHELL_FILE else echo "error: shell environment file does not exist" exit 1 fi mkdir $KONFIG_PROJECTROOT/.logs &>/dev/null SERVICES="mongo redis postgres rabbitmq imply" NGINX_CONF="$KONFIG_PROJECTROOT/nginx.conf" NGINX_PID="$KONFIG_PROJECTROOT/nginx.pid" #{options.requirementCommands?.join "\n"} trap ctrl_c INT function ctrl_c () { supervisorctl shutdown } function nginxstop () { if [ -a $NGINX_PID ]; then echo "stopping nginx" nginx -c $NGINX_CONF -g "pid $NGINX_PID;" -s quit fi } function nginxrun () { nginxstop echo "starting nginx" nginx -c $NGINX_CONF -g "pid $NGINX_PID;" } function checkrunfile () { if [ "$KONFIG_PROJECTROOT/run" -ot "$KONFIG_PROJECTROOT/config/main.$KONFIG_CONFIGNAME.coffee" ]; then echo your run file is older than your config file. doing ./configure. sleep 1 ./configure echo -e "\n\nPlease do ./run again\n" exit 1; fi if [ "$KONFIG_PROJECTROOT/run" -ot "$KONFIG_PROJECTROOT/configure" ]; then echo your run file is older than your configure file. doing ./configure. sleep 1 ./configure echo -e "\n\nPlease do ./run again\n" exit 1; fi } function migrations () { # a temporary migration line (do we still need this?) export PGPASSWORD=$KONFIG_PI:PASSWORD:<PASSWORD>END_PI_PASSWORD PSQL_COMMAND="psql -tA -h $KONFIG_POSTGRES_HOST $KONFIG_POSTGRES_DBNAME -U $KONFIG_POSTGRES_USERNAME" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_type_constant_enum\" ADD VALUE IF NOT EXISTS 'collaboration';" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_participant_status_constant_enum\" ADD VALUE IF NOT EXISTS 'blocked';" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_type_constant_enum\" ADD VALUE IF NOT EXISTS 'linkedtopic';" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_type_constant_enum\" ADD VALUE IF NOT EXISTS 'bot';" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_message_type_constant_enum\" ADD VALUE IF NOT EXISTS 'bot';" $PSQL_COMMAND -c "ALTER TYPE \"api\".\"channel_message_type_constant_enum\" ADD VALUE IF NOT EXISTS 'system';" $PSQL_COMMAND -c "ALTER TYPE \"payment\".\"plan_title_enum\" ADD VALUE IF NOT EXISTS 'bootstrap';" $PSQL_COMMAND -c "ALTER TYPE \"payment\".\"plan_title_enum\" ADD VALUE IF NOT EXISTS 'startup';" $PSQL_COMMAND -c "ALTER TYPE \"payment\".\"plan_title_enum\" ADD VALUE IF NOT EXISTS 'enterprise';" $PSQL_COMMAND -c "ALTER TYPE \"payment\".\"plan_title_enum\" ADD VALUE IF NOT EXISTS 'team_base';" $PSQL_COMMAND -c "ALTER TYPE \"payment\".\"plan_title_enum\" ADD VALUE IF NOT EXISTS 'team_free';" } function run () { # Check if PG DB schema update required go run $KONFIG_PROJECTROOT/go/src/socialapi/tests/pg-update.go $KONFIG_POSTGRES_HOST $KONFIG_POSTGRES_PORT RESULT=$? if [ $RESULT -ne 0 ]; then exit 1 fi # Update node modules if ! scripts/check-node_modules.sh; then npm install --silent fi # Check everything else check # Remove old watcher files (do we still need this?) rm -rf $KONFIG_PROJECTROOT/go/bin/goldorf-main-* rm -rf $KONFIG_PROJECTROOT/go/bin/watcher-* # Run Go builder $KONFIG_PROJECTROOT/go/build.sh # Run Social Api builder make -C $KONFIG_PROJECTROOT/go/src/socialapi configure # Do PG Migration if necessary migrate up # Create default workspaces node scripts/create-default-workspace # Sanitize email addresses node $KONFIG_PROJECTROOT/scripts/sanitize-email supervisord && sleep 1 # Show the all logs of workers tail -fq ./.logs/*.log } function docker_compose() { if ! which docker-compose; then echo 'error: docker-compose is not found' echo '$ pip install docker-compose' exit 1 fi local ENTRYPOINT="/opt/koding/scripts/bootstrap-container $@" docker-compose run --entrypoint $ENTRYPOINT backend } function printHelp (){ echo "Usage: " echo "" echo " run : to start koding" echo " run docker-compose : to start koding in docker-compose environment" echo " run exec : to exec arbitrary commands" echo " run install : to compile/install client and " echo " run buildclient : to see of specified worker logs only" echo " run logs : to see all workers logs" echo " run log [worker] : to see of specified worker logs only" echo " run buildservices : to initialize and start services" echo " run resetdb : to reset databases" echo " run services : to stop and restart services" echo " run worker : to list workers" echo " run printconfig : to print koding config environment variables (output in json via --json flag)" echo " run worker [worker] : to run a single worker" echo " run migrate [command] : to apply/revert database changes (command: [create|up|down|version|reset|redo|to|goto])" echo " run importusers : to import koding user data" echo " run nodeservertests : to run tests for node.js web server" echo " run socialworkertests : to run tests for social worker" echo " run nodetestfiles : to run a single test or all test files in a directory" echo " run sanitize-email : to sanitize email" echo " run help : to show this list" echo "" } function migrate () { migrations params=(create up down version reset redo to goto) param=$1 case "${params[@]}" in *"$param"*) ;; *) echo "Error: Command not found: $param" echo "Usage: run migrate COMMAND [arg]" echo "" echo "Commands: " echo " create [filename] : create new migration file in path" echo " up : apply all available migrations" echo " down : roll back all migrations" echo " redo : roll back the most recently applied migration, then run it again" echo " reset : run down and then up command" echo " version : show the current migration version" echo " to [n] : (+n) apply the next n / (-n) roll back the previous n migrations" echo " goto [n] : go to specific migration" echo "" exit 1 ;; esac if [ "$param" == "to" ]; then param="migrate" elif [ "$param" == "create" ] && [ -z "$2" ]; then echo "Please choose a migration file name. (ex. add_created_at_column_account)" echo "Usage: run migrate create [filename]" echo "" exit 1 fi $GOBIN/migrate -url "postgres://$KONFIG_POSTGRES_HOST:$KONFIG_POSTGRES_PORT/$KONFIG_POSTGRES_DBNAME?user=social_superuser&password=PI:PASSWORD:<PASSWORD>END_PI" -path "$KONFIG_PROJECTROOT/go/src/socialapi/db/sql/migrations" $param $2 if [ "$param" == "create" ]; then echo "Please edit created script files and add them to your repository." fi } function check (){ check_service_dependencies if [[ `uname` == 'Darwin' ]]; then if [ -z "$DOCKER_HOST" ]; then echo "You need to export DOCKER_HOST, run 'boot2docker up' and follow the instructions." exit 1 fi fi mongo $KONFIG_MONGO --eval "db.stats()" > /dev/null # do a simple harmless command of some sort RESULT=$? # returns 0 if mongo eval succeeds if [ $RESULT -ne 0 ]; then echo "" echo "Can't talk to mongodb at $KONFIG_MONGO, is it not running? exiting." exit 1 fi EXISTS=$(PGPASSWORD=$KONFIG_POSTGRES_PASSWORD psql -tA -h $KONFIG_POSTGRES_HOST social -U $KONFIG_POSTGRES_USERNAME -c "Select 1 from pg_tables where tablename = 'key' AND schemaname = 'kite';") if [[ $EXISTS != '1' ]]; then echo "" echo "You don't have the new Kontrol Postgres. Please call ./run buildservices." exit 1 fi } function check_psql () { command -v psql >/dev/null 2>&1 || { echo >&2 "I require psql but it's not installed. (brew install postgresql) Aborting."; exit 1; } } function check_service_dependencies () { echo "checking required services: nginx, docker, mongo, graphicsmagick..." command -v go >/dev/null 2>&1 || { echo >&2 "I require go but it's not installed. Aborting."; exit 1; } command -v docker >/dev/null 2>&1 || { echo >&2 "I require docker but it's not installed. Aborting."; exit 1; } command -v nginx >/dev/null 2>&1 || { echo >&2 "I require nginx but it's not installed. (brew install nginx maybe?) Aborting."; exit 1; } command -v mongorestore >/dev/null 2>&1 || { echo >&2 "I require mongorestore but it's not installed. Aborting."; exit 1; } command -v node >/dev/null 2>&1 || { echo >&2 "I require node but it's not installed. Aborting."; exit 1; } command -v npm >/dev/null 2>&1 || { echo >&2 "I require npm but it's not installed. Aborting."; exit 1; } command -v gulp >/dev/null 2>&1 || { echo >&2 "I require gulp but it's not installed. (npm i gulp -g) Aborting."; exit 1; } # command -v stylus >/dev/null 2>&1 || { echo >&2 "I require stylus but it's not installed. (npm i stylus -g) Aborting."; exit 1; } command -v coffee >/dev/null 2>&1 || { echo >&2 "I require coffee-script but it's not installed. (npm i coffee-script -g) Aborting."; exit 1; } check_psql if [[ `uname` == 'Darwin' ]]; then brew info graphicsmagick >/dev/null 2>&1 || { echo >&2 "I require graphicsmagick but it's not installed. Aborting."; exit 1; } command -v boot2docker >/dev/null 2>&1 || { echo >&2 "I require boot2docker but it's not installed. Aborting."; exit 1; } elif [[ `uname` == 'Linux' ]]; then command -v gm >/dev/null 2>&1 || { echo >&2 "I require graphicsmagick but it's not installed. Aborting."; exit 1; } fi set -o errexit scripts/check-node-version.sh scripts/check-npm-version.sh scripts/check-gulp-version.sh scripts/check-go-version.sh scripts/check-supervisor.sh set +o errexit } function build_services () { if [[ `uname` == 'Darwin' ]]; then boot2docker up fi echo "Stopping services: $SERVICES" docker stop $SERVICES echo "Removing services: $SERVICES" docker rm $SERVICES # Build Mongo service pushd $KONFIG_PROJECTROOT/install/docker-mongo docker build -t koding/mongo . # Build postgres pushd $KONFIG_PROJECTROOT/go/src/socialapi/db/sql # Include this to dockerfile before we continute with building mkdir -p kontrol cp $KONFIG_PROJECTROOT/go/src/github.com/koding/kite/kontrol/*.sql kontrol/ sed -i -e "s/somerandompassword/$KONFIG_KONTROL_POSTGRES_PASSWORD/" kontrol/001-schema.sql sed -i -e "s/kontrolapplication/$KONFIG_KONTROL_POSTGRES_USERNAME/" kontrol/001-schema.sql docker build -t koding/postgres . docker run -d -p 27017:27017 --name=mongo koding/mongo --dbpath /data/db --smallfiles --nojournal docker run -d -p 5672:5672 -p 15672:15672 --name=rabbitmq rabbitmq:3-management docker run -d -p 6379:6379 --name=redis redis docker run -d -p 5432:5432 --name=postgres koding/postgres docker run -d -p 18081-18110:8081-8110 -p 18200:8200 -p 19095:9095 --name=imply imply/imply:1.2.1 restoredefaultmongodump echo "#---> CLEARING ALGOLIA INDEXES: @chris <---#" pushd $KONFIG_PROJECTROOT ./scripts/clear-algolia-index.sh -i "accounts$KONFIG_SOCIALAPI_ALGOLIA_INDEXSUFFIX" ./scripts/clear-algolia-index.sh -i "topics$KONFIG_SOCIALAPI_ALGOLIA_INDEXSUFFIX" ./scripts/clear-algolia-index.sh -i "messages$KONFIG_SOCIALAPI_ALGOLIA_INDEXSUFFIX" migrate up } function services () { if [[ `uname` == 'Darwin' ]]; then boot2docker up fi EXISTS=$(docker inspect --format="{{ .State.Running }}" $SERVICES 2> /dev/null) if [ $? -eq 1 ]; then echo "" echo "Some of containers are missing, please do ./run buildservices" exit 1 fi echo "Stopping services: $SERVICES" docker stop $SERVICES echo "Starting services: $SERVICES" docker start $SERVICES nginxrun } function importusers () { node $KONFIG_PROJECTROOT/scripts/user-importer -c dev migrateusers } function migrateusers () { echo '#---> UPDATING MONGO DB TO WORK WITH SOCIALAPI @cihangir <---#' mongo $KONFIG_MONGO --eval='db.jAccounts.update({},{$unset:{socialApiId:0}},{multi:true}); db.jGroups.update({},{$unset:{socialApiChannelId:0}},{multi:true});' go run $KONFIG_PROJECTROOT/go/src/socialapi/workers/cmd/migrator/main.go -c $KONFIG_SOCIALAPI_CONFIGFILEPATH # Required step for guestuser mongo $KONFIG_MONGO --eval='db.jAccounts.update({"profile.nickname":"guestuser"},{$set:{type:"unregistered", socialApiId:0}});' } function restoredefaultmongodump () { echo '#---> CREATING VANILLA KODING DB @gokmen <---#' mongo $KONFIG_MONGO --eval "db.dropDatabase()" pushd $KONFIG_PROJECTROOT/install/docker-mongo if [[ -f $KONFIG_PROJECTROOT/install/docker-mongo/custom-db-dump.tar.bz2 ]]; then tar jxvf $KONFIG_PROJECTROOT/install/docker-mongo/custom-db-dump.tar.bz2 else tar jxvf $KONFIG_PROJECTROOT/install/docker-mongo/default-db-dump.tar.bz2 fi read HOST _ DB <<<"$(echo $KONFIG_MONGO | awk -F '[:/]' '{ print $1, $2, $3}')" mongorestore --host $HOST --db $DB dump/koding rm -rf ./dump updatePermissions } function updatePermissions () { echo '#---> UPDATING MONGO DATABASE ACCORDING TO LATEST CHANGES IN CODE (UPDATE PERMISSIONS @gokmen) <---#' node $KONFIG_PROJECTROOT/scripts/permission-updater -c dev --reset } function updateusers () { node $KONFIG_PROJECTROOT/scripts/user-updater } function create_default_workspace () { node $KONFIG_PROJECTROOT/scripts/create-default-workspace } function cleanchatnotifications () { $GOBIN/notification -c $KONFIG_SOCIALAPI_CONFIGFILEPATH -h } if [ "$#" == "0" ]; then checkrunfile run $1 elif [ "$1" == "docker-compose" ]; then shift docker_compose elif [ "$1" == "exec" ]; then shift exec "$@" elif [ "$1" == "install" ]; then check_service_dependencies #{installScript} elif [ "$1" == "printconfig" ]; then printconfig $@ elif [[ "$1" == "log" || "$1" == "logs" ]]; then trap - INT trap if [ "$2" == "" ]; then tail -fq ./.logs/*.log else tail -fq ./.logs/$2.log fi elif [ "$1" == "cleanup" ]; then ./cleanup $@ elif [ "$1" == "buildclient" ]; then make -C $KONFIG_PROJECTROOT/client dist elif [ "$1" == "services" ]; then check_service_dependencies services elif [ "$1" == "updatepermissions" ]; then updatePermissions elif [ "$1" == "resetdb" ]; then if [ "$2" == "--yes" ]; then env PGPASSWORD=social_superuser psql -tA -h $KONFIG_POSTGRES_HOST $KONFIG_POSTGRES_DBNAME -U social_superuser -c "DELETE FROM \"api\".\"channel_participant\"; DELETE FROM \"api\".\"channel\";DELETE FROM \"api\".\"account\";" restoredefaultmongodump migrateusers exit 0 fi read -p "This will reset current databases, all data will be lost! (y/N)" -n 1 -r echo "" if [[ ! $REPLY =~ ^[Yy]$ ]] then exit 1 fi env PGPASSWORD=social_superuser psql -tA -h $KONFIG_POSTGRES_HOST $KONFIG_POSTGRES_DBNAME -U social_superuser -c "DELETE FROM \"api\".\"channel_participant\"; DELETE FROM \"api\".\"channel\";DELETE FROM \"api\".\"account\";" restoredefaultmongodump migrateusers elif [ "$1" == "buildservices" ]; then check_service_dependencies if [ "$2" != "force" ]; then read -p "This will destroy existing images, do you want to continue? (y/N)" -n 1 -r echo "" if [[ ! $REPLY =~ ^[Yy]$ ]]; then exit 1 fi fi build_services migrate up elif [ "$1" == "help" ]; then printHelp elif [ "$1" == "importusers" ]; then importusers elif [ "$1" == "updateusers" ]; then updateusers elif [ "$1" == "create_default_workspace" ]; then create_default_workspace elif [ "$1" == "cleanchatnotifications" ]; then cleanchatnotifications elif [ "$1" == "worker" ]; then if [ "$2" == "" ]; then echo Available workers: echo "-------------------" supervisorctl status | awk '${print $1} | sort' else trap - INT trap exec supervisorctl start $2 fi elif [ "$1" == "migrate" ]; then check_psql if [ -z "$2" ]; then echo "Please choose a migrate command [create|up|down|version|reset|redo|to|goto]" echo "" else pushd $GOPATH/src/socialapi make install-migrate migrate $2 $3 fi elif [ "$1" == "vmwatchertests" ]; then go test koding/vmwatcher -test.v=true elif [ "$1" == "janitortests" ]; then pushd $KONFIG_PROJECTROOT/go/src/koding/workers/janitor ./test.sh elif [ "$1" == "gatheringestortests" ]; then go test koding/workers/gatheringestor -test.v=true elif [ "$1" == "gomodeltests" ]; then go test koding/db/mongodb/modelhelper -test.v=true elif [ "$1" == "socialworkertests" ]; then $KONFIG_PROJECTROOT/scripts/node-testing/mocha-runner "$KONFIG_PROJECTROOT/workers/social" elif [ "$1" == "nodeservertests" ]; then $KONFIG_PROJECTROOT/scripts/node-testing/mocha-runner "$KONFIG_PROJECTROOT/servers/lib/server" # To run specific test directory or a single test file elif [ "$1" == "nodetestfiles" ]; then $KONFIG_PROJECTROOT/scripts/node-testing/mocha-runner $2 elif [ "$1" == "sanitize-email" ]; then node $KONFIG_PROJECTROOT/scripts/sanitize-email elif [ "$1" == "migrations" ]; then migrations else echo "Unknown command: $1" printHelp fi # ------ THIS FILE IS AUTO-GENERATED BY ./configure ----- #\n """ return run generateSandbox = generateRunFile = (KONFIG) -> return """ #!/bin/bash export HOME=/home/ec2-user ENV_SHELL_FILE=${ENV_SHELL_FILE:-$(dirname $0)/.env.sh} if [ -f "$ENV_SHELL_FILE" ]; then source $ENV_SHELL_FILE else echo "error: shell environment file does not exist" exit 1 fi COMMAND=$1 shift case "$COMMAND" in exec) exec "$@";; esac """ module.exports = { dev: generateDev, default: generateDev, sandbox: generateSandbox, prod: generateSandbox }
[ { "context": " <div className='user'>John Smith</div>\n </div>\n ", "end": 376, "score": 0.999610424041748, "start": 366, "tag": "NAME", "value": "John Smith" }, { "context": " <div className='user'>Frank Castle</div>\n </div>\n ", "end": 728, "score": 0.9996470212936401, "start": 716, "tag": "NAME", "value": "Frank Castle" }, { "context": " <div className='user'>John Smith</div>\n </div>\n ", "end": 1078, "score": 0.9995137453079224, "start": 1068, "tag": "NAME", "value": "John Smith" }, { "context": " <div className='user'>Billy Batson</div>\n </div>\n ", "end": 1430, "score": 0.995464563369751, "start": 1418, "tag": "NAME", "value": "Billy Batson" }, { "context": " <div className='user'>Luke Cage</div>\n </div>\n ", "end": 1779, "score": 0.9993745684623718, "start": 1770, "tag": "NAME", "value": "Luke Cage" }, { "context": " <div className='user'>Billy Batson</div>\n </div>\n ", "end": 2132, "score": 0.9981162548065186, "start": 2120, "tag": "NAME", "value": "Billy Batson" }, { "context": " <div className='user'>Luke Cage</div>\n </div>\n ", "end": 2477, "score": 0.9994296431541443, "start": 2473, "tag": "NAME", "value": "Luke" } ]
public/scripts/example/ActivityExample.cjsx
SolinkCorp/velocity-dashboard
0
React = require 'react' chartColors = require('./ChartStyles').colors module.exports = Content: -> <div> <div className='widgetBody activity-feed'> <ul> <li> <div> <div className='time'>8 min ago</div> <div className='user'>John Smith</div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300004</a></div> </li> <li> <div> <div className='time'>10 min ago</div> <div className='user'>Frank Castle</div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300003</a></div> </li> <li> <div> <div className='time'>14 min ago</div> <div className='user'>John Smith</div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300036</a></div> </li> <li> <div> <div className='time'>20 min ago</div> <div className='user'>Billy Batson</div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300054</a></div> </li> <li> <div> <div className='time'>1 hour ago</div> <div className='user'>Luke Cage</div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300097</a></div> </li> <li> <div> <div className='time'>3 hours ago</div> <div className='user'>Billy Batson</div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300054</a></div> </li> <li> <div> <div className='time'>6 hours ago</div> <div className='user'>Luke Cage</div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300097</a></div> </li> </ul> </div> </div>
107021
React = require 'react' chartColors = require('./ChartStyles').colors module.exports = Content: -> <div> <div className='widgetBody activity-feed'> <ul> <li> <div> <div className='time'>8 min ago</div> <div className='user'><NAME></div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300004</a></div> </li> <li> <div> <div className='time'>10 min ago</div> <div className='user'><NAME></div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300003</a></div> </li> <li> <div> <div className='time'>14 min ago</div> <div className='user'><NAME></div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300036</a></div> </li> <li> <div> <div className='time'>20 min ago</div> <div className='user'><NAME></div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300054</a></div> </li> <li> <div> <div className='time'>1 hour ago</div> <div className='user'><NAME></div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300097</a></div> </li> <li> <div> <div className='time'>3 hours ago</div> <div className='user'><NAME></div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300054</a></div> </li> <li> <div> <div className='time'>6 hours ago</div> <div className='user'><NAME> Cage</div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300097</a></div> </li> </ul> </div> </div>
true
React = require 'react' chartColors = require('./ChartStyles').colors module.exports = Content: -> <div> <div className='widgetBody activity-feed'> <ul> <li> <div> <div className='time'>8 min ago</div> <div className='user'>PI:NAME:<NAME>END_PI</div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300004</a></div> </li> <li> <div> <div className='time'>10 min ago</div> <div className='user'>PI:NAME:<NAME>END_PI</div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300003</a></div> </li> <li> <div> <div className='time'>14 min ago</div> <div className='user'>PI:NAME:<NAME>END_PI</div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300036</a></div> </li> <li> <div> <div className='time'>20 min ago</div> <div className='user'>PI:NAME:<NAME>END_PI</div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300054</a></div> </li> <li> <div> <div className='time'>1 hour ago</div> <div className='user'>PI:NAME:<NAME>END_PI</div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300097</a></div> </li> <li> <div> <div className='time'>3 hours ago</div> <div className='user'>PI:NAME:<NAME>END_PI</div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300054</a></div> </li> <li> <div> <div className='time'>6 hours ago</div> <div className='user'>PI:NAME:<NAME>END_PI Cage</div> </div> <div className='activity'>Received Shipment - <a href='#'>SH12300097</a></div> </li> </ul> </div> </div>
[ { "context": ":'\n \n create: (user_id, callback) ->\n key = crypto.randomBytes(16).toString('hex')\n \n @client.setex @prefix + key, 60, user_", "end": 279, "score": 0.9434216022491455, "start": 243, "tag": "KEY", "value": "crypto.randomBytes(16).toString('hex" } ]
lib/ticket_stores/redis.coffee
mattinsler/keyless
1
crypto = require 'crypto' redis_builder = require 'redis-builder' class RedisTicketStore constructor: (opts = {}) -> @client = redis_builder(opts) @prefix = opts.prefix ? 'keyless-t:' create: (user_id, callback) -> key = crypto.randomBytes(16).toString('hex') @client.setex @prefix + key, 60, user_id, (err) -> return callback(err) if err? callback(null, key) get: (ticket, callback) -> @client.multi() .get(@prefix + ticket, callback) .del(@prefix + ticket) .exec() module.exports = (opts) -> new RedisTicketStore(opts)
9962
crypto = require 'crypto' redis_builder = require 'redis-builder' class RedisTicketStore constructor: (opts = {}) -> @client = redis_builder(opts) @prefix = opts.prefix ? 'keyless-t:' create: (user_id, callback) -> key = <KEY>') @client.setex @prefix + key, 60, user_id, (err) -> return callback(err) if err? callback(null, key) get: (ticket, callback) -> @client.multi() .get(@prefix + ticket, callback) .del(@prefix + ticket) .exec() module.exports = (opts) -> new RedisTicketStore(opts)
true
crypto = require 'crypto' redis_builder = require 'redis-builder' class RedisTicketStore constructor: (opts = {}) -> @client = redis_builder(opts) @prefix = opts.prefix ? 'keyless-t:' create: (user_id, callback) -> key = PI:KEY:<KEY>END_PI') @client.setex @prefix + key, 60, user_id, (err) -> return callback(err) if err? callback(null, key) get: (ticket, callback) -> @client.multi() .get(@prefix + ticket, callback) .del(@prefix + ticket) .exec() module.exports = (opts) -> new RedisTicketStore(opts)
[ { "context": "param + \" \" + this.name)\n \"name\": \"bob\"\n }\n stream = Bacon.fromNodeC", "end": 2670, "score": 0.9229888319969177, "start": 2667, "tag": "NAME", "value": "bob" }, { "context": "fromNodeCallback(src, \"go\", \"hello\")\n [\"hello bob\"])\n it \"toString\", ->\n expect(Bacon.fromNodeC", "end": 2765, "score": 0.8037636280059814, "start": 2762, "tag": "NAME", "value": "bob" } ]
spec/specs/callback.coffee
ArtFacts/bacon.js
0
{ expectStreamTimings, series, semiunstable } = require("../SpecHelper") require("../../src/callback") require("../../src/constant") Bacon = require("../../src/core").default expect = require("chai").expect { expectStreamEvents, series, semiunstable, error } = require("../SpecHelper") testLiftedCallback = (src, liftedCallback) -> input = [ Bacon.constant('a') 'x' Bacon.constant('b').toProperty() 'y' ] output = ['a', 'x', 'b', 'y'] expectStreamEvents( -> liftedCallback(src, input...) [output] ) describe "Bacon.fromCallback", -> describe "makes an EventStream from function that takes a callback", -> expectStreamEvents( -> src = (callback) -> callback("lol") stream = Bacon.fromCallback(src) ["lol"]) describe "supports partial application", -> expectStreamEvents( -> src = (param, callback) -> callback(param) stream = Bacon.fromCallback(src, "lol") ["lol"]) describe "supports partial application with Observable arguments", -> testLiftedCallback( (values..., callback) -> callback(values) Bacon.fromCallback ) describe "supports object, methodName, partial application", -> expectStreamEvents( -> src = { "go": (param, callback) -> callback(param + " " + this.name) "name": "bob" } stream = Bacon.fromCallback(src, "go", "hello") ["hello bob"]) it "toString", -> expect(Bacon.fromCallback((->), "lol").toString()).to.equal("Bacon.fromCallback(function,lol)") describe "Bacon.fromNodeCallback", -> describe "makes an EventStream from function that takes a node-style callback", -> expectStreamEvents( -> src = (callback) -> callback(null, "lol") stream = Bacon.fromNodeCallback(src) ["lol"]) describe "handles error parameter correctly", -> expectStreamEvents( -> src = (callback) -> callback('errortxt', null) stream = Bacon.fromNodeCallback(src) [error()]) describe "supports partial application", -> expectStreamEvents( -> src = (param, callback) -> callback(null, param) stream = Bacon.fromNodeCallback(src, "lol") ["lol"]) describe "supports partial application with Observable arguments", -> testLiftedCallback( (values..., callback) -> callback(null, values) Bacon.fromNodeCallback ) describe "supports object, methodName, partial application", -> expectStreamEvents( -> src = { "go": (param, callback) -> callback(null, param + " " + this.name) "name": "bob" } stream = Bacon.fromNodeCallback(src, "go", "hello") ["hello bob"]) it "toString", -> expect(Bacon.fromNodeCallback((->), "lol").toString()).to.equal("Bacon.fromNodeCallback(function,lol)")
145619
{ expectStreamTimings, series, semiunstable } = require("../SpecHelper") require("../../src/callback") require("../../src/constant") Bacon = require("../../src/core").default expect = require("chai").expect { expectStreamEvents, series, semiunstable, error } = require("../SpecHelper") testLiftedCallback = (src, liftedCallback) -> input = [ Bacon.constant('a') 'x' Bacon.constant('b').toProperty() 'y' ] output = ['a', 'x', 'b', 'y'] expectStreamEvents( -> liftedCallback(src, input...) [output] ) describe "Bacon.fromCallback", -> describe "makes an EventStream from function that takes a callback", -> expectStreamEvents( -> src = (callback) -> callback("lol") stream = Bacon.fromCallback(src) ["lol"]) describe "supports partial application", -> expectStreamEvents( -> src = (param, callback) -> callback(param) stream = Bacon.fromCallback(src, "lol") ["lol"]) describe "supports partial application with Observable arguments", -> testLiftedCallback( (values..., callback) -> callback(values) Bacon.fromCallback ) describe "supports object, methodName, partial application", -> expectStreamEvents( -> src = { "go": (param, callback) -> callback(param + " " + this.name) "name": "bob" } stream = Bacon.fromCallback(src, "go", "hello") ["hello bob"]) it "toString", -> expect(Bacon.fromCallback((->), "lol").toString()).to.equal("Bacon.fromCallback(function,lol)") describe "Bacon.fromNodeCallback", -> describe "makes an EventStream from function that takes a node-style callback", -> expectStreamEvents( -> src = (callback) -> callback(null, "lol") stream = Bacon.fromNodeCallback(src) ["lol"]) describe "handles error parameter correctly", -> expectStreamEvents( -> src = (callback) -> callback('errortxt', null) stream = Bacon.fromNodeCallback(src) [error()]) describe "supports partial application", -> expectStreamEvents( -> src = (param, callback) -> callback(null, param) stream = Bacon.fromNodeCallback(src, "lol") ["lol"]) describe "supports partial application with Observable arguments", -> testLiftedCallback( (values..., callback) -> callback(null, values) Bacon.fromNodeCallback ) describe "supports object, methodName, partial application", -> expectStreamEvents( -> src = { "go": (param, callback) -> callback(null, param + " " + this.name) "name": "<NAME>" } stream = Bacon.fromNodeCallback(src, "go", "hello") ["hello <NAME>"]) it "toString", -> expect(Bacon.fromNodeCallback((->), "lol").toString()).to.equal("Bacon.fromNodeCallback(function,lol)")
true
{ expectStreamTimings, series, semiunstable } = require("../SpecHelper") require("../../src/callback") require("../../src/constant") Bacon = require("../../src/core").default expect = require("chai").expect { expectStreamEvents, series, semiunstable, error } = require("../SpecHelper") testLiftedCallback = (src, liftedCallback) -> input = [ Bacon.constant('a') 'x' Bacon.constant('b').toProperty() 'y' ] output = ['a', 'x', 'b', 'y'] expectStreamEvents( -> liftedCallback(src, input...) [output] ) describe "Bacon.fromCallback", -> describe "makes an EventStream from function that takes a callback", -> expectStreamEvents( -> src = (callback) -> callback("lol") stream = Bacon.fromCallback(src) ["lol"]) describe "supports partial application", -> expectStreamEvents( -> src = (param, callback) -> callback(param) stream = Bacon.fromCallback(src, "lol") ["lol"]) describe "supports partial application with Observable arguments", -> testLiftedCallback( (values..., callback) -> callback(values) Bacon.fromCallback ) describe "supports object, methodName, partial application", -> expectStreamEvents( -> src = { "go": (param, callback) -> callback(param + " " + this.name) "name": "bob" } stream = Bacon.fromCallback(src, "go", "hello") ["hello bob"]) it "toString", -> expect(Bacon.fromCallback((->), "lol").toString()).to.equal("Bacon.fromCallback(function,lol)") describe "Bacon.fromNodeCallback", -> describe "makes an EventStream from function that takes a node-style callback", -> expectStreamEvents( -> src = (callback) -> callback(null, "lol") stream = Bacon.fromNodeCallback(src) ["lol"]) describe "handles error parameter correctly", -> expectStreamEvents( -> src = (callback) -> callback('errortxt', null) stream = Bacon.fromNodeCallback(src) [error()]) describe "supports partial application", -> expectStreamEvents( -> src = (param, callback) -> callback(null, param) stream = Bacon.fromNodeCallback(src, "lol") ["lol"]) describe "supports partial application with Observable arguments", -> testLiftedCallback( (values..., callback) -> callback(null, values) Bacon.fromNodeCallback ) describe "supports object, methodName, partial application", -> expectStreamEvents( -> src = { "go": (param, callback) -> callback(null, param + " " + this.name) "name": "PI:NAME:<NAME>END_PI" } stream = Bacon.fromNodeCallback(src, "go", "hello") ["hello PI:NAME:<NAME>END_PI"]) it "toString", -> expect(Bacon.fromNodeCallback((->), "lol").toString()).to.equal("Bacon.fromNodeCallback(function,lol)")
[ { "context": "###\nVexTab Tests\nCopyright Mohit Cheppudira 2010 <mohit@muthanna.com>\n###\n\nimport Vex from 'v", "end": 43, "score": 0.9998795390129089, "start": 27, "tag": "NAME", "value": "Mohit Cheppudira" }, { "context": "###\nVexTab Tests\nCopyright Mohit Cheppudira 2010 <mohit@muthanna.com>\n###\n\nimport Vex from 'vexflow';\nimport Artist fr", "end": 68, "score": 0.9999285936355591, "start": 50, "tag": "EMAIL", "value": "mohit@muthanna.com" }, { "context": "-4-4h5/3\")\n\n assert.ok(true, \"all pass\")\n\n @chordTies: (assert) ->\n assert.expect 7\n tab = makePa", "end": 12308, "score": 0.8291136622428894, "start": 12301, "tag": "USERNAME", "value": "ordTies" } ]
tests/tests.coffee
ronyeh/vextab
382
### VexTab Tests Copyright Mohit Cheppudira 2010 <mohit@muthanna.com> ### import Vex from 'vexflow'; import Artist from '../src/artist.coffee'; import VexTab from '../src/vextab.coffee'; qunit = QUnit test = qunit.test console.log(test) Artist.DEBUG = false; VexTab.DEBUG = false; class VexTabTests @Start: -> qunit.module "VexTab Parser" test "Basic Test", @basic test "Complex Test", @complex test "Stave Options Test", @staveOptionsTest test "Notation Only Test", @notationOnly test "Tuning Test", @tuning test "String/Fret Test", @stringFret test "MultiFret Test", @multiFret test "Tie Test", @tie test "Bar Test", @bar test "Bend Test", @bend test "Vibrato Test", @vibrato test "Upstroke/Downstroke Test", @strokes test "Chord Test", @chord test "Tapping Test", @tapping test "Chord Ties Test", @chordTies test "Duration Test", @duration test "Triplets and Tuplets Test", @tripletsAndTuplets test "Dotted Notes Test", @dottedNotes test "Annotations Test", @annotations test "Long Bends Test", @longBends test "Rest Test", @rest test "Options Test", @options test "ABC Notes Test", @abcNotes test "ABC Notes with Frets Test", @abcNotesWithFrets test "Rhythm/Slash Notation Test", @rhythmNotation test "Text Lines", @textLines test "Sweep Strokes", @sweepStrokes test "Voices", @voices test "Fingering and String Numbers", @fingering test "Render", @render test "Render Complex", @renderComplex test "Tab Stems", @tabStems test "Rests in Tab", @restsInTab test "Multi String Tab", @multiStringTab test "Time Signature based Beaming", @timeSigBeaming test "Override Fret-Note", @overrideFretNote test "Mixed Tuplets", @mixedTuplets test "Accidental Strategies", @accidentalStrategies test "Fret-hand Fingering and String Numbers", @fingeringAndStrings # Private method catchError = (assert, tab, code, error_type="ParseError") -> error = code: "NoError" message: "Expected exception not caught" caught = false try tab.parse code catch e error = e caught = true # equal(error.code, error_type, error.message) assert.equal(true, caught) makeParser = -> new VexTab(new Artist(0, 0, 800, {scale: 0.8})) makeRenderer = (test_name)-> test_div = $('<div></div>').addClass("testcanvas") test_div.append($('<div></div>').addClass("name").text(test_name)) canvas = $('<div></div>').addClass("vex-tabdiv") test_div.append(canvas) $("body").append(test_div) renderer = new Vex.Flow.Renderer(canvas[0], Vex.Flow.Renderer.Backends.SVG) renderer.getContext().setBackgroundFillStyle("#eed") return renderer renderTest = (assert, title, code) -> tab = makeParser() renderer = makeRenderer(title) assert.notEqual null, tab.parse(code) tab.getArtist().render(renderer) assert.ok(true, "all pass") # ID counter for getRenderedContent. idcounter = 0 # Render content to a new div, and return the content. # Remove some things that change but aren't relevant (IDs) getRenderedContent = (container, code, cssflex) -> idcounter += 1 canvasid = 'rendered-' + idcounter makeCanvas = -> c = $('<div></div>').css('flex', cssflex).css('font-size', '0.8em') p = $('<p></p>').css('margin-top', '0px') p.append($('<pre></pre>').text(code).css('font-family', 'courier')) c.append(p) canvas = $('<div></div>').addClass("vex-tabdiv").attr('id', canvasid) c.append(canvas) return c renderCodeInCanvas = -> tab = new VexTab(new Artist(0, 0, 500, {scale: 0.8})) tab.parse(code) canvas = $('#' + canvasid) renderer = new Vex.Flow.Renderer(canvas[0], Vex.Flow.Renderer.Backends.SVG) renderer.getContext().setBackgroundFillStyle("#eed") tab.getArtist().render(renderer) container.append(makeCanvas()) renderCodeInCanvas() content = $('#' + canvasid). html(). replace(/id=\".*?\"/g, 'id="xxx"') return content # Ensure that the rendered content of vex1 and vex2 are equivalent. assertEquivalent = (assert, title, vex1, vex2) -> test_div = $('<div></div>').addClass("testcanvas") test_div.append($('<div></div>').addClass("name").text(title)) container = $('<div></div>').css('display', 'flex') test_div.append(container) $("body").append(test_div) oldhtml = getRenderedContent(container, vex1, '0 0 30%') newhtml = getRenderedContent(container, vex2, '1') assert.equal(oldhtml, newhtml, title) @basic: (assert) -> assert.expect 3 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n") catchError assert, tab, "tabstave\n notes /2 10/3" assert.ok true, "all pass" @complex: (assert) -> assert.expect 2 tab = makeParser() code = """ tabstave notation=true key=A notes :q (5/2.5/3.7/4) 5h6/3 7/4 | notes :8 [ t12p7p5h7/4 ] :q 7/5 :8 [ 3s5/5 ] notes :8 5-6-7v/4 (8-9-10/4.11s12/4)v tabstave notation=true notes :q (8/2.7b9b7/3) (5b6/2.5b6/3)v :8 [ 7s12/4 ] notes [ t:16:9-:8:3s:16:0/4 ] tabstave notation=true notes :q (5/4.5/5)s(7/4.7/5)s(5/4.5/5) notes :8 [ (5/4.5/5) (7/5) ] | notes :8 [ t(12/5.12/4)s(5/5.5/4) 3b4/5 ] :h 5V/6 """ assert.notEqual null, tab.parse(code) catchError assert, tab, "tabstave\n notes :q 5/L" @staveOptionsTest: (assert) -> assert.expect 3 tab = makeParser() assert.notEqual null, tab.parse("tabstave notation=true key=C#") catchError(assert, tab, "tabstave invalid=true") catchError(assert, tab, "tabstave notation=boo") @notationOnly: (assert) -> assert.expect 122 tab = makeParser() assert.notEqual null, tab.parse("tabstave notation=true") assert.notEqual null, tab.parse("tabstave\n notes :w 1/2 | 1/3 | 1/5 | 1/4") assert.notEqual null, tab.parse("tabstave notation=true tablature=false") assert.notEqual null, tab.parse("tabstave\n notes :w 1/2 | 1/3 | 1/5 | 1/4") catchError(assert, tab, "tabstave notation=false tablature=false") # CLEF TESTS clefs = ["treble", "alto", "tenor", "bass"] for clef in clefs assert.notEqual null, tab.parse("tabstave notation=true clef=" + clef) assert.notEqual null, tab.parse("tabstave clef=" + clef) catchError(assert, tab, "tabstave clef=blah") # KEY SIGNATURE TESTS for key of Vex.Flow.keySignature.keySpecs assert.notEqual null, tab.parse("tabstave key=" + key) assert.notEqual null, tab.parse("tabstave notation=true key=" + key) assert.notEqual null, tab.parse("tabstave notation=true tablature=true key=" + key) catchError(assert, tab, "tabstave notation=true key=rrr") # TIME SIGNATURE TESTS times = ["C", "C|", "2/4", "4/4", "100/4"] for time in times assert.notEqual null, tab.parse("tabstave time=" + time) assert.notEqual null, tab.parse("tabstave notation=true time=" + time) assert.notEqual null, tab.parse("tabstave notation=true tablature=true time=" + time) catchError(assert, tab, "tabstave notation=true time=rrr") assert.ok true, "all pass" @tuning: (assert) -> assert.expect 9 tab = makeParser() assert.notEqual null, tab.parse("tabstave tuning=E/5,B/4,G/4,D/4,A/3,E/3") assert.notEqual null, tab.parse("tabstave tuning=standard") assert.notEqual null, tab.parse("tabstave tuning=eb") assert.notEqual null, tab.parse("tabstave tuning=dropd") catchError(assert, tab, "tabstave tuning=,B/4,G/4,D/4,A/3,E/3") catchError(assert, tab, "tabstave tuning=/4,G/4,D/4,A/3,E/3") catchError(assert, tab, "tabstave tuning=E,B,G,D,A,E") catchError(assert, tab, "tabstave tuning=T/5,B/4,G/4,D/4,A/3,E/3") assert.ok true, "all pass" @stringFret: (assert) -> assert.expect 5 tab = makeParser() assert.notEqual null, tab.parse "tabstave\n notes 10/2 10/3" catchError(assert, tab, "tabstave\n notes /2 10/3") catchError(assert, tab, "tabstave\n notes j/2 10/3") catchError(assert, tab, "tabstave\n notes 4") assert.ok true, "all pass" @multiFret: (assert) -> assert.expect 4 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes 10-11/3") assert.notEqual null, tab.parse("tabstave\n notes 10-11-12-13-15/3 5-4-3-2-1/2") catchError(assert, tab, "tabstave\n notes 10/2-10") catchError(assert, tab, "tabstave\n notes 10-/2") @tie: (assert) -> assert.expect 6 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes 10s11/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11h12p10/3") assert.notEqual null, tab.parse("tabstave notation=true key=A\n notes :w 5/5 | T5/5 | T5V/5") catchError(assert, tab, "tabstave\n notes 10/2s10") catchError(assert, tab, "tabstave\n notes 10s") assert.ok true, "all pass" @bar: (assert) -> assert.expect 7 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes |10s11/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11h12p10/3|") assert.notEqual null, tab.parse("tabstave notation=true key=A\n notes || :w || 5/5 ||| T5/5 | T5V/5") catchError(assert, tab, "tabstave\n | notes 10/2s10") code = """tabstave notation=true key=E time=12/8 notes :w 7/4 | :w 6/5""" assertEquivalent(assert, "Sole notes line ends with bar", code, code + " |") code = """tabstave notation=true key=E time=12/8 notes :w 7/4 | notes :w 6/5""" assertEquivalent(assert, "Last notes line ends with bar", code, code + " |") assert.ok true, "all pass" @bend: (assert) -> assert.expect 5 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes 10b11/3") assert.notEqual null, tab.parse("tabstave\n notes 10b11s12/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11b12/3") catchError(assert, tab, "tabstave\n notes 10b12b10b-/2") assert.ok(true, "all pass"); @vibrato: (assert) -> assert.expect 10 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes 10v/3") assert.notEqual null, tab.parse("tabstave\n notes 10-11v-12v/3") assert.notEqual null, tab.parse("tabstave\n notes 10b11v-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10b11b10v-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11v-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11vs4s12vh15p10-1/2") catchError(assert, tab, "tabstave\n notes 10v") catchError(assert, tab, "tabstave\n notes 10vb/1") catchError(assert, tab, "tabstave\n notes 10-b11/3") assert.ok(true, "all pass") @strokes: (assert) -> assert.expect 10 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes 10d/3") assert.notEqual null, tab.parse("tabstave\n notes 10-11u-12d/3") assert.notEqual null, tab.parse("tabstave\n notes 10b11u-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10b11b10d-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11d-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11us4s12vh15p10-1/2") assert.notEqual null, tab.parse("tabstave\n notes (10/2.10/1)d") catchError(assert, tab, "tabstave\n notes 10vb/1") catchError(assert, tab, "tabstave\n notes 10-b11/3") assert.ok(true, "all pass"); @chord: (assert) -> assert.expect 8 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes (4/6)") assert.notEqual null, tab.parse("tabstave\n notes (4/5.6/6)") catchError assert, tab, "tabstave\n notes (4/5.6/7)", "BadArguments" catchError assert, tab, "tabstave\n notes (4" catchError assert, tab, "tabstave\n notes (4/)" catchError assert, tab, "tabstave\n notes (/5)" catchError assert, tab, "tabstave\n notes (4/5.)" assert.ok(true, "all pass") @tapping: (assert) -> assert.expect 5 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes t5p4p3/3") assert.notEqual null, tab.parse("tabstave\n notes 5t12p5-4-3/1") catchError(assert, tab, "tabstave\n notes 5t/4") catchError(assert, tab, "tabstave\n notes t-4-4h5/3") assert.ok(true, "all pass") @chordTies: (assert) -> assert.expect 7 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes (1/2.2/3)s(3/2.4/3)") assert.notEqual null, tab.parse("tabstave\n notes (1/2.2/3.3/4)s(3/2.4/3.5/4)") assert.notEqual null, tab.parse("tabstave\n notes (4/5.1/2.2/3)s(3/2.4/3)") assert.notEqual null, tab.parse("tabstave\n notes (1/2.2/3)s(3/2.5/5.4/3)") assert.notEqual null, tab.parse("tabstave\n notes (1/2.2/3)s(3/2.4/3)h(6/2.7/3)") assert.notEqual null, tab.parse("tabstave\n notes t(1/2.2/3)s(3/2.4/3)h(6/2.7/3)") assert.ok(true, "all pass") @duration: (assert) -> tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes :w (1/2.2/3)s(3/2.4/3)") assert.notEqual null, tab.parse("tabstave\n notes :h (1/2.2/3)s(3/2.4/3) :q 1/2") assert.notEqual null, tab.parse("tabstave\n notes :h (1/2.2/3)s(3/2.4/3) 1/2 ^3^") catchError(assert, tab, "tabstave notation=true\n notes :w (1/2.2/3)s(3/2.4/3) ^3^", "ArtistError") assert.ok(true, "all pass") @tripletsAndTuplets: (assert) -> assert.expect 1 tab = makeParser() code = """ tabstave notation=true key=Ab tuning=eb notes :8 5s7s8/5 ^3^ :16 (5/2.6/3) 7-12-15s21/3 ^5^ tabstave notation=true key=Ab tuning=eb notes :8 5h7s9-12s15p12h15/5 ^7^ | :q 5-7-8/5 ^3^ """ assert.notEqual null, tab.parse(code) @dottedNotes: (assert) -> assert.expect 1 tab = makeParser() code = """ tabstave notation=true time=4/4 key=Ab tuning=eb notes :8d 5/4 :16 5/5 :8d 5/4 :16 5/5 :8d 5/4 :16 5/5 :q 5v/5 """ assert.notEqual null, tab.parse(code) @annotations: (assert) -> assert.expect 1 tab = makeParser() code = """ tabstave notation=true time=4/4 key=Ab tuning=eb notes :q 5/5 5/4 5/3 ^3^ $Fi,Ga,Ro!$ :h 4/4 $Blah!$ tabstave notation=true key=A notes :q (5/2.5/3.7/4) $.big.A7#9$ 5h6/3 7/4 | notes :8 7/4 $.italic.sweep$ 6/3 5/2 3v/1 :q 7v/5 $.Arial-10-bold.P.H$ :8 3s5/5 """ assert.notEqual null, tab.parse(code) @longBends: (assert) -> assert.expect 1 tab = makeParser() code = """ tabstave notation=true key=A notes :8 7b9b7b9b7s12b14b12s7s5s2/3 """ assert.notEqual null, tab.parse(code) @rest: (assert) -> assert.expect 1 tab = makeParser() code = """ tabstave notation=true key=A notes :8 ## 7b9b7b9b7s12b14b12s7s5s2/3 #0# 4/4 #9# 5/5 """ assert.notEqual null, tab.parse(code) @options: (assert) -> assert.expect 8 tab = makeParser() assert.notEqual null, tab.parse("options width=400\ntabstave\n") assert.notEqual null, tab.parse("options font-face=Arial\ntabstave\n") assert.notEqual null, tab.parse("options font-size=10\ntabstave\n") assert.notEqual null, tab.parse("options font-style=italic\ntabstave\n") assert.notEqual null, tab.parse("options space=40\ntabstave\n") assert.notEqual null, tab.parse("options stave-distance=40\ntabstave\n") catchError assert, tab, "options w=40\ntabstave\n notes /2 10/3" assert.ok true, "all pass" @abcNotes: (assert) -> assert.expect 6 tab = makeParser() assert.notEqual null, tab.parse("tabstave notation=true\n notes A/5 C-D-E/5") assert.notEqual null, tab.parse("tabstave\n notes :q A/5 C-D-:h:E/5") assert.notEqual null, tab.parse("tabstave\n notes :q (A/5.A/4)T(A/5.A/4)") assert.notEqual null, tab.parse("tabstave notation=true tablature=false\n notes A#/5 C##-D@@-E/5") assert.notEqual null, tab.parse("tabstave\n notes An/5 C-D@-E/5") assert.ok(true, "all pass") @abcNotesWithFrets: (assert) -> assert.expect 6 tab = makeParser() assert.notEqual null, tab.parse("tabstave notation=true\n notes A5_5/5 Cn~4_4-5-6/5") assert.notEqual null, tab.parse("tabstave\n notes :q A/5 C-D-:h:A4_6/5") assert.notEqual null, tab.parse("tabstave\n notes :q (E@2_6/5.A/4)T(A/5.A/4)") assert.notEqual null, tab.parse("tabstave notation=true tablature=false\n notes A#3_4/5 C##-D@@-E/5") assert.notEqual null, tab.parse("tabstave\n notes A@~3_6/5 C-D@-E/5") assert.ok(true, "all pass") @rhythmNotation: (assert) -> assert.expect 4 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes :qS A/5 C-D-:h:E/5") assert.notEqual null, tab.parse("tabstave notation=true\n notes :16S (A/5.A/4)T(A/5.A/4)") assert.notEqual null, tab.parse("tabstave notation=true tablature=false\n notes :qS X/5 C-D-:h:E/5") assert.ok(true, "all pass") @textLines: (assert) -> assert.expect 6 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes :qS A/5 C-D-:h:E/5") assert.notEqual null, tab.parse("tabstave\n text .4, Blah, :16, Boo") assert.notEqual null, tab.parse("tabstave notation=true\n text .4, Blah, :16, Boo") assert.notEqual null, tab.parse("tabstave notation=true\n text .4, Blah,++, :16, Boo") assert.notEqual null, tab.parse("tabstave notation=true\n text .4, .strict, Blah,++, :16, .smooth, Boo") assert.ok(true, "all pass") @sweepStrokes: (assert) -> assert.expect 8 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/rd.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/ru.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/bu.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/bd.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/qu.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/qd.$") catchError assert, tab, "tabstave\n notes :q (5/2.5/3.7/4) $.stroke/xd.$", "ArtistError" assert.ok(true, "all pass") @voices: (assert) -> assert.expect 1 tab = makeParser() code = """ options stave-distance=30 tabstave notation=true key=A time=4/4 voice notes :q (5/2.5/3.7/4) :8 7p5h6/3 ^3^ 5h6h7/5 ^3^ :q 7V/4 | notes :8 t12p7/4 s5s3/4 :8 3s:16:5-7/5 :q p5/4 voice notes :h 5/6 :q 5/6 :8 4-5/5 | :w 5/5 """ assert.notEqual null, tab.parse(code) @fingering: (assert) -> assert.expect 7 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:r:s:1.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:l:f:1.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:a:s:1.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:b:s:1.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:l:f:1.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:r:s:1.$") assert.ok(true, "all pass") @render: (assert) -> tab = makeParser() renderer = makeRenderer("Render") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:r:s:1.$") tab.getArtist().render(renderer) assert.ok(true, "all pass") @renderComplex: (assert) -> code = """ options space=20 tab-stems=true stave-distance=40 tab-stem-direction=down tabstave notation=true key=A time=4/4 notes :q =|: (5/2.5/3.7/4) :8 7-5h6/3 ^3^ 5h6-7/5 ^3^ :q 7V/4 | notes :8 t12p7/4 s5s3/4 :8 3s:16:5-7/5 :h p5/4 text :w, |#segno, ,|, :hd, , #tr options space=65 tabstave notation=true notes :q (5/4.5/5) (7/4.7/5)s(5/4.5/5) ^3^ notes :8 7-5/4 $.a./b.$ (5/4.5/5)h(7/5) =:| notes :8 (12/5.12/4)ds(5/5.5/4)u 3b4/5 notes :h (5V/6.5/4.6/3.7/2) $.italic.let ring$ =|= text :h, ,.font=Times-12-italic, D.S. al coda, |#coda text :h, ,.-1, .font=Arial-14-bold,A13 text ++, .30, #f options space=70 """ renderTest assert, "Render Complex", code @tabStems: (assert) -> code = """ options tab-stems=true tabstave key=A notes :q (5/2.5/3.7/4) $.a./b.$ :8 5h6/3 7/4 $.a>/b.$ notes :16 5h6/3 7/4 $.a>/b.$ notes :8d 5/5 """ renderTest assert, "Tab Stems", code code = """ options tab-stems=true tab-stem-direction=down tabstave key=A notation=true notes :q (5/2.5/3.7/4) $.a./b.$ :8 5h6/3 7/4 $.a>/b.$ notes :16 5h6/3 7/4 $.a>/b.$ notes :8d 5/5 """ renderTest assert, "Tab Stem Direction", code @restsInTab: (assert) -> code = """ options tab-stems=true tabstave key=A notes :q (5/2.5/3.7/4) $.a./b.$ :8 5h6/3 7/4 $.a>/b.$ notes :16 5h6/3 7/4 $.a>/b.$ notes :8d ## """ renderTest assert, "Rests in Tab", code @timeSigBeaming: (assert) -> code = """ tabstave notation=true tablature=false time=4/4 notes :8 ## D-E-F-G-A-B/4 C/5 tabstave notation=true tablature=false time=6/8 notes :8 C-D-E-F/4 ## A-B/4 C-D-E-F-:16:G-F/5 """ renderTest assert, "Time Signature based Beaming", code @multiStringTab: (assert) -> code = """ tabstave key=A strings=4 notes :q (5/2.5/3.7/4) $.a./b.$ :8 5h6/3 7/4 $.a>/b.$ notes :16 5h6/3 7/4 $.a>/b.$ options space=20 """ renderTest assert, "Bass Tab", code code = """ tabstave key=A strings=8 tuning=E/5,B/4,G/4,D/4,A/3,E/3,B/2,G/2 notes :q (5/2.5/3.7/8) :8 5h6/3 7/8 notes :16 5h6/3 7/7 """ renderTest assert, "8-string Tab", code @overrideFretNote: (assert) -> code = """ options stave-distance=30 space=20 options font-face=courier font-style=bold tabstave notation=true key=A time=5/4 notes :q 8/4 $8/4$ notes B@4_8/4 $B@4_8/4$ notes B@~4_8/4 $B@~4_8/4$ notes C@@5_8/4 $C@@5_8/4$ notes G##5_5/1 $G##5_5/1$ text .font=Times-15-italic,|8va """ renderTest assert, "Override Fret Note", code @mixedTuplets: (assert) -> code = """ tabstave notation=true tablature=false key=G time=4/4 notes :q E/5 :8 E/5 ^3,2^ :8 E/5 :q E/5 ^3,2^ notes :8 E-E-E/5 ^3^ ## E-E/5 ^3^ options space=20 """ renderTest assert, "Mixed Tuplets", code @accidentalStrategies: (assert) -> code = """ options player=true tempo=80 tabstave notation=true key=G time=4/4 notes :8 5-5-6-6-5-5-3-3/3 """ renderTest assert, "Standard Accidental Strategy", code code = """ options player=true tempo=80 accidentals=cautionary tabstave notation=true key=G time=4/4 notes :8 5-5-6-6-5-5-3-3/3 """ renderTest assert, "Cautionary Accidental Strategy", code @fingeringAndStrings: (assert) -> code = """ options space=40 player=true tempo=80 instrument=acoustic_guitar_nylon tabstave notation=true tablature=false key=G time=4/4 voice notes !octave-shift -1! notes :8 ## (D/4.G/4.D/5.G/5) notes $.fingering/4:r:f:4-3:r:f:3.$ notes $.fingering/4:l:s:1-3:r:s:2.$ notes :h (E/4.G/4.C/5.E/5) notes $.fingering/1:r:f:2-3:r:f:1.$ notes $.fingering/1:l:s:4-3:r:s:2.$ notes :q ## voice notes :8 G/3 $.fingering/1:r:f:2-1:r:s:6.$ notes :8 F/3 $.fingering/1:r:f:1-1:r:s:6.$ notes :q G/3 $.fingering/1:r:f:2-1:r:s:6.$ notes :q G/3 $.fingering/1:r:f:2-1:r:s:6.$ notes :q G/3 $.fingering/1:r:f:2-1:r:s:6.$ text .font=Arial-14-Bold,.-2 text :8,G,G/F,:h,Am/G options space=60 """ renderTest assert, "Fret Hand Fingering and String Numbers", code VexTabTests.Start()
184793
### VexTab Tests Copyright <NAME> 2010 <<EMAIL>> ### import Vex from 'vexflow'; import Artist from '../src/artist.coffee'; import VexTab from '../src/vextab.coffee'; qunit = QUnit test = qunit.test console.log(test) Artist.DEBUG = false; VexTab.DEBUG = false; class VexTabTests @Start: -> qunit.module "VexTab Parser" test "Basic Test", @basic test "Complex Test", @complex test "Stave Options Test", @staveOptionsTest test "Notation Only Test", @notationOnly test "Tuning Test", @tuning test "String/Fret Test", @stringFret test "MultiFret Test", @multiFret test "Tie Test", @tie test "Bar Test", @bar test "Bend Test", @bend test "Vibrato Test", @vibrato test "Upstroke/Downstroke Test", @strokes test "Chord Test", @chord test "Tapping Test", @tapping test "Chord Ties Test", @chordTies test "Duration Test", @duration test "Triplets and Tuplets Test", @tripletsAndTuplets test "Dotted Notes Test", @dottedNotes test "Annotations Test", @annotations test "Long Bends Test", @longBends test "Rest Test", @rest test "Options Test", @options test "ABC Notes Test", @abcNotes test "ABC Notes with Frets Test", @abcNotesWithFrets test "Rhythm/Slash Notation Test", @rhythmNotation test "Text Lines", @textLines test "Sweep Strokes", @sweepStrokes test "Voices", @voices test "Fingering and String Numbers", @fingering test "Render", @render test "Render Complex", @renderComplex test "Tab Stems", @tabStems test "Rests in Tab", @restsInTab test "Multi String Tab", @multiStringTab test "Time Signature based Beaming", @timeSigBeaming test "Override Fret-Note", @overrideFretNote test "Mixed Tuplets", @mixedTuplets test "Accidental Strategies", @accidentalStrategies test "Fret-hand Fingering and String Numbers", @fingeringAndStrings # Private method catchError = (assert, tab, code, error_type="ParseError") -> error = code: "NoError" message: "Expected exception not caught" caught = false try tab.parse code catch e error = e caught = true # equal(error.code, error_type, error.message) assert.equal(true, caught) makeParser = -> new VexTab(new Artist(0, 0, 800, {scale: 0.8})) makeRenderer = (test_name)-> test_div = $('<div></div>').addClass("testcanvas") test_div.append($('<div></div>').addClass("name").text(test_name)) canvas = $('<div></div>').addClass("vex-tabdiv") test_div.append(canvas) $("body").append(test_div) renderer = new Vex.Flow.Renderer(canvas[0], Vex.Flow.Renderer.Backends.SVG) renderer.getContext().setBackgroundFillStyle("#eed") return renderer renderTest = (assert, title, code) -> tab = makeParser() renderer = makeRenderer(title) assert.notEqual null, tab.parse(code) tab.getArtist().render(renderer) assert.ok(true, "all pass") # ID counter for getRenderedContent. idcounter = 0 # Render content to a new div, and return the content. # Remove some things that change but aren't relevant (IDs) getRenderedContent = (container, code, cssflex) -> idcounter += 1 canvasid = 'rendered-' + idcounter makeCanvas = -> c = $('<div></div>').css('flex', cssflex).css('font-size', '0.8em') p = $('<p></p>').css('margin-top', '0px') p.append($('<pre></pre>').text(code).css('font-family', 'courier')) c.append(p) canvas = $('<div></div>').addClass("vex-tabdiv").attr('id', canvasid) c.append(canvas) return c renderCodeInCanvas = -> tab = new VexTab(new Artist(0, 0, 500, {scale: 0.8})) tab.parse(code) canvas = $('#' + canvasid) renderer = new Vex.Flow.Renderer(canvas[0], Vex.Flow.Renderer.Backends.SVG) renderer.getContext().setBackgroundFillStyle("#eed") tab.getArtist().render(renderer) container.append(makeCanvas()) renderCodeInCanvas() content = $('#' + canvasid). html(). replace(/id=\".*?\"/g, 'id="xxx"') return content # Ensure that the rendered content of vex1 and vex2 are equivalent. assertEquivalent = (assert, title, vex1, vex2) -> test_div = $('<div></div>').addClass("testcanvas") test_div.append($('<div></div>').addClass("name").text(title)) container = $('<div></div>').css('display', 'flex') test_div.append(container) $("body").append(test_div) oldhtml = getRenderedContent(container, vex1, '0 0 30%') newhtml = getRenderedContent(container, vex2, '1') assert.equal(oldhtml, newhtml, title) @basic: (assert) -> assert.expect 3 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n") catchError assert, tab, "tabstave\n notes /2 10/3" assert.ok true, "all pass" @complex: (assert) -> assert.expect 2 tab = makeParser() code = """ tabstave notation=true key=A notes :q (5/2.5/3.7/4) 5h6/3 7/4 | notes :8 [ t12p7p5h7/4 ] :q 7/5 :8 [ 3s5/5 ] notes :8 5-6-7v/4 (8-9-10/4.11s12/4)v tabstave notation=true notes :q (8/2.7b9b7/3) (5b6/2.5b6/3)v :8 [ 7s12/4 ] notes [ t:16:9-:8:3s:16:0/4 ] tabstave notation=true notes :q (5/4.5/5)s(7/4.7/5)s(5/4.5/5) notes :8 [ (5/4.5/5) (7/5) ] | notes :8 [ t(12/5.12/4)s(5/5.5/4) 3b4/5 ] :h 5V/6 """ assert.notEqual null, tab.parse(code) catchError assert, tab, "tabstave\n notes :q 5/L" @staveOptionsTest: (assert) -> assert.expect 3 tab = makeParser() assert.notEqual null, tab.parse("tabstave notation=true key=C#") catchError(assert, tab, "tabstave invalid=true") catchError(assert, tab, "tabstave notation=boo") @notationOnly: (assert) -> assert.expect 122 tab = makeParser() assert.notEqual null, tab.parse("tabstave notation=true") assert.notEqual null, tab.parse("tabstave\n notes :w 1/2 | 1/3 | 1/5 | 1/4") assert.notEqual null, tab.parse("tabstave notation=true tablature=false") assert.notEqual null, tab.parse("tabstave\n notes :w 1/2 | 1/3 | 1/5 | 1/4") catchError(assert, tab, "tabstave notation=false tablature=false") # CLEF TESTS clefs = ["treble", "alto", "tenor", "bass"] for clef in clefs assert.notEqual null, tab.parse("tabstave notation=true clef=" + clef) assert.notEqual null, tab.parse("tabstave clef=" + clef) catchError(assert, tab, "tabstave clef=blah") # KEY SIGNATURE TESTS for key of Vex.Flow.keySignature.keySpecs assert.notEqual null, tab.parse("tabstave key=" + key) assert.notEqual null, tab.parse("tabstave notation=true key=" + key) assert.notEqual null, tab.parse("tabstave notation=true tablature=true key=" + key) catchError(assert, tab, "tabstave notation=true key=rrr") # TIME SIGNATURE TESTS times = ["C", "C|", "2/4", "4/4", "100/4"] for time in times assert.notEqual null, tab.parse("tabstave time=" + time) assert.notEqual null, tab.parse("tabstave notation=true time=" + time) assert.notEqual null, tab.parse("tabstave notation=true tablature=true time=" + time) catchError(assert, tab, "tabstave notation=true time=rrr") assert.ok true, "all pass" @tuning: (assert) -> assert.expect 9 tab = makeParser() assert.notEqual null, tab.parse("tabstave tuning=E/5,B/4,G/4,D/4,A/3,E/3") assert.notEqual null, tab.parse("tabstave tuning=standard") assert.notEqual null, tab.parse("tabstave tuning=eb") assert.notEqual null, tab.parse("tabstave tuning=dropd") catchError(assert, tab, "tabstave tuning=,B/4,G/4,D/4,A/3,E/3") catchError(assert, tab, "tabstave tuning=/4,G/4,D/4,A/3,E/3") catchError(assert, tab, "tabstave tuning=E,B,G,D,A,E") catchError(assert, tab, "tabstave tuning=T/5,B/4,G/4,D/4,A/3,E/3") assert.ok true, "all pass" @stringFret: (assert) -> assert.expect 5 tab = makeParser() assert.notEqual null, tab.parse "tabstave\n notes 10/2 10/3" catchError(assert, tab, "tabstave\n notes /2 10/3") catchError(assert, tab, "tabstave\n notes j/2 10/3") catchError(assert, tab, "tabstave\n notes 4") assert.ok true, "all pass" @multiFret: (assert) -> assert.expect 4 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes 10-11/3") assert.notEqual null, tab.parse("tabstave\n notes 10-11-12-13-15/3 5-4-3-2-1/2") catchError(assert, tab, "tabstave\n notes 10/2-10") catchError(assert, tab, "tabstave\n notes 10-/2") @tie: (assert) -> assert.expect 6 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes 10s11/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11h12p10/3") assert.notEqual null, tab.parse("tabstave notation=true key=A\n notes :w 5/5 | T5/5 | T5V/5") catchError(assert, tab, "tabstave\n notes 10/2s10") catchError(assert, tab, "tabstave\n notes 10s") assert.ok true, "all pass" @bar: (assert) -> assert.expect 7 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes |10s11/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11h12p10/3|") assert.notEqual null, tab.parse("tabstave notation=true key=A\n notes || :w || 5/5 ||| T5/5 | T5V/5") catchError(assert, tab, "tabstave\n | notes 10/2s10") code = """tabstave notation=true key=E time=12/8 notes :w 7/4 | :w 6/5""" assertEquivalent(assert, "Sole notes line ends with bar", code, code + " |") code = """tabstave notation=true key=E time=12/8 notes :w 7/4 | notes :w 6/5""" assertEquivalent(assert, "Last notes line ends with bar", code, code + " |") assert.ok true, "all pass" @bend: (assert) -> assert.expect 5 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes 10b11/3") assert.notEqual null, tab.parse("tabstave\n notes 10b11s12/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11b12/3") catchError(assert, tab, "tabstave\n notes 10b12b10b-/2") assert.ok(true, "all pass"); @vibrato: (assert) -> assert.expect 10 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes 10v/3") assert.notEqual null, tab.parse("tabstave\n notes 10-11v-12v/3") assert.notEqual null, tab.parse("tabstave\n notes 10b11v-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10b11b10v-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11v-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11vs4s12vh15p10-1/2") catchError(assert, tab, "tabstave\n notes 10v") catchError(assert, tab, "tabstave\n notes 10vb/1") catchError(assert, tab, "tabstave\n notes 10-b11/3") assert.ok(true, "all pass") @strokes: (assert) -> assert.expect 10 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes 10d/3") assert.notEqual null, tab.parse("tabstave\n notes 10-11u-12d/3") assert.notEqual null, tab.parse("tabstave\n notes 10b11u-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10b11b10d-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11d-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11us4s12vh15p10-1/2") assert.notEqual null, tab.parse("tabstave\n notes (10/2.10/1)d") catchError(assert, tab, "tabstave\n notes 10vb/1") catchError(assert, tab, "tabstave\n notes 10-b11/3") assert.ok(true, "all pass"); @chord: (assert) -> assert.expect 8 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes (4/6)") assert.notEqual null, tab.parse("tabstave\n notes (4/5.6/6)") catchError assert, tab, "tabstave\n notes (4/5.6/7)", "BadArguments" catchError assert, tab, "tabstave\n notes (4" catchError assert, tab, "tabstave\n notes (4/)" catchError assert, tab, "tabstave\n notes (/5)" catchError assert, tab, "tabstave\n notes (4/5.)" assert.ok(true, "all pass") @tapping: (assert) -> assert.expect 5 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes t5p4p3/3") assert.notEqual null, tab.parse("tabstave\n notes 5t12p5-4-3/1") catchError(assert, tab, "tabstave\n notes 5t/4") catchError(assert, tab, "tabstave\n notes t-4-4h5/3") assert.ok(true, "all pass") @chordTies: (assert) -> assert.expect 7 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes (1/2.2/3)s(3/2.4/3)") assert.notEqual null, tab.parse("tabstave\n notes (1/2.2/3.3/4)s(3/2.4/3.5/4)") assert.notEqual null, tab.parse("tabstave\n notes (4/5.1/2.2/3)s(3/2.4/3)") assert.notEqual null, tab.parse("tabstave\n notes (1/2.2/3)s(3/2.5/5.4/3)") assert.notEqual null, tab.parse("tabstave\n notes (1/2.2/3)s(3/2.4/3)h(6/2.7/3)") assert.notEqual null, tab.parse("tabstave\n notes t(1/2.2/3)s(3/2.4/3)h(6/2.7/3)") assert.ok(true, "all pass") @duration: (assert) -> tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes :w (1/2.2/3)s(3/2.4/3)") assert.notEqual null, tab.parse("tabstave\n notes :h (1/2.2/3)s(3/2.4/3) :q 1/2") assert.notEqual null, tab.parse("tabstave\n notes :h (1/2.2/3)s(3/2.4/3) 1/2 ^3^") catchError(assert, tab, "tabstave notation=true\n notes :w (1/2.2/3)s(3/2.4/3) ^3^", "ArtistError") assert.ok(true, "all pass") @tripletsAndTuplets: (assert) -> assert.expect 1 tab = makeParser() code = """ tabstave notation=true key=Ab tuning=eb notes :8 5s7s8/5 ^3^ :16 (5/2.6/3) 7-12-15s21/3 ^5^ tabstave notation=true key=Ab tuning=eb notes :8 5h7s9-12s15p12h15/5 ^7^ | :q 5-7-8/5 ^3^ """ assert.notEqual null, tab.parse(code) @dottedNotes: (assert) -> assert.expect 1 tab = makeParser() code = """ tabstave notation=true time=4/4 key=Ab tuning=eb notes :8d 5/4 :16 5/5 :8d 5/4 :16 5/5 :8d 5/4 :16 5/5 :q 5v/5 """ assert.notEqual null, tab.parse(code) @annotations: (assert) -> assert.expect 1 tab = makeParser() code = """ tabstave notation=true time=4/4 key=Ab tuning=eb notes :q 5/5 5/4 5/3 ^3^ $Fi,Ga,Ro!$ :h 4/4 $Blah!$ tabstave notation=true key=A notes :q (5/2.5/3.7/4) $.big.A7#9$ 5h6/3 7/4 | notes :8 7/4 $.italic.sweep$ 6/3 5/2 3v/1 :q 7v/5 $.Arial-10-bold.P.H$ :8 3s5/5 """ assert.notEqual null, tab.parse(code) @longBends: (assert) -> assert.expect 1 tab = makeParser() code = """ tabstave notation=true key=A notes :8 7b9b7b9b7s12b14b12s7s5s2/3 """ assert.notEqual null, tab.parse(code) @rest: (assert) -> assert.expect 1 tab = makeParser() code = """ tabstave notation=true key=A notes :8 ## 7b9b7b9b7s12b14b12s7s5s2/3 #0# 4/4 #9# 5/5 """ assert.notEqual null, tab.parse(code) @options: (assert) -> assert.expect 8 tab = makeParser() assert.notEqual null, tab.parse("options width=400\ntabstave\n") assert.notEqual null, tab.parse("options font-face=Arial\ntabstave\n") assert.notEqual null, tab.parse("options font-size=10\ntabstave\n") assert.notEqual null, tab.parse("options font-style=italic\ntabstave\n") assert.notEqual null, tab.parse("options space=40\ntabstave\n") assert.notEqual null, tab.parse("options stave-distance=40\ntabstave\n") catchError assert, tab, "options w=40\ntabstave\n notes /2 10/3" assert.ok true, "all pass" @abcNotes: (assert) -> assert.expect 6 tab = makeParser() assert.notEqual null, tab.parse("tabstave notation=true\n notes A/5 C-D-E/5") assert.notEqual null, tab.parse("tabstave\n notes :q A/5 C-D-:h:E/5") assert.notEqual null, tab.parse("tabstave\n notes :q (A/5.A/4)T(A/5.A/4)") assert.notEqual null, tab.parse("tabstave notation=true tablature=false\n notes A#/5 C##-D@@-E/5") assert.notEqual null, tab.parse("tabstave\n notes An/5 C-D@-E/5") assert.ok(true, "all pass") @abcNotesWithFrets: (assert) -> assert.expect 6 tab = makeParser() assert.notEqual null, tab.parse("tabstave notation=true\n notes A5_5/5 Cn~4_4-5-6/5") assert.notEqual null, tab.parse("tabstave\n notes :q A/5 C-D-:h:A4_6/5") assert.notEqual null, tab.parse("tabstave\n notes :q (E@2_6/5.A/4)T(A/5.A/4)") assert.notEqual null, tab.parse("tabstave notation=true tablature=false\n notes A#3_4/5 C##-D@@-E/5") assert.notEqual null, tab.parse("tabstave\n notes A@~3_6/5 C-D@-E/5") assert.ok(true, "all pass") @rhythmNotation: (assert) -> assert.expect 4 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes :qS A/5 C-D-:h:E/5") assert.notEqual null, tab.parse("tabstave notation=true\n notes :16S (A/5.A/4)T(A/5.A/4)") assert.notEqual null, tab.parse("tabstave notation=true tablature=false\n notes :qS X/5 C-D-:h:E/5") assert.ok(true, "all pass") @textLines: (assert) -> assert.expect 6 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes :qS A/5 C-D-:h:E/5") assert.notEqual null, tab.parse("tabstave\n text .4, Blah, :16, Boo") assert.notEqual null, tab.parse("tabstave notation=true\n text .4, Blah, :16, Boo") assert.notEqual null, tab.parse("tabstave notation=true\n text .4, Blah,++, :16, Boo") assert.notEqual null, tab.parse("tabstave notation=true\n text .4, .strict, Blah,++, :16, .smooth, Boo") assert.ok(true, "all pass") @sweepStrokes: (assert) -> assert.expect 8 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/rd.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/ru.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/bu.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/bd.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/qu.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/qd.$") catchError assert, tab, "tabstave\n notes :q (5/2.5/3.7/4) $.stroke/xd.$", "ArtistError" assert.ok(true, "all pass") @voices: (assert) -> assert.expect 1 tab = makeParser() code = """ options stave-distance=30 tabstave notation=true key=A time=4/4 voice notes :q (5/2.5/3.7/4) :8 7p5h6/3 ^3^ 5h6h7/5 ^3^ :q 7V/4 | notes :8 t12p7/4 s5s3/4 :8 3s:16:5-7/5 :q p5/4 voice notes :h 5/6 :q 5/6 :8 4-5/5 | :w 5/5 """ assert.notEqual null, tab.parse(code) @fingering: (assert) -> assert.expect 7 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:r:s:1.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:l:f:1.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:a:s:1.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:b:s:1.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:l:f:1.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:r:s:1.$") assert.ok(true, "all pass") @render: (assert) -> tab = makeParser() renderer = makeRenderer("Render") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:r:s:1.$") tab.getArtist().render(renderer) assert.ok(true, "all pass") @renderComplex: (assert) -> code = """ options space=20 tab-stems=true stave-distance=40 tab-stem-direction=down tabstave notation=true key=A time=4/4 notes :q =|: (5/2.5/3.7/4) :8 7-5h6/3 ^3^ 5h6-7/5 ^3^ :q 7V/4 | notes :8 t12p7/4 s5s3/4 :8 3s:16:5-7/5 :h p5/4 text :w, |#segno, ,|, :hd, , #tr options space=65 tabstave notation=true notes :q (5/4.5/5) (7/4.7/5)s(5/4.5/5) ^3^ notes :8 7-5/4 $.a./b.$ (5/4.5/5)h(7/5) =:| notes :8 (12/5.12/4)ds(5/5.5/4)u 3b4/5 notes :h (5V/6.5/4.6/3.7/2) $.italic.let ring$ =|= text :h, ,.font=Times-12-italic, D.S. al coda, |#coda text :h, ,.-1, .font=Arial-14-bold,A13 text ++, .30, #f options space=70 """ renderTest assert, "Render Complex", code @tabStems: (assert) -> code = """ options tab-stems=true tabstave key=A notes :q (5/2.5/3.7/4) $.a./b.$ :8 5h6/3 7/4 $.a>/b.$ notes :16 5h6/3 7/4 $.a>/b.$ notes :8d 5/5 """ renderTest assert, "Tab Stems", code code = """ options tab-stems=true tab-stem-direction=down tabstave key=A notation=true notes :q (5/2.5/3.7/4) $.a./b.$ :8 5h6/3 7/4 $.a>/b.$ notes :16 5h6/3 7/4 $.a>/b.$ notes :8d 5/5 """ renderTest assert, "Tab Stem Direction", code @restsInTab: (assert) -> code = """ options tab-stems=true tabstave key=A notes :q (5/2.5/3.7/4) $.a./b.$ :8 5h6/3 7/4 $.a>/b.$ notes :16 5h6/3 7/4 $.a>/b.$ notes :8d ## """ renderTest assert, "Rests in Tab", code @timeSigBeaming: (assert) -> code = """ tabstave notation=true tablature=false time=4/4 notes :8 ## D-E-F-G-A-B/4 C/5 tabstave notation=true tablature=false time=6/8 notes :8 C-D-E-F/4 ## A-B/4 C-D-E-F-:16:G-F/5 """ renderTest assert, "Time Signature based Beaming", code @multiStringTab: (assert) -> code = """ tabstave key=A strings=4 notes :q (5/2.5/3.7/4) $.a./b.$ :8 5h6/3 7/4 $.a>/b.$ notes :16 5h6/3 7/4 $.a>/b.$ options space=20 """ renderTest assert, "Bass Tab", code code = """ tabstave key=A strings=8 tuning=E/5,B/4,G/4,D/4,A/3,E/3,B/2,G/2 notes :q (5/2.5/3.7/8) :8 5h6/3 7/8 notes :16 5h6/3 7/7 """ renderTest assert, "8-string Tab", code @overrideFretNote: (assert) -> code = """ options stave-distance=30 space=20 options font-face=courier font-style=bold tabstave notation=true key=A time=5/4 notes :q 8/4 $8/4$ notes B@4_8/4 $B@4_8/4$ notes B@~4_8/4 $B@~4_8/4$ notes C@@5_8/4 $C@@5_8/4$ notes G##5_5/1 $G##5_5/1$ text .font=Times-15-italic,|8va """ renderTest assert, "Override Fret Note", code @mixedTuplets: (assert) -> code = """ tabstave notation=true tablature=false key=G time=4/4 notes :q E/5 :8 E/5 ^3,2^ :8 E/5 :q E/5 ^3,2^ notes :8 E-E-E/5 ^3^ ## E-E/5 ^3^ options space=20 """ renderTest assert, "Mixed Tuplets", code @accidentalStrategies: (assert) -> code = """ options player=true tempo=80 tabstave notation=true key=G time=4/4 notes :8 5-5-6-6-5-5-3-3/3 """ renderTest assert, "Standard Accidental Strategy", code code = """ options player=true tempo=80 accidentals=cautionary tabstave notation=true key=G time=4/4 notes :8 5-5-6-6-5-5-3-3/3 """ renderTest assert, "Cautionary Accidental Strategy", code @fingeringAndStrings: (assert) -> code = """ options space=40 player=true tempo=80 instrument=acoustic_guitar_nylon tabstave notation=true tablature=false key=G time=4/4 voice notes !octave-shift -1! notes :8 ## (D/4.G/4.D/5.G/5) notes $.fingering/4:r:f:4-3:r:f:3.$ notes $.fingering/4:l:s:1-3:r:s:2.$ notes :h (E/4.G/4.C/5.E/5) notes $.fingering/1:r:f:2-3:r:f:1.$ notes $.fingering/1:l:s:4-3:r:s:2.$ notes :q ## voice notes :8 G/3 $.fingering/1:r:f:2-1:r:s:6.$ notes :8 F/3 $.fingering/1:r:f:1-1:r:s:6.$ notes :q G/3 $.fingering/1:r:f:2-1:r:s:6.$ notes :q G/3 $.fingering/1:r:f:2-1:r:s:6.$ notes :q G/3 $.fingering/1:r:f:2-1:r:s:6.$ text .font=Arial-14-Bold,.-2 text :8,G,G/F,:h,Am/G options space=60 """ renderTest assert, "Fret Hand Fingering and String Numbers", code VexTabTests.Start()
true
### VexTab Tests Copyright PI:NAME:<NAME>END_PI 2010 <PI:EMAIL:<EMAIL>END_PI> ### import Vex from 'vexflow'; import Artist from '../src/artist.coffee'; import VexTab from '../src/vextab.coffee'; qunit = QUnit test = qunit.test console.log(test) Artist.DEBUG = false; VexTab.DEBUG = false; class VexTabTests @Start: -> qunit.module "VexTab Parser" test "Basic Test", @basic test "Complex Test", @complex test "Stave Options Test", @staveOptionsTest test "Notation Only Test", @notationOnly test "Tuning Test", @tuning test "String/Fret Test", @stringFret test "MultiFret Test", @multiFret test "Tie Test", @tie test "Bar Test", @bar test "Bend Test", @bend test "Vibrato Test", @vibrato test "Upstroke/Downstroke Test", @strokes test "Chord Test", @chord test "Tapping Test", @tapping test "Chord Ties Test", @chordTies test "Duration Test", @duration test "Triplets and Tuplets Test", @tripletsAndTuplets test "Dotted Notes Test", @dottedNotes test "Annotations Test", @annotations test "Long Bends Test", @longBends test "Rest Test", @rest test "Options Test", @options test "ABC Notes Test", @abcNotes test "ABC Notes with Frets Test", @abcNotesWithFrets test "Rhythm/Slash Notation Test", @rhythmNotation test "Text Lines", @textLines test "Sweep Strokes", @sweepStrokes test "Voices", @voices test "Fingering and String Numbers", @fingering test "Render", @render test "Render Complex", @renderComplex test "Tab Stems", @tabStems test "Rests in Tab", @restsInTab test "Multi String Tab", @multiStringTab test "Time Signature based Beaming", @timeSigBeaming test "Override Fret-Note", @overrideFretNote test "Mixed Tuplets", @mixedTuplets test "Accidental Strategies", @accidentalStrategies test "Fret-hand Fingering and String Numbers", @fingeringAndStrings # Private method catchError = (assert, tab, code, error_type="ParseError") -> error = code: "NoError" message: "Expected exception not caught" caught = false try tab.parse code catch e error = e caught = true # equal(error.code, error_type, error.message) assert.equal(true, caught) makeParser = -> new VexTab(new Artist(0, 0, 800, {scale: 0.8})) makeRenderer = (test_name)-> test_div = $('<div></div>').addClass("testcanvas") test_div.append($('<div></div>').addClass("name").text(test_name)) canvas = $('<div></div>').addClass("vex-tabdiv") test_div.append(canvas) $("body").append(test_div) renderer = new Vex.Flow.Renderer(canvas[0], Vex.Flow.Renderer.Backends.SVG) renderer.getContext().setBackgroundFillStyle("#eed") return renderer renderTest = (assert, title, code) -> tab = makeParser() renderer = makeRenderer(title) assert.notEqual null, tab.parse(code) tab.getArtist().render(renderer) assert.ok(true, "all pass") # ID counter for getRenderedContent. idcounter = 0 # Render content to a new div, and return the content. # Remove some things that change but aren't relevant (IDs) getRenderedContent = (container, code, cssflex) -> idcounter += 1 canvasid = 'rendered-' + idcounter makeCanvas = -> c = $('<div></div>').css('flex', cssflex).css('font-size', '0.8em') p = $('<p></p>').css('margin-top', '0px') p.append($('<pre></pre>').text(code).css('font-family', 'courier')) c.append(p) canvas = $('<div></div>').addClass("vex-tabdiv").attr('id', canvasid) c.append(canvas) return c renderCodeInCanvas = -> tab = new VexTab(new Artist(0, 0, 500, {scale: 0.8})) tab.parse(code) canvas = $('#' + canvasid) renderer = new Vex.Flow.Renderer(canvas[0], Vex.Flow.Renderer.Backends.SVG) renderer.getContext().setBackgroundFillStyle("#eed") tab.getArtist().render(renderer) container.append(makeCanvas()) renderCodeInCanvas() content = $('#' + canvasid). html(). replace(/id=\".*?\"/g, 'id="xxx"') return content # Ensure that the rendered content of vex1 and vex2 are equivalent. assertEquivalent = (assert, title, vex1, vex2) -> test_div = $('<div></div>').addClass("testcanvas") test_div.append($('<div></div>').addClass("name").text(title)) container = $('<div></div>').css('display', 'flex') test_div.append(container) $("body").append(test_div) oldhtml = getRenderedContent(container, vex1, '0 0 30%') newhtml = getRenderedContent(container, vex2, '1') assert.equal(oldhtml, newhtml, title) @basic: (assert) -> assert.expect 3 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n") catchError assert, tab, "tabstave\n notes /2 10/3" assert.ok true, "all pass" @complex: (assert) -> assert.expect 2 tab = makeParser() code = """ tabstave notation=true key=A notes :q (5/2.5/3.7/4) 5h6/3 7/4 | notes :8 [ t12p7p5h7/4 ] :q 7/5 :8 [ 3s5/5 ] notes :8 5-6-7v/4 (8-9-10/4.11s12/4)v tabstave notation=true notes :q (8/2.7b9b7/3) (5b6/2.5b6/3)v :8 [ 7s12/4 ] notes [ t:16:9-:8:3s:16:0/4 ] tabstave notation=true notes :q (5/4.5/5)s(7/4.7/5)s(5/4.5/5) notes :8 [ (5/4.5/5) (7/5) ] | notes :8 [ t(12/5.12/4)s(5/5.5/4) 3b4/5 ] :h 5V/6 """ assert.notEqual null, tab.parse(code) catchError assert, tab, "tabstave\n notes :q 5/L" @staveOptionsTest: (assert) -> assert.expect 3 tab = makeParser() assert.notEqual null, tab.parse("tabstave notation=true key=C#") catchError(assert, tab, "tabstave invalid=true") catchError(assert, tab, "tabstave notation=boo") @notationOnly: (assert) -> assert.expect 122 tab = makeParser() assert.notEqual null, tab.parse("tabstave notation=true") assert.notEqual null, tab.parse("tabstave\n notes :w 1/2 | 1/3 | 1/5 | 1/4") assert.notEqual null, tab.parse("tabstave notation=true tablature=false") assert.notEqual null, tab.parse("tabstave\n notes :w 1/2 | 1/3 | 1/5 | 1/4") catchError(assert, tab, "tabstave notation=false tablature=false") # CLEF TESTS clefs = ["treble", "alto", "tenor", "bass"] for clef in clefs assert.notEqual null, tab.parse("tabstave notation=true clef=" + clef) assert.notEqual null, tab.parse("tabstave clef=" + clef) catchError(assert, tab, "tabstave clef=blah") # KEY SIGNATURE TESTS for key of Vex.Flow.keySignature.keySpecs assert.notEqual null, tab.parse("tabstave key=" + key) assert.notEqual null, tab.parse("tabstave notation=true key=" + key) assert.notEqual null, tab.parse("tabstave notation=true tablature=true key=" + key) catchError(assert, tab, "tabstave notation=true key=rrr") # TIME SIGNATURE TESTS times = ["C", "C|", "2/4", "4/4", "100/4"] for time in times assert.notEqual null, tab.parse("tabstave time=" + time) assert.notEqual null, tab.parse("tabstave notation=true time=" + time) assert.notEqual null, tab.parse("tabstave notation=true tablature=true time=" + time) catchError(assert, tab, "tabstave notation=true time=rrr") assert.ok true, "all pass" @tuning: (assert) -> assert.expect 9 tab = makeParser() assert.notEqual null, tab.parse("tabstave tuning=E/5,B/4,G/4,D/4,A/3,E/3") assert.notEqual null, tab.parse("tabstave tuning=standard") assert.notEqual null, tab.parse("tabstave tuning=eb") assert.notEqual null, tab.parse("tabstave tuning=dropd") catchError(assert, tab, "tabstave tuning=,B/4,G/4,D/4,A/3,E/3") catchError(assert, tab, "tabstave tuning=/4,G/4,D/4,A/3,E/3") catchError(assert, tab, "tabstave tuning=E,B,G,D,A,E") catchError(assert, tab, "tabstave tuning=T/5,B/4,G/4,D/4,A/3,E/3") assert.ok true, "all pass" @stringFret: (assert) -> assert.expect 5 tab = makeParser() assert.notEqual null, tab.parse "tabstave\n notes 10/2 10/3" catchError(assert, tab, "tabstave\n notes /2 10/3") catchError(assert, tab, "tabstave\n notes j/2 10/3") catchError(assert, tab, "tabstave\n notes 4") assert.ok true, "all pass" @multiFret: (assert) -> assert.expect 4 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes 10-11/3") assert.notEqual null, tab.parse("tabstave\n notes 10-11-12-13-15/3 5-4-3-2-1/2") catchError(assert, tab, "tabstave\n notes 10/2-10") catchError(assert, tab, "tabstave\n notes 10-/2") @tie: (assert) -> assert.expect 6 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes 10s11/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11h12p10/3") assert.notEqual null, tab.parse("tabstave notation=true key=A\n notes :w 5/5 | T5/5 | T5V/5") catchError(assert, tab, "tabstave\n notes 10/2s10") catchError(assert, tab, "tabstave\n notes 10s") assert.ok true, "all pass" @bar: (assert) -> assert.expect 7 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes |10s11/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11h12p10/3|") assert.notEqual null, tab.parse("tabstave notation=true key=A\n notes || :w || 5/5 ||| T5/5 | T5V/5") catchError(assert, tab, "tabstave\n | notes 10/2s10") code = """tabstave notation=true key=E time=12/8 notes :w 7/4 | :w 6/5""" assertEquivalent(assert, "Sole notes line ends with bar", code, code + " |") code = """tabstave notation=true key=E time=12/8 notes :w 7/4 | notes :w 6/5""" assertEquivalent(assert, "Last notes line ends with bar", code, code + " |") assert.ok true, "all pass" @bend: (assert) -> assert.expect 5 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes 10b11/3") assert.notEqual null, tab.parse("tabstave\n notes 10b11s12/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11b12/3") catchError(assert, tab, "tabstave\n notes 10b12b10b-/2") assert.ok(true, "all pass"); @vibrato: (assert) -> assert.expect 10 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes 10v/3") assert.notEqual null, tab.parse("tabstave\n notes 10-11v-12v/3") assert.notEqual null, tab.parse("tabstave\n notes 10b11v-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10b11b10v-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11v-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11vs4s12vh15p10-1/2") catchError(assert, tab, "tabstave\n notes 10v") catchError(assert, tab, "tabstave\n notes 10vb/1") catchError(assert, tab, "tabstave\n notes 10-b11/3") assert.ok(true, "all pass") @strokes: (assert) -> assert.expect 10 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes 10d/3") assert.notEqual null, tab.parse("tabstave\n notes 10-11u-12d/3") assert.notEqual null, tab.parse("tabstave\n notes 10b11u-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10b11b10d-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11d-12/3") assert.notEqual null, tab.parse("tabstave\n notes 10s11us4s12vh15p10-1/2") assert.notEqual null, tab.parse("tabstave\n notes (10/2.10/1)d") catchError(assert, tab, "tabstave\n notes 10vb/1") catchError(assert, tab, "tabstave\n notes 10-b11/3") assert.ok(true, "all pass"); @chord: (assert) -> assert.expect 8 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes (4/6)") assert.notEqual null, tab.parse("tabstave\n notes (4/5.6/6)") catchError assert, tab, "tabstave\n notes (4/5.6/7)", "BadArguments" catchError assert, tab, "tabstave\n notes (4" catchError assert, tab, "tabstave\n notes (4/)" catchError assert, tab, "tabstave\n notes (/5)" catchError assert, tab, "tabstave\n notes (4/5.)" assert.ok(true, "all pass") @tapping: (assert) -> assert.expect 5 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes t5p4p3/3") assert.notEqual null, tab.parse("tabstave\n notes 5t12p5-4-3/1") catchError(assert, tab, "tabstave\n notes 5t/4") catchError(assert, tab, "tabstave\n notes t-4-4h5/3") assert.ok(true, "all pass") @chordTies: (assert) -> assert.expect 7 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes (1/2.2/3)s(3/2.4/3)") assert.notEqual null, tab.parse("tabstave\n notes (1/2.2/3.3/4)s(3/2.4/3.5/4)") assert.notEqual null, tab.parse("tabstave\n notes (4/5.1/2.2/3)s(3/2.4/3)") assert.notEqual null, tab.parse("tabstave\n notes (1/2.2/3)s(3/2.5/5.4/3)") assert.notEqual null, tab.parse("tabstave\n notes (1/2.2/3)s(3/2.4/3)h(6/2.7/3)") assert.notEqual null, tab.parse("tabstave\n notes t(1/2.2/3)s(3/2.4/3)h(6/2.7/3)") assert.ok(true, "all pass") @duration: (assert) -> tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes :w (1/2.2/3)s(3/2.4/3)") assert.notEqual null, tab.parse("tabstave\n notes :h (1/2.2/3)s(3/2.4/3) :q 1/2") assert.notEqual null, tab.parse("tabstave\n notes :h (1/2.2/3)s(3/2.4/3) 1/2 ^3^") catchError(assert, tab, "tabstave notation=true\n notes :w (1/2.2/3)s(3/2.4/3) ^3^", "ArtistError") assert.ok(true, "all pass") @tripletsAndTuplets: (assert) -> assert.expect 1 tab = makeParser() code = """ tabstave notation=true key=Ab tuning=eb notes :8 5s7s8/5 ^3^ :16 (5/2.6/3) 7-12-15s21/3 ^5^ tabstave notation=true key=Ab tuning=eb notes :8 5h7s9-12s15p12h15/5 ^7^ | :q 5-7-8/5 ^3^ """ assert.notEqual null, tab.parse(code) @dottedNotes: (assert) -> assert.expect 1 tab = makeParser() code = """ tabstave notation=true time=4/4 key=Ab tuning=eb notes :8d 5/4 :16 5/5 :8d 5/4 :16 5/5 :8d 5/4 :16 5/5 :q 5v/5 """ assert.notEqual null, tab.parse(code) @annotations: (assert) -> assert.expect 1 tab = makeParser() code = """ tabstave notation=true time=4/4 key=Ab tuning=eb notes :q 5/5 5/4 5/3 ^3^ $Fi,Ga,Ro!$ :h 4/4 $Blah!$ tabstave notation=true key=A notes :q (5/2.5/3.7/4) $.big.A7#9$ 5h6/3 7/4 | notes :8 7/4 $.italic.sweep$ 6/3 5/2 3v/1 :q 7v/5 $.Arial-10-bold.P.H$ :8 3s5/5 """ assert.notEqual null, tab.parse(code) @longBends: (assert) -> assert.expect 1 tab = makeParser() code = """ tabstave notation=true key=A notes :8 7b9b7b9b7s12b14b12s7s5s2/3 """ assert.notEqual null, tab.parse(code) @rest: (assert) -> assert.expect 1 tab = makeParser() code = """ tabstave notation=true key=A notes :8 ## 7b9b7b9b7s12b14b12s7s5s2/3 #0# 4/4 #9# 5/5 """ assert.notEqual null, tab.parse(code) @options: (assert) -> assert.expect 8 tab = makeParser() assert.notEqual null, tab.parse("options width=400\ntabstave\n") assert.notEqual null, tab.parse("options font-face=Arial\ntabstave\n") assert.notEqual null, tab.parse("options font-size=10\ntabstave\n") assert.notEqual null, tab.parse("options font-style=italic\ntabstave\n") assert.notEqual null, tab.parse("options space=40\ntabstave\n") assert.notEqual null, tab.parse("options stave-distance=40\ntabstave\n") catchError assert, tab, "options w=40\ntabstave\n notes /2 10/3" assert.ok true, "all pass" @abcNotes: (assert) -> assert.expect 6 tab = makeParser() assert.notEqual null, tab.parse("tabstave notation=true\n notes A/5 C-D-E/5") assert.notEqual null, tab.parse("tabstave\n notes :q A/5 C-D-:h:E/5") assert.notEqual null, tab.parse("tabstave\n notes :q (A/5.A/4)T(A/5.A/4)") assert.notEqual null, tab.parse("tabstave notation=true tablature=false\n notes A#/5 C##-D@@-E/5") assert.notEqual null, tab.parse("tabstave\n notes An/5 C-D@-E/5") assert.ok(true, "all pass") @abcNotesWithFrets: (assert) -> assert.expect 6 tab = makeParser() assert.notEqual null, tab.parse("tabstave notation=true\n notes A5_5/5 Cn~4_4-5-6/5") assert.notEqual null, tab.parse("tabstave\n notes :q A/5 C-D-:h:A4_6/5") assert.notEqual null, tab.parse("tabstave\n notes :q (E@2_6/5.A/4)T(A/5.A/4)") assert.notEqual null, tab.parse("tabstave notation=true tablature=false\n notes A#3_4/5 C##-D@@-E/5") assert.notEqual null, tab.parse("tabstave\n notes A@~3_6/5 C-D@-E/5") assert.ok(true, "all pass") @rhythmNotation: (assert) -> assert.expect 4 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes :qS A/5 C-D-:h:E/5") assert.notEqual null, tab.parse("tabstave notation=true\n notes :16S (A/5.A/4)T(A/5.A/4)") assert.notEqual null, tab.parse("tabstave notation=true tablature=false\n notes :qS X/5 C-D-:h:E/5") assert.ok(true, "all pass") @textLines: (assert) -> assert.expect 6 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes :qS A/5 C-D-:h:E/5") assert.notEqual null, tab.parse("tabstave\n text .4, Blah, :16, Boo") assert.notEqual null, tab.parse("tabstave notation=true\n text .4, Blah, :16, Boo") assert.notEqual null, tab.parse("tabstave notation=true\n text .4, Blah,++, :16, Boo") assert.notEqual null, tab.parse("tabstave notation=true\n text .4, .strict, Blah,++, :16, .smooth, Boo") assert.ok(true, "all pass") @sweepStrokes: (assert) -> assert.expect 8 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/rd.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/ru.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/bu.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/bd.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/qu.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.stroke/qd.$") catchError assert, tab, "tabstave\n notes :q (5/2.5/3.7/4) $.stroke/xd.$", "ArtistError" assert.ok(true, "all pass") @voices: (assert) -> assert.expect 1 tab = makeParser() code = """ options stave-distance=30 tabstave notation=true key=A time=4/4 voice notes :q (5/2.5/3.7/4) :8 7p5h6/3 ^3^ 5h6h7/5 ^3^ :q 7V/4 | notes :8 t12p7/4 s5s3/4 :8 3s:16:5-7/5 :q p5/4 voice notes :h 5/6 :q 5/6 :8 4-5/5 | :w 5/5 """ assert.notEqual null, tab.parse(code) @fingering: (assert) -> assert.expect 7 tab = makeParser() assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:r:s:1.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:l:f:1.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:a:s:1.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:b:s:1.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:l:f:1.$") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:r:s:1.$") assert.ok(true, "all pass") @render: (assert) -> tab = makeParser() renderer = makeRenderer("Render") assert.notEqual null, tab.parse("tabstave\n notes :q (5/2.5/3.7/4) $.fingering/0:r:s:1.$") tab.getArtist().render(renderer) assert.ok(true, "all pass") @renderComplex: (assert) -> code = """ options space=20 tab-stems=true stave-distance=40 tab-stem-direction=down tabstave notation=true key=A time=4/4 notes :q =|: (5/2.5/3.7/4) :8 7-5h6/3 ^3^ 5h6-7/5 ^3^ :q 7V/4 | notes :8 t12p7/4 s5s3/4 :8 3s:16:5-7/5 :h p5/4 text :w, |#segno, ,|, :hd, , #tr options space=65 tabstave notation=true notes :q (5/4.5/5) (7/4.7/5)s(5/4.5/5) ^3^ notes :8 7-5/4 $.a./b.$ (5/4.5/5)h(7/5) =:| notes :8 (12/5.12/4)ds(5/5.5/4)u 3b4/5 notes :h (5V/6.5/4.6/3.7/2) $.italic.let ring$ =|= text :h, ,.font=Times-12-italic, D.S. al coda, |#coda text :h, ,.-1, .font=Arial-14-bold,A13 text ++, .30, #f options space=70 """ renderTest assert, "Render Complex", code @tabStems: (assert) -> code = """ options tab-stems=true tabstave key=A notes :q (5/2.5/3.7/4) $.a./b.$ :8 5h6/3 7/4 $.a>/b.$ notes :16 5h6/3 7/4 $.a>/b.$ notes :8d 5/5 """ renderTest assert, "Tab Stems", code code = """ options tab-stems=true tab-stem-direction=down tabstave key=A notation=true notes :q (5/2.5/3.7/4) $.a./b.$ :8 5h6/3 7/4 $.a>/b.$ notes :16 5h6/3 7/4 $.a>/b.$ notes :8d 5/5 """ renderTest assert, "Tab Stem Direction", code @restsInTab: (assert) -> code = """ options tab-stems=true tabstave key=A notes :q (5/2.5/3.7/4) $.a./b.$ :8 5h6/3 7/4 $.a>/b.$ notes :16 5h6/3 7/4 $.a>/b.$ notes :8d ## """ renderTest assert, "Rests in Tab", code @timeSigBeaming: (assert) -> code = """ tabstave notation=true tablature=false time=4/4 notes :8 ## D-E-F-G-A-B/4 C/5 tabstave notation=true tablature=false time=6/8 notes :8 C-D-E-F/4 ## A-B/4 C-D-E-F-:16:G-F/5 """ renderTest assert, "Time Signature based Beaming", code @multiStringTab: (assert) -> code = """ tabstave key=A strings=4 notes :q (5/2.5/3.7/4) $.a./b.$ :8 5h6/3 7/4 $.a>/b.$ notes :16 5h6/3 7/4 $.a>/b.$ options space=20 """ renderTest assert, "Bass Tab", code code = """ tabstave key=A strings=8 tuning=E/5,B/4,G/4,D/4,A/3,E/3,B/2,G/2 notes :q (5/2.5/3.7/8) :8 5h6/3 7/8 notes :16 5h6/3 7/7 """ renderTest assert, "8-string Tab", code @overrideFretNote: (assert) -> code = """ options stave-distance=30 space=20 options font-face=courier font-style=bold tabstave notation=true key=A time=5/4 notes :q 8/4 $8/4$ notes B@4_8/4 $B@4_8/4$ notes B@~4_8/4 $B@~4_8/4$ notes C@@5_8/4 $C@@5_8/4$ notes G##5_5/1 $G##5_5/1$ text .font=Times-15-italic,|8va """ renderTest assert, "Override Fret Note", code @mixedTuplets: (assert) -> code = """ tabstave notation=true tablature=false key=G time=4/4 notes :q E/5 :8 E/5 ^3,2^ :8 E/5 :q E/5 ^3,2^ notes :8 E-E-E/5 ^3^ ## E-E/5 ^3^ options space=20 """ renderTest assert, "Mixed Tuplets", code @accidentalStrategies: (assert) -> code = """ options player=true tempo=80 tabstave notation=true key=G time=4/4 notes :8 5-5-6-6-5-5-3-3/3 """ renderTest assert, "Standard Accidental Strategy", code code = """ options player=true tempo=80 accidentals=cautionary tabstave notation=true key=G time=4/4 notes :8 5-5-6-6-5-5-3-3/3 """ renderTest assert, "Cautionary Accidental Strategy", code @fingeringAndStrings: (assert) -> code = """ options space=40 player=true tempo=80 instrument=acoustic_guitar_nylon tabstave notation=true tablature=false key=G time=4/4 voice notes !octave-shift -1! notes :8 ## (D/4.G/4.D/5.G/5) notes $.fingering/4:r:f:4-3:r:f:3.$ notes $.fingering/4:l:s:1-3:r:s:2.$ notes :h (E/4.G/4.C/5.E/5) notes $.fingering/1:r:f:2-3:r:f:1.$ notes $.fingering/1:l:s:4-3:r:s:2.$ notes :q ## voice notes :8 G/3 $.fingering/1:r:f:2-1:r:s:6.$ notes :8 F/3 $.fingering/1:r:f:1-1:r:s:6.$ notes :q G/3 $.fingering/1:r:f:2-1:r:s:6.$ notes :q G/3 $.fingering/1:r:f:2-1:r:s:6.$ notes :q G/3 $.fingering/1:r:f:2-1:r:s:6.$ text .font=Arial-14-Bold,.-2 text :8,G,G/F,:h,Am/G options space=60 """ renderTest assert, "Fret Hand Fingering and String Numbers", code VexTabTests.Start()
[ { "context": "dapted from the no-trailing-spaces rule.\n# @author Greg Cochard\n###\n'use strict'\n\n{countBy} = require 'lodash'\n\n#", "end": 134, "score": 0.9997483491897583, "start": 122, "tag": "NAME", "value": "Greg Cochard" } ]
src/rules/no-multiple-empty-lines.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Disallows multiple blank lines. # implementation adapted from the no-trailing-spaces rule. # @author Greg Cochard ### 'use strict' {countBy} = require 'lodash' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow multiple empty lines' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/no-multiple-empty-lines' fixable: 'whitespace' schema: [ type: 'object' properties: max: type: 'integer' minimum: 0 maxEOF: type: 'integer' minimum: 0 maxBOF: type: 'integer' minimum: 0 required: ['max'] additionalProperties: no ] create: (context) -> # Use options.max or 2 as default max = 2 maxEOF = max maxBOF = max if context.options.length {max} = context.options[0] maxEOF = unless typeof context.options[0].maxEOF is 'undefined' context.options[0].maxEOF else max maxBOF = unless typeof context.options[0].maxBOF is 'undefined' context.options[0].maxBOF else max sourceCode = context.getSourceCode() # Swallow the final newline, as some editors add it automatically and we don't want it to cause an issue allLines = if sourceCode.lines[sourceCode.lines.length - 1] is '' sourceCode.lines.slice 0, -1 else sourceCode.lines templateLiteralLines = new Set() #-------------------------------------------------------------------------- # Public #-------------------------------------------------------------------------- TemplateLiteral: (node) -> node.quasis.forEach (literalPart) -> ignoredLine = literalPart.loc.start.line # Empty lines have a semantic meaning if they're inside template literals. Don't count these as empty lines. # Don't trust loc.end.line (since we're currently just +1'ing the last column of the inclusive location data) # while ignoredLine < literalPart.loc.end.line # templateLiteralLines.add ignoredLine # ignoredLine++ numNewlines = countBy(literalPart.value.raw)['\n'] ? 0 for [0...numNewlines] templateLiteralLines.add ignoredLine ignoredLine++ 'Program:exit': (node) -> allLines # Given a list of lines, first get a list of line numbers that are non-empty. .reduce( (nonEmptyLineNumbers, line, index) -> if line.trim() or templateLiteralLines.has index + 1 nonEmptyLineNumbers.push index + 1 nonEmptyLineNumbers , [] ) # Add a value at the end to allow trailing empty lines to be checked. .concat allLines.length + 1 # Given two line numbers of non-empty lines, report the lines between if the difference is too large. .reduce( (lastLineNumber, lineNumber) -> if lastLineNumber is 0 message = 'Too many blank lines at the beginning of file. Max of {{max}} allowed.' maxAllowed = maxBOF else if lineNumber is allLines.length + 1 message = 'Too many blank lines at the end of file. Max of {{max}} allowed.' maxAllowed = maxEOF else message = 'More than {{max}} blank {{pluralizedLines}} not allowed.' maxAllowed = max if lineNumber - lastLineNumber - 1 > maxAllowed context.report { node loc: start: line: lastLineNumber + 1, column: 0 end: line: lineNumber, column: 0 message data: max: maxAllowed pluralizedLines: if maxAllowed is 1 then 'line' else 'lines' fix: (fixer) -> rangeStart = sourceCode.getIndexFromLoc( line: lastLineNumber + 1, column: 0 ) ### # The end of the removal range is usually the start index of the next line. # However, at the end of the file there is no next line, so the end of the # range is just the length of the text. ### lineNumberAfterRemovedLines = lineNumber - maxAllowed rangeEnd = if lineNumberAfterRemovedLines <= allLines.length sourceCode.getIndexFromLoc( line: lineNumberAfterRemovedLines, column: 0 ) else sourceCode.text.length fixer.removeRange [rangeStart, rangeEnd] } lineNumber , 0 )
182222
###* # @fileoverview Disallows multiple blank lines. # implementation adapted from the no-trailing-spaces rule. # @author <NAME> ### 'use strict' {countBy} = require 'lodash' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow multiple empty lines' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/no-multiple-empty-lines' fixable: 'whitespace' schema: [ type: 'object' properties: max: type: 'integer' minimum: 0 maxEOF: type: 'integer' minimum: 0 maxBOF: type: 'integer' minimum: 0 required: ['max'] additionalProperties: no ] create: (context) -> # Use options.max or 2 as default max = 2 maxEOF = max maxBOF = max if context.options.length {max} = context.options[0] maxEOF = unless typeof context.options[0].maxEOF is 'undefined' context.options[0].maxEOF else max maxBOF = unless typeof context.options[0].maxBOF is 'undefined' context.options[0].maxBOF else max sourceCode = context.getSourceCode() # Swallow the final newline, as some editors add it automatically and we don't want it to cause an issue allLines = if sourceCode.lines[sourceCode.lines.length - 1] is '' sourceCode.lines.slice 0, -1 else sourceCode.lines templateLiteralLines = new Set() #-------------------------------------------------------------------------- # Public #-------------------------------------------------------------------------- TemplateLiteral: (node) -> node.quasis.forEach (literalPart) -> ignoredLine = literalPart.loc.start.line # Empty lines have a semantic meaning if they're inside template literals. Don't count these as empty lines. # Don't trust loc.end.line (since we're currently just +1'ing the last column of the inclusive location data) # while ignoredLine < literalPart.loc.end.line # templateLiteralLines.add ignoredLine # ignoredLine++ numNewlines = countBy(literalPart.value.raw)['\n'] ? 0 for [0...numNewlines] templateLiteralLines.add ignoredLine ignoredLine++ 'Program:exit': (node) -> allLines # Given a list of lines, first get a list of line numbers that are non-empty. .reduce( (nonEmptyLineNumbers, line, index) -> if line.trim() or templateLiteralLines.has index + 1 nonEmptyLineNumbers.push index + 1 nonEmptyLineNumbers , [] ) # Add a value at the end to allow trailing empty lines to be checked. .concat allLines.length + 1 # Given two line numbers of non-empty lines, report the lines between if the difference is too large. .reduce( (lastLineNumber, lineNumber) -> if lastLineNumber is 0 message = 'Too many blank lines at the beginning of file. Max of {{max}} allowed.' maxAllowed = maxBOF else if lineNumber is allLines.length + 1 message = 'Too many blank lines at the end of file. Max of {{max}} allowed.' maxAllowed = maxEOF else message = 'More than {{max}} blank {{pluralizedLines}} not allowed.' maxAllowed = max if lineNumber - lastLineNumber - 1 > maxAllowed context.report { node loc: start: line: lastLineNumber + 1, column: 0 end: line: lineNumber, column: 0 message data: max: maxAllowed pluralizedLines: if maxAllowed is 1 then 'line' else 'lines' fix: (fixer) -> rangeStart = sourceCode.getIndexFromLoc( line: lastLineNumber + 1, column: 0 ) ### # The end of the removal range is usually the start index of the next line. # However, at the end of the file there is no next line, so the end of the # range is just the length of the text. ### lineNumberAfterRemovedLines = lineNumber - maxAllowed rangeEnd = if lineNumberAfterRemovedLines <= allLines.length sourceCode.getIndexFromLoc( line: lineNumberAfterRemovedLines, column: 0 ) else sourceCode.text.length fixer.removeRange [rangeStart, rangeEnd] } lineNumber , 0 )
true
###* # @fileoverview Disallows multiple blank lines. # implementation adapted from the no-trailing-spaces rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' {countBy} = require 'lodash' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow multiple empty lines' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/no-multiple-empty-lines' fixable: 'whitespace' schema: [ type: 'object' properties: max: type: 'integer' minimum: 0 maxEOF: type: 'integer' minimum: 0 maxBOF: type: 'integer' minimum: 0 required: ['max'] additionalProperties: no ] create: (context) -> # Use options.max or 2 as default max = 2 maxEOF = max maxBOF = max if context.options.length {max} = context.options[0] maxEOF = unless typeof context.options[0].maxEOF is 'undefined' context.options[0].maxEOF else max maxBOF = unless typeof context.options[0].maxBOF is 'undefined' context.options[0].maxBOF else max sourceCode = context.getSourceCode() # Swallow the final newline, as some editors add it automatically and we don't want it to cause an issue allLines = if sourceCode.lines[sourceCode.lines.length - 1] is '' sourceCode.lines.slice 0, -1 else sourceCode.lines templateLiteralLines = new Set() #-------------------------------------------------------------------------- # Public #-------------------------------------------------------------------------- TemplateLiteral: (node) -> node.quasis.forEach (literalPart) -> ignoredLine = literalPart.loc.start.line # Empty lines have a semantic meaning if they're inside template literals. Don't count these as empty lines. # Don't trust loc.end.line (since we're currently just +1'ing the last column of the inclusive location data) # while ignoredLine < literalPart.loc.end.line # templateLiteralLines.add ignoredLine # ignoredLine++ numNewlines = countBy(literalPart.value.raw)['\n'] ? 0 for [0...numNewlines] templateLiteralLines.add ignoredLine ignoredLine++ 'Program:exit': (node) -> allLines # Given a list of lines, first get a list of line numbers that are non-empty. .reduce( (nonEmptyLineNumbers, line, index) -> if line.trim() or templateLiteralLines.has index + 1 nonEmptyLineNumbers.push index + 1 nonEmptyLineNumbers , [] ) # Add a value at the end to allow trailing empty lines to be checked. .concat allLines.length + 1 # Given two line numbers of non-empty lines, report the lines between if the difference is too large. .reduce( (lastLineNumber, lineNumber) -> if lastLineNumber is 0 message = 'Too many blank lines at the beginning of file. Max of {{max}} allowed.' maxAllowed = maxBOF else if lineNumber is allLines.length + 1 message = 'Too many blank lines at the end of file. Max of {{max}} allowed.' maxAllowed = maxEOF else message = 'More than {{max}} blank {{pluralizedLines}} not allowed.' maxAllowed = max if lineNumber - lastLineNumber - 1 > maxAllowed context.report { node loc: start: line: lastLineNumber + 1, column: 0 end: line: lineNumber, column: 0 message data: max: maxAllowed pluralizedLines: if maxAllowed is 1 then 'line' else 'lines' fix: (fixer) -> rangeStart = sourceCode.getIndexFromLoc( line: lastLineNumber + 1, column: 0 ) ### # The end of the removal range is usually the start index of the next line. # However, at the end of the file there is no next line, so the end of the # range is just the length of the text. ### lineNumberAfterRemovedLines = lineNumber - maxAllowed rangeEnd = if lineNumberAfterRemovedLines <= allLines.length sourceCode.getIndexFromLoc( line: lineNumberAfterRemovedLines, column: 0 ) else sourceCode.text.length fixer.removeRange [rangeStart, rangeEnd] } lineNumber , 0 )
[ { "context": "\n#\n# Commands:\n# hubot beat time\n#\n# Author:\n# Kevin L <kevin@stealsyour.pw>\n\ndateutil = require(\"dateut", "end": 184, "score": 0.9995102882385254, "start": 177, "tag": "NAME", "value": "Kevin L" }, { "context": "nds:\n# hubot beat time\n#\n# Author:\n# Kevin L <kevin@stealsyour.pw>\n\ndateutil = require(\"dateutil\")\n\ndateutil._forma", "end": 205, "score": 0.9999303221702576, "start": 186, "tag": "EMAIL", "value": "kevin@stealsyour.pw" } ]
src/beat-time.coffee
thatarchguy/hubot-beat-time
1
# Description: # Allows Hubot to tell the current time in .beats! # # Dependencies: # dateutil # # Configuration: # None # # Commands: # hubot beat time # # Author: # Kevin L <kevin@stealsyour.pw> dateutil = require("dateutil") dateutil._formats['B'] = (d) -> mo = 0 Math.round((d.getUTCHours() * 3600 + (d.getUTCMinutes() - mo + 60) * 60 + d.getUTCSeconds()) * 1000 / 86400) % 1000 module.exports = (robot) -> robot.respond /beat time/i, (msg) -> mydate = new Date() beats = dateutil.format( mydate, 'B' ) msg.send "@#{beats}"
199695
# Description: # Allows Hubot to tell the current time in .beats! # # Dependencies: # dateutil # # Configuration: # None # # Commands: # hubot beat time # # Author: # <NAME> <<EMAIL>> dateutil = require("dateutil") dateutil._formats['B'] = (d) -> mo = 0 Math.round((d.getUTCHours() * 3600 + (d.getUTCMinutes() - mo + 60) * 60 + d.getUTCSeconds()) * 1000 / 86400) % 1000 module.exports = (robot) -> robot.respond /beat time/i, (msg) -> mydate = new Date() beats = dateutil.format( mydate, 'B' ) msg.send "@#{beats}"
true
# Description: # Allows Hubot to tell the current time in .beats! # # Dependencies: # dateutil # # Configuration: # None # # Commands: # hubot beat time # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> dateutil = require("dateutil") dateutil._formats['B'] = (d) -> mo = 0 Math.round((d.getUTCHours() * 3600 + (d.getUTCMinutes() - mo + 60) * 60 + d.getUTCSeconds()) * 1000 / 86400) % 1000 module.exports = (robot) -> robot.respond /beat time/i, (msg) -> mydate = new Date() beats = dateutil.format( mydate, 'B' ) msg.send "@#{beats}"
[ { "context": "tro: 98}, {k: 'yo', more: 43}]\n [{k: 'yo', v: 'alice'}, {k: 'bob', v: 'katie'}, {k: 'a', qoux: 34}]\n])", "end": 2778, "score": 0.9474909901618958, "start": 2773, "tag": "NAME", "value": "alice" }, { "context": ": 43}]\n [{k: 'yo', v: 'alice'}, {k: 'bob', v: 'katie'}, {k: 'a', qoux: 34}]\n]), [\n [{k: 'a', num: 1", "end": 2802, "score": 0.980698823928833, "start": 2797, "tag": "NAME", "value": "katie" }, { "context": ": 34}]\n [{k: 'yo', v: more: 43}, {k: 'yo', v: 'alice'}]\n [{k: 'f', otro: 98}, undefined]\n [undef", "end": 2925, "score": 0.9199289679527283, "start": 2920, "tag": "NAME", "value": "alice" }, { "context": ": 'f', otro: 98}, undefined]\n [undefined, {k: 'bob', v: 'katie'}]\n]\n\nassert _.isEqual zip_sets_by(_.", "end": 2989, "score": 0.8965733647346497, "start": 2986, "tag": "NAME", "value": "bob" }, { "context": "o: 98}, undefined]\n [undefined, {k: 'bob', v: 'katie'}]\n]\n\nassert _.isEqual zip_sets_by(_.identity, [\n", "end": 3001, "score": 0.9889967441558838, "start": 2996, "tag": "NAME", "value": "katie" } ]
src/util.coffee
caffed/pagedraw
3,213
_ = require 'underscore' _l = require 'lodash' config = require './config' nodeUtil = require 'util' md5 = require 'blueimp-md5' exports.capitalize_first_char = (str) -> "#{str.slice(0,1).toUpperCase()}#{str.slice(1)}" exports.lowercase_first_char = (str) -> "#{str.slice(0,1).toLowerCase()}#{str.slice(1)}" exports.propLink = propLink = (obj, prop, onChange) -> value: obj[prop] requestChange: (newval) -> obj[prop] = newval onChange() exports.find_unused = find_unused = (existing_items, elem_gen, i = 0) -> if (candidate = elem_gen(i)) not in existing_items then candidate else find_unused(existing_items, elem_gen, i+1) # zip_dicts :: [{String: Object}] -> {String: [Object]} # An array of dictionaries -> A dictionary of arrays # assert zip_dicts([{a: 1, b: 2}, {a: 'foo', b: 'bar'}, {a: 'nyan', b: 'cat'}]) # == {a: [1, 'foo', 'nyan'], b: [2, 'bar', 'cat']} # assert zip_dicts([{a: 1, b: 2}, {a: 10, c: 99}]) # == {a: [1, 10], b: [2, undefined], c: [undefined, 99]} # assert zip_dicts([]) == {} # assert zip_dicts([{a: 1, b: 2, c: 3}]) == {a: [1], b: [2], c: [3]} exports.zip_dicts = zip_dicts = (dicts) -> all_keys = _l.uniq _l.flatten _l.map dicts, _l.keys return _l.fromPairs _l.map all_keys, (key) -> [key, _l.map(dicts, key)] # zip_sets_by :: (Object -> String) -> [Set Object] -> Set [Object] # where Set a = [a], but the order of the array has no meaning # zip_sets_by takes an ordered list of N sets with combined M unique elements and returns # a set of M ordered lists each of length N. zip_sets_by effectively takes the transpose # of the list of sets, with the wrinkle that since the sets are unordered, we have to # match up the corresponding elements. Elements in two sets correspond if they have the # same index() result. We want to return a set of lists where each list's objects are in # the same equivalence class under index(), and each element in the list came from the set # in the same ordinal position. That is, in each list in the set we return, the i-th # element of the list came from the i-th input set. If the i-th input set has no elements # in the right equivalence class, the value is `undefined`. If multiple elements in the # same input set are in the same equivalence class, one is selected. # index :: (Object -> String). `index` takes an element and returns a string # identifying the element. Each element of a set in will be matched with its # counterparts in the other sets with the same index(). # Technically an `index` is an underscore iteratee (http://underscorejs.org/#iteratee), # so index will often be a string. ### assert _.isEqual zip_sets_by('k', [ [{k: 'a', num: 100}, {k: 'f', otro: 98}, {k: 'yo', more: 43}] [{k: 'yo', v: 'alice'}, {k: 'bob', v: 'katie'}, {k: 'a', qoux: 34}] ]), [ [{k: 'a', num: 100}, {k: 'a', qoux: 34}] [{k: 'yo', v: more: 43}, {k: 'yo', v: 'alice'}] [{k: 'f', otro: 98}, undefined] [undefined, {k: 'bob', v: 'katie'}] ] assert _.isEqual zip_sets_by(_.identity, [ ['a', 'b', 'c', 'd'] ['b', 'z', 'q', 'c', 'b'] ]), [ ['a', undefined] ['b', 'b'] ['c', 'c'] ['d', undefined] [undefined, 'z'] [undefined, 'q'] ] ### exports.zip_sets_by = zip_sets_by = (index_key, sets) -> set_of_indexes = sets.map (set) -> _.indexBy set, index_key index_of_per_object_lists = zip_dicts set_of_indexes per_object_lists = _.values index_of_per_object_lists return per_object_lists # flatten_trees_preorder_to_depth_list :: [Tree] -> (Tree -> [Tree]) -> [{node: Tree, depth: Int}] # depths start at 0 # Fun fact: the *inverse* of this function, a depth-list -> tree, is the pre-processing step # indentation-aware languages like Python use to transform indented lines indentations to a # meaningful tree. exports.flatten_trees_preorder_to_depth_list = flatten_trees_preorder_to_depth_list = (roots, get_children_iteratee) -> get_children_fn = _l.iteratee(get_children_iteratee) depth_list = [] walk = (node, depth) -> depth_list.push({node, depth}) walk(child, depth + 1) for child in get_children_fn(node) walk(root, 0) for root in roots return depth_list # map_tree :: A -> (A -> [A]) -> (A -> [B] -> B) -> B # A and B are typically tree-ish types. With this approach, the types don't have to a-priori be structurally # trees, as long as you can provide a children_iteratee that returns the edges of a node as-if it were a tree. # More typically, this is just nice because we don't have to assume a .children, and can parameterize over any # concrete tree type. # children_iteratee is a lodash iteratee, so you can pass it the string 'children' to have this operate over a # tree where child nodes are a list off of the .children property # map_tree preserves the ordering of the children it's handed. You may, of course, reorder the children in the # children_iteratee, and we will preserve the reordering. _map_tree = (root, getChildren, fn) -> fn(root, getChildren(root).map((child) -> _map_tree(child, getChildren, fn))) exports.map_tree = map_tree = (root, children_iteratee, fn) -> _map_tree(root, _l.iteratee(children_iteratee), fn) # flatten_tree :: A -> (A -> [A]) -> [A] exports.flatten_tree = flatten_tree = (root, getChildren) -> accum = [] _flatten_tree(root, getChildren, accum) return accum _flatten_tree = (root, getChildren, accum) -> accum.push(root) _flatten_tree(child, getChildren, accum) for child in getChildren(root) # truth_table :: [Bool] -> String # truth_table maps a list of bools into a string with a 't' for every true and an # 'f' for every false. # assert truth_table([true, true, false]) = "ttf" # assert truth_table([false, false]) = "ff" # assert truth_table([true]) = "t" # assert truth_table([true, false, false, true]) = "tfft" # assert truth_table([true, true, true, true]) = "tttt" # assert truth_table([true, false]) = "tf" exports.truth_table = (bools) -> (bools.map (b) -> if b then 't' else f).join('') ## Tools for dealing with firebase's not-quite JSON shenanigans # The following are all unused in the codebase as of 2/11/2017, but they should work exports.dropEmpty = (n) -> if _l.isArray(n) or (_l.isObject(n) and n.prototype == undefined and n.constructor == Object) for key in _l.keys(n) if _l.isEmpty(n[key]) delete n[key] else dropEmpty(n[key]) exports.FixedSizeStack = class FixedSizeStack constructor: (@size) -> @data = [] push: (elem) -> @data.shift() if @data.length >= @size @data.push(elem) pop: -> @data.pop() peek: -> _l.last(@data) clear: -> @data = [] length: -> @data.length exports.firebase_safe_encode = firebase_safe_encode = (json) -> if _l.isArray(json) {t: 'a', v: json.map(firebase_safe_encode)} else if _l.isPlainObject(json) {t: 'o', v: _l.mapValues(json, firebase_safe_encode)} else if _l.isString(json) {t: 's', v: json} else if _l.isBoolean(json) {t: 'b', v: json} else if _l.isNumber(json) {t: 'i', v: json} else if json == null {t: 'e'} else throw new Error("unknown json type") exports.firebase_safe_decode = firebase_safe_decode = (json) -> return {} if not json?.t? switch json.t when 'a' new Array(json.v).map(firebase_safe_decode) when 'o' _l.mapValues(json.v, firebase_safe_decode) when 's' json.v when 'b' json.v when 'i' json.v when 'e' null else throw new Error("unknown type from firebase") exports.memoize_on = memoize_on = (cache, name, getter) -> return cache[name] ?= getter() exports.memoized_on = memoized_on = (indexer, expensive_fn) -> cache = {} index_fn = _l.iteratee(indexer) return -> index = index_fn(arguments...) return cache[index] ?= expensive_fn(arguments...) exports.parseSvg = (plain_text) -> try parsed_xml = (new DOMParser()).parseFromString(plain_text, "image/svg+xml") catch return null return if (svg = _l.head(parsed_xml.children))?.tagName == 'svg' then svg else null exports.getDimensionsFromParsedSvg = (parsed_svg) -> return {width: parsed_svg.width?.baseVal?.value ? 100, height: parsed_svg.height?.baseVal?.value ? 100} getDimensionsFromB64Png = (base64) -> header = atob(base64.slice(0, 50)).slice(16,24) uint8 = Uint8Array.from(header, (c) => c.charCodeAt(0)) dataView = new DataView(uint8.buffer) return { width: dataView.getInt32(0), height: dataView.getInt32(4) } # Expects dataUri to be of the form data:image/png;base64,encoded_image exports.getPngDimensionsFromDataUri = getPngDimensionsFromDataUri = (dataUri) -> encoded_image = dataUri.split(',')[1] return getDimensionsFromB64Png(encoded_image) # Expects pngBlob to be a Web API Blob exports.getPngUriFromBlob = getPngUriFromBlob = (pngBlob, callback) -> reader = new FileReader() reader.onload = (event) => png_as_url = event.target.result callback(png_as_url) reader.readAsDataURL(pngBlob) # Expects pngBlob to be a Web API Blob exports.getPngDimensions = getPngDimensions = (pngBlob, callback) -> getPngUriFromBlob pngBlob, (dataUri) -> callback(getPngDimensionsFromDataUri dataUri) exports.isPermutation = (arr1, arr2) -> arr1.length == arr2.length and _l.intersection(arr1, arr2).length == arr1.length exports.splice = (arr, args...) -> ret = arr.slice() ret.splice(args...) return ret exports.log_assert = log_assert = (expr) -> error = null try passes = expr() error = new Error(expr.toString()) if not passes catch e passes = false error = e if not passes return config.assertHandler(expr) if config.assertHandler? if config.environment == 'production' track_error(error, 'Assertion failed: ' + error.message) else console.assert(false, expr.toString()) exports.prod_assert = log_assert # Use this only if expr is expensive to compute. Favor log_assert instead. exports.assert = assert = (expr) -> # FIXME these assertions should go somewhere or something # FIXME2: These asserts throw in all cases but the editor in production # Right now they will also throw in the compileserver since it doesnt get config.environment return if config.asserts == false or config.environment == 'production' try passes = expr() catch passes = false if not passes return config.assertHandler(expr) if config.assertHandler? # debugger # throw console.assert(false, expr.toString()) exports.log = (msg, json) -> console.log nodeUtil.inspect(_l.extend({}, json, {msg}), {depth: 10}) registeredErrorTracker = undefined exports.registerErrorTracker = (rollbar) -> registeredErrorTracker = rollbar.handleErrorWithPayloadData # Track a warning without throwing it exports.track_warning = track_warning = (msg, json) -> console.warn(msg, json) return if config.environment != 'production' if registeredErrorTracker? return registeredErrorTracker(new Error(msg), {level: 'warning', json}) else if window?.Rollbar? window.Rollbar.warning(msg, json) else console.warn('No registered error tracker') exports.track_error = track_error = (error, msg) -> console.warn(msg, error) return if config.environment != 'production' if registeredErrorTracker? return registeredErrorTracker(error, {level: 'error', json: {msg}}) else if window?.Rollbar? window.Rollbar.error(msg, error) else console.warn('No registered error tracker') exports.collisions = (list, iteratee = _l.identity) -> set = new Set() collisions = [] list.forEach (elem) -> if set.has((it = iteratee(elem))) collisions.push(it) set.add(it) return collisions exports.find_connected = (start_points, get_neighbors) -> seen = new Set() explore = (node) -> return if seen.has(node) seen.add(node) explore(neighbor) for neighbor in get_neighbors(node) explore(start_point) for start_point in start_points return Array.from(seen) exports.dfs = dfs = (node, match, get_next) -> if match(node) return node else for child in get_next(node) found = dfs(child, match, get_next) return found if found? return undefined exports.distanceSquared = (coordsA, coordsB) -> Math.pow(coordsB[1] - coordsA[1], 2) + Math.pow(coordsB[0] - coordsA[0], 2) exports.throttled_map = (max_parallel, base, map_fn) -> new Promise (resolve, reject) -> [i, in_flight_promises] = [0, 0] [results, errors] = [new Array(base.length), []] do fire = -> while i < base.length and in_flight_promises < max_parallel # Avoid the javascript loop variable hoisting issue with i. Look up the `do` syntax for coffeescript. [curr, i] = [i, i + 1] do (curr) -> in_flight_promises += 1 map_fn(base[curr]).then( ((val) -> results[curr] = val), ((err) -> errors.push(err)) ).then -> in_flight_promises -= 1 fire() if in_flight_promises == 0 and i >= base.length # the i >= base.length should be redundant return resolve(results) unless not _l.isEmpty(errors) return reject(errors) if not _l.isEmpty(errors) exports.hash_string = (str) -> md5(str) # uninvoked_promise :: (-> (A | Promise A)) -> (Promise A, () -> Promise A) exports.uninvoked_promise = (action) -> resolver = null promise = new Promise (accept, reject) -> resolver = {accept, reject} fire = -> fired = Promise.resolve().then(action) resolver.accept(fired) return fired [promise, fire] exports.CV = -> resolve = null p = new Promise (accept, reject) -> resolve = {accept, reject} return [p, resolve] # after :: (() -> ()) -> (). `after` takes a callback, instead of a promise, because promises have # less fine grained control over scheduling; the .then schedules a microtask, whereas a callback is # sync with whatever invokes it. Feel free to pass {after: (cb) -> Promise.resolve().then => cb()}. exports.if_changed = if_changed = ({value, compare, after}) -> new Promise (resolve, reject) -> original_value = value() after -> changed = compare(original_value, value()) resolve(changed) # For Perf. Use when you're sure you know which blocks can be mutated by this valueLink exports.propLinkWithMutatedBlocks = propLinkWithMutatedBlocks = (object, attr, onChange, mutated_blocks) -> assert -> mutated_blocks?.length > 0 propLink(object, attr, => onChange({mutated_blocks: _l.keyBy(_l.map mutated_blocks, 'uniqueKey')})) # sorted_buckets :: [a] -> (a -> Equalable) -> [[a]] # where Equalable is a type that supports == in a meaningful way, like string or number # The second argument is a lodash interatee, so it can be a function, or a string naming a member like # sorted_buckets([{top: 12, ...}, {top: 11, ...}, {top: 12, ...}, {top: 119, ...}], 'top') # Could be implemented differently to take an (a -> a -> Bool) as a second argument. # sorted_buckets([3, 4, 2, 5, 6, 2, 2.3, 4.1, 5, 5], _l.identity) == [[2, 2], [2.3], [3], [4], [4.1], [5, 5, 5], [6]] # sorted_buckets([3, 4, 2, 5, 6, 2, 2.3, 4.1, 5, 5], ((o) -> Math.floor(o))) == [[2, 2, 2.3], [3], [4, 4.1], [5, 5, 5], [6]] # Does not make any guarantees about the order elements within a bucket exports.sorted_buckets = sorted_buckets = (lst, it) -> fn = _l.iteratee(it) sorted = _l.sortBy(lst, fn) current_value = {} # unequalable sentinal buckets = [] for elem in sorted next_value = fn(elem) buckets.push([]) if current_value != next_value _l.last(buckets).push(elem) current_value = next_value return buckets
15770
_ = require 'underscore' _l = require 'lodash' config = require './config' nodeUtil = require 'util' md5 = require 'blueimp-md5' exports.capitalize_first_char = (str) -> "#{str.slice(0,1).toUpperCase()}#{str.slice(1)}" exports.lowercase_first_char = (str) -> "#{str.slice(0,1).toLowerCase()}#{str.slice(1)}" exports.propLink = propLink = (obj, prop, onChange) -> value: obj[prop] requestChange: (newval) -> obj[prop] = newval onChange() exports.find_unused = find_unused = (existing_items, elem_gen, i = 0) -> if (candidate = elem_gen(i)) not in existing_items then candidate else find_unused(existing_items, elem_gen, i+1) # zip_dicts :: [{String: Object}] -> {String: [Object]} # An array of dictionaries -> A dictionary of arrays # assert zip_dicts([{a: 1, b: 2}, {a: 'foo', b: 'bar'}, {a: 'nyan', b: 'cat'}]) # == {a: [1, 'foo', 'nyan'], b: [2, 'bar', 'cat']} # assert zip_dicts([{a: 1, b: 2}, {a: 10, c: 99}]) # == {a: [1, 10], b: [2, undefined], c: [undefined, 99]} # assert zip_dicts([]) == {} # assert zip_dicts([{a: 1, b: 2, c: 3}]) == {a: [1], b: [2], c: [3]} exports.zip_dicts = zip_dicts = (dicts) -> all_keys = _l.uniq _l.flatten _l.map dicts, _l.keys return _l.fromPairs _l.map all_keys, (key) -> [key, _l.map(dicts, key)] # zip_sets_by :: (Object -> String) -> [Set Object] -> Set [Object] # where Set a = [a], but the order of the array has no meaning # zip_sets_by takes an ordered list of N sets with combined M unique elements and returns # a set of M ordered lists each of length N. zip_sets_by effectively takes the transpose # of the list of sets, with the wrinkle that since the sets are unordered, we have to # match up the corresponding elements. Elements in two sets correspond if they have the # same index() result. We want to return a set of lists where each list's objects are in # the same equivalence class under index(), and each element in the list came from the set # in the same ordinal position. That is, in each list in the set we return, the i-th # element of the list came from the i-th input set. If the i-th input set has no elements # in the right equivalence class, the value is `undefined`. If multiple elements in the # same input set are in the same equivalence class, one is selected. # index :: (Object -> String). `index` takes an element and returns a string # identifying the element. Each element of a set in will be matched with its # counterparts in the other sets with the same index(). # Technically an `index` is an underscore iteratee (http://underscorejs.org/#iteratee), # so index will often be a string. ### assert _.isEqual zip_sets_by('k', [ [{k: 'a', num: 100}, {k: 'f', otro: 98}, {k: 'yo', more: 43}] [{k: 'yo', v: '<NAME>'}, {k: 'bob', v: '<NAME>'}, {k: 'a', qoux: 34}] ]), [ [{k: 'a', num: 100}, {k: 'a', qoux: 34}] [{k: 'yo', v: more: 43}, {k: 'yo', v: '<NAME>'}] [{k: 'f', otro: 98}, undefined] [undefined, {k: '<NAME>', v: '<NAME>'}] ] assert _.isEqual zip_sets_by(_.identity, [ ['a', 'b', 'c', 'd'] ['b', 'z', 'q', 'c', 'b'] ]), [ ['a', undefined] ['b', 'b'] ['c', 'c'] ['d', undefined] [undefined, 'z'] [undefined, 'q'] ] ### exports.zip_sets_by = zip_sets_by = (index_key, sets) -> set_of_indexes = sets.map (set) -> _.indexBy set, index_key index_of_per_object_lists = zip_dicts set_of_indexes per_object_lists = _.values index_of_per_object_lists return per_object_lists # flatten_trees_preorder_to_depth_list :: [Tree] -> (Tree -> [Tree]) -> [{node: Tree, depth: Int}] # depths start at 0 # Fun fact: the *inverse* of this function, a depth-list -> tree, is the pre-processing step # indentation-aware languages like Python use to transform indented lines indentations to a # meaningful tree. exports.flatten_trees_preorder_to_depth_list = flatten_trees_preorder_to_depth_list = (roots, get_children_iteratee) -> get_children_fn = _l.iteratee(get_children_iteratee) depth_list = [] walk = (node, depth) -> depth_list.push({node, depth}) walk(child, depth + 1) for child in get_children_fn(node) walk(root, 0) for root in roots return depth_list # map_tree :: A -> (A -> [A]) -> (A -> [B] -> B) -> B # A and B are typically tree-ish types. With this approach, the types don't have to a-priori be structurally # trees, as long as you can provide a children_iteratee that returns the edges of a node as-if it were a tree. # More typically, this is just nice because we don't have to assume a .children, and can parameterize over any # concrete tree type. # children_iteratee is a lodash iteratee, so you can pass it the string 'children' to have this operate over a # tree where child nodes are a list off of the .children property # map_tree preserves the ordering of the children it's handed. You may, of course, reorder the children in the # children_iteratee, and we will preserve the reordering. _map_tree = (root, getChildren, fn) -> fn(root, getChildren(root).map((child) -> _map_tree(child, getChildren, fn))) exports.map_tree = map_tree = (root, children_iteratee, fn) -> _map_tree(root, _l.iteratee(children_iteratee), fn) # flatten_tree :: A -> (A -> [A]) -> [A] exports.flatten_tree = flatten_tree = (root, getChildren) -> accum = [] _flatten_tree(root, getChildren, accum) return accum _flatten_tree = (root, getChildren, accum) -> accum.push(root) _flatten_tree(child, getChildren, accum) for child in getChildren(root) # truth_table :: [Bool] -> String # truth_table maps a list of bools into a string with a 't' for every true and an # 'f' for every false. # assert truth_table([true, true, false]) = "ttf" # assert truth_table([false, false]) = "ff" # assert truth_table([true]) = "t" # assert truth_table([true, false, false, true]) = "tfft" # assert truth_table([true, true, true, true]) = "tttt" # assert truth_table([true, false]) = "tf" exports.truth_table = (bools) -> (bools.map (b) -> if b then 't' else f).join('') ## Tools for dealing with firebase's not-quite JSON shenanigans # The following are all unused in the codebase as of 2/11/2017, but they should work exports.dropEmpty = (n) -> if _l.isArray(n) or (_l.isObject(n) and n.prototype == undefined and n.constructor == Object) for key in _l.keys(n) if _l.isEmpty(n[key]) delete n[key] else dropEmpty(n[key]) exports.FixedSizeStack = class FixedSizeStack constructor: (@size) -> @data = [] push: (elem) -> @data.shift() if @data.length >= @size @data.push(elem) pop: -> @data.pop() peek: -> _l.last(@data) clear: -> @data = [] length: -> @data.length exports.firebase_safe_encode = firebase_safe_encode = (json) -> if _l.isArray(json) {t: 'a', v: json.map(firebase_safe_encode)} else if _l.isPlainObject(json) {t: 'o', v: _l.mapValues(json, firebase_safe_encode)} else if _l.isString(json) {t: 's', v: json} else if _l.isBoolean(json) {t: 'b', v: json} else if _l.isNumber(json) {t: 'i', v: json} else if json == null {t: 'e'} else throw new Error("unknown json type") exports.firebase_safe_decode = firebase_safe_decode = (json) -> return {} if not json?.t? switch json.t when 'a' new Array(json.v).map(firebase_safe_decode) when 'o' _l.mapValues(json.v, firebase_safe_decode) when 's' json.v when 'b' json.v when 'i' json.v when 'e' null else throw new Error("unknown type from firebase") exports.memoize_on = memoize_on = (cache, name, getter) -> return cache[name] ?= getter() exports.memoized_on = memoized_on = (indexer, expensive_fn) -> cache = {} index_fn = _l.iteratee(indexer) return -> index = index_fn(arguments...) return cache[index] ?= expensive_fn(arguments...) exports.parseSvg = (plain_text) -> try parsed_xml = (new DOMParser()).parseFromString(plain_text, "image/svg+xml") catch return null return if (svg = _l.head(parsed_xml.children))?.tagName == 'svg' then svg else null exports.getDimensionsFromParsedSvg = (parsed_svg) -> return {width: parsed_svg.width?.baseVal?.value ? 100, height: parsed_svg.height?.baseVal?.value ? 100} getDimensionsFromB64Png = (base64) -> header = atob(base64.slice(0, 50)).slice(16,24) uint8 = Uint8Array.from(header, (c) => c.charCodeAt(0)) dataView = new DataView(uint8.buffer) return { width: dataView.getInt32(0), height: dataView.getInt32(4) } # Expects dataUri to be of the form data:image/png;base64,encoded_image exports.getPngDimensionsFromDataUri = getPngDimensionsFromDataUri = (dataUri) -> encoded_image = dataUri.split(',')[1] return getDimensionsFromB64Png(encoded_image) # Expects pngBlob to be a Web API Blob exports.getPngUriFromBlob = getPngUriFromBlob = (pngBlob, callback) -> reader = new FileReader() reader.onload = (event) => png_as_url = event.target.result callback(png_as_url) reader.readAsDataURL(pngBlob) # Expects pngBlob to be a Web API Blob exports.getPngDimensions = getPngDimensions = (pngBlob, callback) -> getPngUriFromBlob pngBlob, (dataUri) -> callback(getPngDimensionsFromDataUri dataUri) exports.isPermutation = (arr1, arr2) -> arr1.length == arr2.length and _l.intersection(arr1, arr2).length == arr1.length exports.splice = (arr, args...) -> ret = arr.slice() ret.splice(args...) return ret exports.log_assert = log_assert = (expr) -> error = null try passes = expr() error = new Error(expr.toString()) if not passes catch e passes = false error = e if not passes return config.assertHandler(expr) if config.assertHandler? if config.environment == 'production' track_error(error, 'Assertion failed: ' + error.message) else console.assert(false, expr.toString()) exports.prod_assert = log_assert # Use this only if expr is expensive to compute. Favor log_assert instead. exports.assert = assert = (expr) -> # FIXME these assertions should go somewhere or something # FIXME2: These asserts throw in all cases but the editor in production # Right now they will also throw in the compileserver since it doesnt get config.environment return if config.asserts == false or config.environment == 'production' try passes = expr() catch passes = false if not passes return config.assertHandler(expr) if config.assertHandler? # debugger # throw console.assert(false, expr.toString()) exports.log = (msg, json) -> console.log nodeUtil.inspect(_l.extend({}, json, {msg}), {depth: 10}) registeredErrorTracker = undefined exports.registerErrorTracker = (rollbar) -> registeredErrorTracker = rollbar.handleErrorWithPayloadData # Track a warning without throwing it exports.track_warning = track_warning = (msg, json) -> console.warn(msg, json) return if config.environment != 'production' if registeredErrorTracker? return registeredErrorTracker(new Error(msg), {level: 'warning', json}) else if window?.Rollbar? window.Rollbar.warning(msg, json) else console.warn('No registered error tracker') exports.track_error = track_error = (error, msg) -> console.warn(msg, error) return if config.environment != 'production' if registeredErrorTracker? return registeredErrorTracker(error, {level: 'error', json: {msg}}) else if window?.Rollbar? window.Rollbar.error(msg, error) else console.warn('No registered error tracker') exports.collisions = (list, iteratee = _l.identity) -> set = new Set() collisions = [] list.forEach (elem) -> if set.has((it = iteratee(elem))) collisions.push(it) set.add(it) return collisions exports.find_connected = (start_points, get_neighbors) -> seen = new Set() explore = (node) -> return if seen.has(node) seen.add(node) explore(neighbor) for neighbor in get_neighbors(node) explore(start_point) for start_point in start_points return Array.from(seen) exports.dfs = dfs = (node, match, get_next) -> if match(node) return node else for child in get_next(node) found = dfs(child, match, get_next) return found if found? return undefined exports.distanceSquared = (coordsA, coordsB) -> Math.pow(coordsB[1] - coordsA[1], 2) + Math.pow(coordsB[0] - coordsA[0], 2) exports.throttled_map = (max_parallel, base, map_fn) -> new Promise (resolve, reject) -> [i, in_flight_promises] = [0, 0] [results, errors] = [new Array(base.length), []] do fire = -> while i < base.length and in_flight_promises < max_parallel # Avoid the javascript loop variable hoisting issue with i. Look up the `do` syntax for coffeescript. [curr, i] = [i, i + 1] do (curr) -> in_flight_promises += 1 map_fn(base[curr]).then( ((val) -> results[curr] = val), ((err) -> errors.push(err)) ).then -> in_flight_promises -= 1 fire() if in_flight_promises == 0 and i >= base.length # the i >= base.length should be redundant return resolve(results) unless not _l.isEmpty(errors) return reject(errors) if not _l.isEmpty(errors) exports.hash_string = (str) -> md5(str) # uninvoked_promise :: (-> (A | Promise A)) -> (Promise A, () -> Promise A) exports.uninvoked_promise = (action) -> resolver = null promise = new Promise (accept, reject) -> resolver = {accept, reject} fire = -> fired = Promise.resolve().then(action) resolver.accept(fired) return fired [promise, fire] exports.CV = -> resolve = null p = new Promise (accept, reject) -> resolve = {accept, reject} return [p, resolve] # after :: (() -> ()) -> (). `after` takes a callback, instead of a promise, because promises have # less fine grained control over scheduling; the .then schedules a microtask, whereas a callback is # sync with whatever invokes it. Feel free to pass {after: (cb) -> Promise.resolve().then => cb()}. exports.if_changed = if_changed = ({value, compare, after}) -> new Promise (resolve, reject) -> original_value = value() after -> changed = compare(original_value, value()) resolve(changed) # For Perf. Use when you're sure you know which blocks can be mutated by this valueLink exports.propLinkWithMutatedBlocks = propLinkWithMutatedBlocks = (object, attr, onChange, mutated_blocks) -> assert -> mutated_blocks?.length > 0 propLink(object, attr, => onChange({mutated_blocks: _l.keyBy(_l.map mutated_blocks, 'uniqueKey')})) # sorted_buckets :: [a] -> (a -> Equalable) -> [[a]] # where Equalable is a type that supports == in a meaningful way, like string or number # The second argument is a lodash interatee, so it can be a function, or a string naming a member like # sorted_buckets([{top: 12, ...}, {top: 11, ...}, {top: 12, ...}, {top: 119, ...}], 'top') # Could be implemented differently to take an (a -> a -> Bool) as a second argument. # sorted_buckets([3, 4, 2, 5, 6, 2, 2.3, 4.1, 5, 5], _l.identity) == [[2, 2], [2.3], [3], [4], [4.1], [5, 5, 5], [6]] # sorted_buckets([3, 4, 2, 5, 6, 2, 2.3, 4.1, 5, 5], ((o) -> Math.floor(o))) == [[2, 2, 2.3], [3], [4, 4.1], [5, 5, 5], [6]] # Does not make any guarantees about the order elements within a bucket exports.sorted_buckets = sorted_buckets = (lst, it) -> fn = _l.iteratee(it) sorted = _l.sortBy(lst, fn) current_value = {} # unequalable sentinal buckets = [] for elem in sorted next_value = fn(elem) buckets.push([]) if current_value != next_value _l.last(buckets).push(elem) current_value = next_value return buckets
true
_ = require 'underscore' _l = require 'lodash' config = require './config' nodeUtil = require 'util' md5 = require 'blueimp-md5' exports.capitalize_first_char = (str) -> "#{str.slice(0,1).toUpperCase()}#{str.slice(1)}" exports.lowercase_first_char = (str) -> "#{str.slice(0,1).toLowerCase()}#{str.slice(1)}" exports.propLink = propLink = (obj, prop, onChange) -> value: obj[prop] requestChange: (newval) -> obj[prop] = newval onChange() exports.find_unused = find_unused = (existing_items, elem_gen, i = 0) -> if (candidate = elem_gen(i)) not in existing_items then candidate else find_unused(existing_items, elem_gen, i+1) # zip_dicts :: [{String: Object}] -> {String: [Object]} # An array of dictionaries -> A dictionary of arrays # assert zip_dicts([{a: 1, b: 2}, {a: 'foo', b: 'bar'}, {a: 'nyan', b: 'cat'}]) # == {a: [1, 'foo', 'nyan'], b: [2, 'bar', 'cat']} # assert zip_dicts([{a: 1, b: 2}, {a: 10, c: 99}]) # == {a: [1, 10], b: [2, undefined], c: [undefined, 99]} # assert zip_dicts([]) == {} # assert zip_dicts([{a: 1, b: 2, c: 3}]) == {a: [1], b: [2], c: [3]} exports.zip_dicts = zip_dicts = (dicts) -> all_keys = _l.uniq _l.flatten _l.map dicts, _l.keys return _l.fromPairs _l.map all_keys, (key) -> [key, _l.map(dicts, key)] # zip_sets_by :: (Object -> String) -> [Set Object] -> Set [Object] # where Set a = [a], but the order of the array has no meaning # zip_sets_by takes an ordered list of N sets with combined M unique elements and returns # a set of M ordered lists each of length N. zip_sets_by effectively takes the transpose # of the list of sets, with the wrinkle that since the sets are unordered, we have to # match up the corresponding elements. Elements in two sets correspond if they have the # same index() result. We want to return a set of lists where each list's objects are in # the same equivalence class under index(), and each element in the list came from the set # in the same ordinal position. That is, in each list in the set we return, the i-th # element of the list came from the i-th input set. If the i-th input set has no elements # in the right equivalence class, the value is `undefined`. If multiple elements in the # same input set are in the same equivalence class, one is selected. # index :: (Object -> String). `index` takes an element and returns a string # identifying the element. Each element of a set in will be matched with its # counterparts in the other sets with the same index(). # Technically an `index` is an underscore iteratee (http://underscorejs.org/#iteratee), # so index will often be a string. ### assert _.isEqual zip_sets_by('k', [ [{k: 'a', num: 100}, {k: 'f', otro: 98}, {k: 'yo', more: 43}] [{k: 'yo', v: 'PI:NAME:<NAME>END_PI'}, {k: 'bob', v: 'PI:NAME:<NAME>END_PI'}, {k: 'a', qoux: 34}] ]), [ [{k: 'a', num: 100}, {k: 'a', qoux: 34}] [{k: 'yo', v: more: 43}, {k: 'yo', v: 'PI:NAME:<NAME>END_PI'}] [{k: 'f', otro: 98}, undefined] [undefined, {k: 'PI:NAME:<NAME>END_PI', v: 'PI:NAME:<NAME>END_PI'}] ] assert _.isEqual zip_sets_by(_.identity, [ ['a', 'b', 'c', 'd'] ['b', 'z', 'q', 'c', 'b'] ]), [ ['a', undefined] ['b', 'b'] ['c', 'c'] ['d', undefined] [undefined, 'z'] [undefined, 'q'] ] ### exports.zip_sets_by = zip_sets_by = (index_key, sets) -> set_of_indexes = sets.map (set) -> _.indexBy set, index_key index_of_per_object_lists = zip_dicts set_of_indexes per_object_lists = _.values index_of_per_object_lists return per_object_lists # flatten_trees_preorder_to_depth_list :: [Tree] -> (Tree -> [Tree]) -> [{node: Tree, depth: Int}] # depths start at 0 # Fun fact: the *inverse* of this function, a depth-list -> tree, is the pre-processing step # indentation-aware languages like Python use to transform indented lines indentations to a # meaningful tree. exports.flatten_trees_preorder_to_depth_list = flatten_trees_preorder_to_depth_list = (roots, get_children_iteratee) -> get_children_fn = _l.iteratee(get_children_iteratee) depth_list = [] walk = (node, depth) -> depth_list.push({node, depth}) walk(child, depth + 1) for child in get_children_fn(node) walk(root, 0) for root in roots return depth_list # map_tree :: A -> (A -> [A]) -> (A -> [B] -> B) -> B # A and B are typically tree-ish types. With this approach, the types don't have to a-priori be structurally # trees, as long as you can provide a children_iteratee that returns the edges of a node as-if it were a tree. # More typically, this is just nice because we don't have to assume a .children, and can parameterize over any # concrete tree type. # children_iteratee is a lodash iteratee, so you can pass it the string 'children' to have this operate over a # tree where child nodes are a list off of the .children property # map_tree preserves the ordering of the children it's handed. You may, of course, reorder the children in the # children_iteratee, and we will preserve the reordering. _map_tree = (root, getChildren, fn) -> fn(root, getChildren(root).map((child) -> _map_tree(child, getChildren, fn))) exports.map_tree = map_tree = (root, children_iteratee, fn) -> _map_tree(root, _l.iteratee(children_iteratee), fn) # flatten_tree :: A -> (A -> [A]) -> [A] exports.flatten_tree = flatten_tree = (root, getChildren) -> accum = [] _flatten_tree(root, getChildren, accum) return accum _flatten_tree = (root, getChildren, accum) -> accum.push(root) _flatten_tree(child, getChildren, accum) for child in getChildren(root) # truth_table :: [Bool] -> String # truth_table maps a list of bools into a string with a 't' for every true and an # 'f' for every false. # assert truth_table([true, true, false]) = "ttf" # assert truth_table([false, false]) = "ff" # assert truth_table([true]) = "t" # assert truth_table([true, false, false, true]) = "tfft" # assert truth_table([true, true, true, true]) = "tttt" # assert truth_table([true, false]) = "tf" exports.truth_table = (bools) -> (bools.map (b) -> if b then 't' else f).join('') ## Tools for dealing with firebase's not-quite JSON shenanigans # The following are all unused in the codebase as of 2/11/2017, but they should work exports.dropEmpty = (n) -> if _l.isArray(n) or (_l.isObject(n) and n.prototype == undefined and n.constructor == Object) for key in _l.keys(n) if _l.isEmpty(n[key]) delete n[key] else dropEmpty(n[key]) exports.FixedSizeStack = class FixedSizeStack constructor: (@size) -> @data = [] push: (elem) -> @data.shift() if @data.length >= @size @data.push(elem) pop: -> @data.pop() peek: -> _l.last(@data) clear: -> @data = [] length: -> @data.length exports.firebase_safe_encode = firebase_safe_encode = (json) -> if _l.isArray(json) {t: 'a', v: json.map(firebase_safe_encode)} else if _l.isPlainObject(json) {t: 'o', v: _l.mapValues(json, firebase_safe_encode)} else if _l.isString(json) {t: 's', v: json} else if _l.isBoolean(json) {t: 'b', v: json} else if _l.isNumber(json) {t: 'i', v: json} else if json == null {t: 'e'} else throw new Error("unknown json type") exports.firebase_safe_decode = firebase_safe_decode = (json) -> return {} if not json?.t? switch json.t when 'a' new Array(json.v).map(firebase_safe_decode) when 'o' _l.mapValues(json.v, firebase_safe_decode) when 's' json.v when 'b' json.v when 'i' json.v when 'e' null else throw new Error("unknown type from firebase") exports.memoize_on = memoize_on = (cache, name, getter) -> return cache[name] ?= getter() exports.memoized_on = memoized_on = (indexer, expensive_fn) -> cache = {} index_fn = _l.iteratee(indexer) return -> index = index_fn(arguments...) return cache[index] ?= expensive_fn(arguments...) exports.parseSvg = (plain_text) -> try parsed_xml = (new DOMParser()).parseFromString(plain_text, "image/svg+xml") catch return null return if (svg = _l.head(parsed_xml.children))?.tagName == 'svg' then svg else null exports.getDimensionsFromParsedSvg = (parsed_svg) -> return {width: parsed_svg.width?.baseVal?.value ? 100, height: parsed_svg.height?.baseVal?.value ? 100} getDimensionsFromB64Png = (base64) -> header = atob(base64.slice(0, 50)).slice(16,24) uint8 = Uint8Array.from(header, (c) => c.charCodeAt(0)) dataView = new DataView(uint8.buffer) return { width: dataView.getInt32(0), height: dataView.getInt32(4) } # Expects dataUri to be of the form data:image/png;base64,encoded_image exports.getPngDimensionsFromDataUri = getPngDimensionsFromDataUri = (dataUri) -> encoded_image = dataUri.split(',')[1] return getDimensionsFromB64Png(encoded_image) # Expects pngBlob to be a Web API Blob exports.getPngUriFromBlob = getPngUriFromBlob = (pngBlob, callback) -> reader = new FileReader() reader.onload = (event) => png_as_url = event.target.result callback(png_as_url) reader.readAsDataURL(pngBlob) # Expects pngBlob to be a Web API Blob exports.getPngDimensions = getPngDimensions = (pngBlob, callback) -> getPngUriFromBlob pngBlob, (dataUri) -> callback(getPngDimensionsFromDataUri dataUri) exports.isPermutation = (arr1, arr2) -> arr1.length == arr2.length and _l.intersection(arr1, arr2).length == arr1.length exports.splice = (arr, args...) -> ret = arr.slice() ret.splice(args...) return ret exports.log_assert = log_assert = (expr) -> error = null try passes = expr() error = new Error(expr.toString()) if not passes catch e passes = false error = e if not passes return config.assertHandler(expr) if config.assertHandler? if config.environment == 'production' track_error(error, 'Assertion failed: ' + error.message) else console.assert(false, expr.toString()) exports.prod_assert = log_assert # Use this only if expr is expensive to compute. Favor log_assert instead. exports.assert = assert = (expr) -> # FIXME these assertions should go somewhere or something # FIXME2: These asserts throw in all cases but the editor in production # Right now they will also throw in the compileserver since it doesnt get config.environment return if config.asserts == false or config.environment == 'production' try passes = expr() catch passes = false if not passes return config.assertHandler(expr) if config.assertHandler? # debugger # throw console.assert(false, expr.toString()) exports.log = (msg, json) -> console.log nodeUtil.inspect(_l.extend({}, json, {msg}), {depth: 10}) registeredErrorTracker = undefined exports.registerErrorTracker = (rollbar) -> registeredErrorTracker = rollbar.handleErrorWithPayloadData # Track a warning without throwing it exports.track_warning = track_warning = (msg, json) -> console.warn(msg, json) return if config.environment != 'production' if registeredErrorTracker? return registeredErrorTracker(new Error(msg), {level: 'warning', json}) else if window?.Rollbar? window.Rollbar.warning(msg, json) else console.warn('No registered error tracker') exports.track_error = track_error = (error, msg) -> console.warn(msg, error) return if config.environment != 'production' if registeredErrorTracker? return registeredErrorTracker(error, {level: 'error', json: {msg}}) else if window?.Rollbar? window.Rollbar.error(msg, error) else console.warn('No registered error tracker') exports.collisions = (list, iteratee = _l.identity) -> set = new Set() collisions = [] list.forEach (elem) -> if set.has((it = iteratee(elem))) collisions.push(it) set.add(it) return collisions exports.find_connected = (start_points, get_neighbors) -> seen = new Set() explore = (node) -> return if seen.has(node) seen.add(node) explore(neighbor) for neighbor in get_neighbors(node) explore(start_point) for start_point in start_points return Array.from(seen) exports.dfs = dfs = (node, match, get_next) -> if match(node) return node else for child in get_next(node) found = dfs(child, match, get_next) return found if found? return undefined exports.distanceSquared = (coordsA, coordsB) -> Math.pow(coordsB[1] - coordsA[1], 2) + Math.pow(coordsB[0] - coordsA[0], 2) exports.throttled_map = (max_parallel, base, map_fn) -> new Promise (resolve, reject) -> [i, in_flight_promises] = [0, 0] [results, errors] = [new Array(base.length), []] do fire = -> while i < base.length and in_flight_promises < max_parallel # Avoid the javascript loop variable hoisting issue with i. Look up the `do` syntax for coffeescript. [curr, i] = [i, i + 1] do (curr) -> in_flight_promises += 1 map_fn(base[curr]).then( ((val) -> results[curr] = val), ((err) -> errors.push(err)) ).then -> in_flight_promises -= 1 fire() if in_flight_promises == 0 and i >= base.length # the i >= base.length should be redundant return resolve(results) unless not _l.isEmpty(errors) return reject(errors) if not _l.isEmpty(errors) exports.hash_string = (str) -> md5(str) # uninvoked_promise :: (-> (A | Promise A)) -> (Promise A, () -> Promise A) exports.uninvoked_promise = (action) -> resolver = null promise = new Promise (accept, reject) -> resolver = {accept, reject} fire = -> fired = Promise.resolve().then(action) resolver.accept(fired) return fired [promise, fire] exports.CV = -> resolve = null p = new Promise (accept, reject) -> resolve = {accept, reject} return [p, resolve] # after :: (() -> ()) -> (). `after` takes a callback, instead of a promise, because promises have # less fine grained control over scheduling; the .then schedules a microtask, whereas a callback is # sync with whatever invokes it. Feel free to pass {after: (cb) -> Promise.resolve().then => cb()}. exports.if_changed = if_changed = ({value, compare, after}) -> new Promise (resolve, reject) -> original_value = value() after -> changed = compare(original_value, value()) resolve(changed) # For Perf. Use when you're sure you know which blocks can be mutated by this valueLink exports.propLinkWithMutatedBlocks = propLinkWithMutatedBlocks = (object, attr, onChange, mutated_blocks) -> assert -> mutated_blocks?.length > 0 propLink(object, attr, => onChange({mutated_blocks: _l.keyBy(_l.map mutated_blocks, 'uniqueKey')})) # sorted_buckets :: [a] -> (a -> Equalable) -> [[a]] # where Equalable is a type that supports == in a meaningful way, like string or number # The second argument is a lodash interatee, so it can be a function, or a string naming a member like # sorted_buckets([{top: 12, ...}, {top: 11, ...}, {top: 12, ...}, {top: 119, ...}], 'top') # Could be implemented differently to take an (a -> a -> Bool) as a second argument. # sorted_buckets([3, 4, 2, 5, 6, 2, 2.3, 4.1, 5, 5], _l.identity) == [[2, 2], [2.3], [3], [4], [4.1], [5, 5, 5], [6]] # sorted_buckets([3, 4, 2, 5, 6, 2, 2.3, 4.1, 5, 5], ((o) -> Math.floor(o))) == [[2, 2, 2.3], [3], [4, 4.1], [5, 5, 5], [6]] # Does not make any guarantees about the order elements within a bucket exports.sorted_buckets = sorted_buckets = (lst, it) -> fn = _l.iteratee(it) sorted = _l.sortBy(lst, fn) current_value = {} # unequalable sentinal buckets = [] for elem in sorted next_value = fn(elem) buckets.push([]) if current_value != next_value _l.last(buckets).push(elem) current_value = next_value return buckets
[ { "context": "###\nCopyright 2016 Balena\n\nLicensed under the Apache License, Version 2.0 (", "end": 25, "score": 0.9941018223762512, "start": 19, "tag": "NAME", "value": "Balena" }, { "context": "twork.getFiles\n# \twifiSsid: 'foobar'\n# \twifiKey: 'hello'\n###\nexports.getFiles = (options = {}) ->\n\n\tif no", "end": 953, "score": 0.9708694219589233, "start": 948, "tag": "KEY", "value": "hello" } ]
lib/network.coffee
balena-io-modules/resin-device-config
2
### Copyright 2016 Balena Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### _ = require('lodash') settings = require('./settings') ###* # @summary Get network configuration files # @protected # @function # # @param {Object} [options={}] - options # @param {String} [options.wifiSsid] - wifi ssid # @param {String} [options.wifiKey] - wifi key # # @returns {Object} Network configuration files # # @example # files = network.getFiles # wifiSsid: 'foobar' # wifiKey: 'hello' ### exports.getFiles = (options = {}) -> if not _.isPlainObject(options) throw new Error("Invalid options: #{options}") return { 'network/settings': settings.main 'network/network.config': settings.getHomeSettings(options) }
117250
### Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### _ = require('lodash') settings = require('./settings') ###* # @summary Get network configuration files # @protected # @function # # @param {Object} [options={}] - options # @param {String} [options.wifiSsid] - wifi ssid # @param {String} [options.wifiKey] - wifi key # # @returns {Object} Network configuration files # # @example # files = network.getFiles # wifiSsid: 'foobar' # wifiKey: '<KEY>' ### exports.getFiles = (options = {}) -> if not _.isPlainObject(options) throw new Error("Invalid options: #{options}") return { 'network/settings': settings.main 'network/network.config': settings.getHomeSettings(options) }
true
### Copyright 2016 PI:NAME:<NAME>END_PI Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### _ = require('lodash') settings = require('./settings') ###* # @summary Get network configuration files # @protected # @function # # @param {Object} [options={}] - options # @param {String} [options.wifiSsid] - wifi ssid # @param {String} [options.wifiKey] - wifi key # # @returns {Object} Network configuration files # # @example # files = network.getFiles # wifiSsid: 'foobar' # wifiKey: 'PI:KEY:<KEY>END_PI' ### exports.getFiles = (options = {}) -> if not _.isPlainObject(options) throw new Error("Invalid options: #{options}") return { 'network/settings': settings.main 'network/network.config': settings.getHomeSettings(options) }
[ { "context": "# Copyright (c) 2015 naymspace software (Dennis Nissen)\n#\n# Licensed under the Apache License, Version 2", "end": 54, "score": 0.9998756051063538, "start": 41, "tag": "NAME", "value": "Dennis Nissen" }, { "context": " email: \"invalid email address\"\n password: \"passwords do not match\"\n min: \"too small\"\n max: \"too high\"\n ", "end": 3174, "score": 0.9993696212768555, "start": 3152, "tag": "PASSWORD", "value": "passwords do not match" }, { "context": "l output\"\n profit: \"Profit\"\n username: \"Username\"\n password: \"Password\"\n password_again:", "end": 3537, "score": 0.9981250762939453, "start": 3529, "tag": "USERNAME", "value": "Username" }, { "context": "ofit\"\n username: \"Username\"\n password: \"Password\"\n password_again: \"Password (again)\"\n e", "end": 3564, "score": 0.9995087385177612, "start": 3556, "tag": "PASSWORD", "value": "Password" }, { "context": " password: \"Password\"\n password_again: \"Password (again)\"\n email: \"Email\"\n firstname: \"First na", "end": 3604, "score": 0.9972643852233887, "start": 3589, "tag": "PASSWORD", "value": "Password (again" }, { "context": "ode: \"Sourcecode\"\n examples:\n firstname: \"John\"\n lastname: \"Doe\"\n\n $translateProvider.tran", "end": 4020, "score": 0.9997175931930542, "start": 4016, "tag": "NAME", "value": "John" }, { "context": "xamples:\n firstname: \"John\"\n lastname: \"Doe\"\n\n $translateProvider.translations 'de',\n mes", "end": 4042, "score": 0.9995992183685303, "start": 4039, "tag": "NAME", "value": "Doe" }, { "context": "\"\n hello: \"Hallo {{name}}!\"\n thankyou: \"Vielen Dank!\"\n login_failed: \"Anmeldung fehlgeschlagen!\"", "end": 4179, "score": 0.9714767336845398, "start": 4168, "tag": "NAME", "value": "Vielen Dank" }, { "context": "mail: \"ungültige E-Mail-Adresse\"\n password: \"die Passwörter stimmen nicht überein\"\n min: \"zu klein\"\n max: \"zu groß\"\n e", "end": 6816, "score": 0.9992679357528687, "start": 6780, "tag": "PASSWORD", "value": "die Passwörter stimmen nicht überein" }, { "context": " Modells\"\n profit: \"Gewinn\"\n username: \"Benutzername\"\n password: \"Passwort\"\n password_again:", "end": 7209, "score": 0.9996331334114075, "start": 7197, "tag": "USERNAME", "value": "Benutzername" }, { "context": "\"\n username: \"Benutzername\"\n password: \"Passwort\"\n password_again: \"Passwort (erneut)\"\n ", "end": 7236, "score": 0.9992327690124512, "start": 7228, "tag": "PASSWORD", "value": "Passwort" }, { "context": " password: \"Passwort\"\n password_again: \"Passwort (erneut)\"\n email: \"E-Mail\"\n firstname: \"Vorname", "end": 7277, "score": 0.9842966198921204, "start": 7261, "tag": "PASSWORD", "value": "Passwort (erneut" }, { "context": "\n you: \"Sie\"\n incentivizedtask_fellow: \"Anderer Spieler\"\n money: \"${{amount}}\"\n variant: \"Varia", "end": 7420, "score": 0.9873752593994141, "start": 7405, "tag": "NAME", "value": "Anderer Spieler" }, { "context": "ode: \"Sourcecode\"\n examples:\n firstname: \"Max\"\n lastname: \"Mustermann\"\n\n $translateProvid", "end": 7700, "score": 0.9998121857643127, "start": 7697, "tag": "NAME", "value": "Max" }, { "context": "examples:\n firstname: \"Max\"\n lastname: \"Mustermann\"\n\n $translateProvider.translations 'fr',\n mes", "end": 7729, "score": 0.9996077418327332, "start": 7719, "tag": "NAME", "value": "Mustermann" }, { "context": " hello: \"Bonjour {{name}}!\"\n thankyou: \"Merci!\"\n login_failed: \"La connection à échoué!\"\n ", "end": 7841, "score": 0.8721121549606323, "start": 7836, "tag": "NAME", "value": "Merci" }, { "context": "pattern: \"type d'entrée incorrecte\"\n email: \"courriel mél incorrect\"\n password: \"passwords do not match\"\n m", "end": 10409, "score": 0.8432400822639465, "start": 10387, "tag": "NAME", "value": "courriel mél incorrect" }, { "context": " email: \"courriel mél incorrect\"\n password: \"passwords do not match\"\n min: \"trop petit\"\n max: \"trop large\"\n", "end": 10450, "score": 0.9991946220397949, "start": 10428, "tag": "PASSWORD", "value": "passwords do not match" }, { "context": " max: \"trop large\"\n elements:\n login: \"S'identifier\"\n to_login: \"Aller À la page d’identificatio", "end": 10540, "score": 0.8354153037071228, "start": 10528, "tag": "USERNAME", "value": "S'identifier" }, { "context": " modèle\"\n profit: \"Revenus\"\n username: \"Nom d’utilisateur\"\n password: \"Mot de passe\"\n password_ag", "end": 10877, "score": 0.8489871025085449, "start": 10860, "tag": "USERNAME", "value": "Nom d’utilisateur" }, { "context": " username: \"Nom d’utilisateur\"\n password: \"Mot de passe\"\n password_again: \"Mot de passe (ressaisir)\"", "end": 10908, "score": 0.9990274310112, "start": 10896, "tag": "PASSWORD", "value": "Mot de passe" }, { "context": " password: \"Mot de passe\"\n password_again: \"Mot de passe (ressaisir)\"\n email: \"Courriel mél\"\n fi", "end": 10945, "score": 0.9580850601196289, "start": 10933, "tag": "PASSWORD", "value": "Mot de passe" }, { "context": "d_again: \"Mot de passe (ressaisir)\"\n email: \"Courriel mél\"\n firstname: \"Surnom\"\n lastname: \"Nom\"\n", "end": 10985, "score": 0.9981749057769775, "start": 10973, "tag": "NAME", "value": "Courriel mél" }, { "context": "r)\"\n email: \"Courriel mél\"\n firstname: \"Surnom\"\n lastname: \"Nom\"\n you: \"Vous\"\n in", "end": 11011, "score": 0.928516685962677, "start": 11005, "tag": "NAME", "value": "Surnom" }, { "context": "de: \"Code source\"\n examples:\n firstname: \"John\"\n lastname: \"Doe\"\n\n# $translateProvider.use", "end": 11380, "score": 0.9997568130493164, "start": 11376, "tag": "NAME", "value": "John" }, { "context": "xamples:\n firstname: \"John\"\n lastname: \"Doe\"\n\n# $translateProvider.useStaticFilesLoader\n# ", "end": 11402, "score": 0.9996137619018555, "start": 11399, "tag": "NAME", "value": "Doe" } ]
src/app/i18n/i18n.coffee
ogumi/client
0
# Copyright (c) 2015 naymspace software (Dennis Nissen) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. angular.module 'webClient' .config ($translateProvider) -> $translateProvider.translations 'en', messages: back: "back" hello: "Hello {{name}}!" thankyou: "Thank you!" login_failed: "Login failed!" error_head: "Error!" server_error: "An error occurred." register_server_error_info: "Please try again with a different user name." register_ok_head: "Registration successful" register_ok_info: "You can now login." logged_out: "Logged out." helpemail: "Optionally enter your email address here if you wish to." password_mismatch_head: "Incorrect input!" password_mismatch_info: "The passwords do not match." connection_error: "There seems to be an error with the server connection. Please wait a moment and then reload." offline: "You are offline. Please connect to the internet." online: "You are online." session_participate_error: "Wrong password or session is full." session_not_active: "This session is over." experiment_error: "The experiment calculation stopped with an error: " no_active_sessions: "There are no active sessions right now." already_answered: "You have already sended data for this step." loading_sessions: "Loading active sessions..." loading_experiment: "Loading experiment..." loading: "Loading..." not_active_experiment: "This experiment is not active. It will start {{startDate}}." active_waiting: "Please wait until the next step starts: {{endDate}}." ended_waiting: "The next step has started. Press \"Next\" to proceed." ended_experiment: "This experiment is over." lastmoney: "You have won ${{amount}}." currentmoneysum: "You won ${{current}} in this step.<br/>Current sum: ${{amount}}." current_timestep: "Current timestep: {{timestep}}" incentivizedtask_passive: "Please be patient until your fellow has answered." server_not_reachable: "OGUMI server at given URL is not responding" texts: login: "Please login to the server to participate in a session." register : "You can register to a server to be able to participate in a session on that server." sessions : "Welcome! Please choose a running session." actions: submit: "Submit" choose: "Choose" send: "Send" next: "Next" ok: "OK" quit: "Quit" close: "Close" errors: required: "required" pattern: "incorrect input type" email: "invalid email address" password: "passwords do not match" min: "too small" max: "too high" elements: login: "Login" to_login: "Go to login" register: "Register" logout: "Logout" session: "Session" sessions: "Sessions" experiment: "Experiment" change_input: "Change Input" model_output: "Model output" profit: "Profit" username: "Username" password: "Password" password_again: "Password (again)" email: "Email" firstname: "First name" lastname: "Last name" you: "You" incentivizedtask_fellow: "Other" money: "${{amount}}" variant: "Variant" server: "Server" later: "later" enhanced: "enhanced" max: "Max" about: "About" version: "Version" license: "License" sourcecode: "Sourcecode" examples: firstname: "John" lastname: "Doe" $translateProvider.translations 'de', messages: back: "zurück" hello: "Hallo {{name}}!" thankyou: "Vielen Dank!" login_failed: "Anmeldung fehlgeschlagen!" error_head: "Fehler!" server_error: "Ein Fehler ist aufgetreten." register_server_error_info: "Bitte versuchen Sie es mit einem anderen Benutzernamen erneut." register_ok_head: "Registrierung erfolgreich" register_ok_info: "Bitte loggen Sie sich ein." logged_out: "Sie haben sich abgemeldet." helpemail: "Optional geben Sie hier Ihre E-Mail-Adresse ein, wenn sie wünschen." password_mismatch_head: "Fehlerhafte Eingabe!" password_mismatch_info: "Die Passwörter stimmen nicht überein." connection_error: "Es scheint einen Fehler mit der Serververbindung zu geben. Bitte warten Sie einen Moment und laden danach neu." offline: "Sie sind offline. Bitte verbinden Sie sich mit dem Internet." online: "Sie sind online." session_participate_error: "Falsches Passwort oder die Veranstaltung ist voll." session_not_active: "Diese Veranstaltung ist beendet." experiment_error: "Die Berechnung des Experiments wurde mit einem Fehler beendet: " no_active_sessions: "Zur Zeit sind keine Veranstaltungen aktiv." already_answered: "Sie haben bereits Daten für diesen Schritt gesendet." loading_sessions: "Lade aktive Veranstaltungen..." loading_experiment: "Lade Experiment..." not_active_experiment: "Dieses Experiment ist noch nicht aktiv. Es wird zum folgenden Zeitpunkt starten: {{startDate}}." active_waiting: "Bitte warten Sie bis der nächste Schritt startet: {{endDate}}." ended_waiting: "Der nächste Schritt ist gestartet. Um Fortzufahren drücke \"Weiter\"." ended_experiment: "Dieses Experiment ist vorbei." lastmoney: "Sie haben ${{amount}} gewonnen." currentmoneysum: "Sie haben ${{current}} in diesem Abschnitt gewonnen.<br/>Aktuelle Summe: ${{amount}}." current_timestep: "Aktueller Zeitschritt: {{timestep}}" incentivizedtask_passive: "Bitte warten Sie bis Ihr Mitspieler antwortet." texts: login: "Bitte melden Sie sich an einem Server an um an einer Veranstaltung teilzunehmen." register : "Sie können sich auf einem Server registrieren, um an Veranstaltungen auf diesem teilzunehmen." sessions : "Willkommen! Bitte wählen Sie eine laufende Veranstaltung." actions: submit: "Absenden" choose: "Auswählen" send: "Senden" next: "Weiter" ok: "OK" quit: "Beenden" close: "Schließen" errors: required: "erforderlich" pattern: "ungültiger Eingabetyp" email: "ungültige E-Mail-Adresse" password: "die Passwörter stimmen nicht überein" min: "zu klein" max: "zu groß" elements: login: "Anmeldung" to_login: "Zur Anmeldung" register: "Registrierung" logout: "Abmelden" session: "Veranstaltung" sessions: "Veranstaltungen" experiment: "Experiment" change_input: "Eingabe" model_output: "Ausgabe des Modells" profit: "Gewinn" username: "Benutzername" password: "Passwort" password_again: "Passwort (erneut)" email: "E-Mail" firstname: "Vorname" lastname: "Nachname" you: "Sie" incentivizedtask_fellow: "Anderer Spieler" money: "${{amount}}" variant: "Variante" server: "Server" later: "später" enhanced: "erweitert" max: "Max" about: "Über" version: "Version" license: "Lizenz" sourcecode: "Sourcecode" examples: firstname: "Max" lastname: "Mustermann" $translateProvider.translations 'fr', messages: hello: "Bonjour {{name}}!" thankyou: "Merci!" login_failed: "La connection à échoué!" error_head: "Erreur!" server_error: "Une erreur s'est produite." register_server_error_info: "S'il vous plaît essayez à nouveau avec un nom nouveau d'utilisateur." register_ok_head: "Enregistrement réussit" register_ok_info: "Vous pouvez maintenant vous connecter." logged_out: "Séance fermée." helpemail: "Si vous voulez, vous pouvez aussi rentrer votre courriel mél ici." password_mismatch_head: "Entrée incorrecte!" password_mismatch_info: "Les mots de passe ne correspondent pas." connection_error: "Il semble y avoir une erreur avec la connexion au serveur. S'il vous plaît attendez un moment et puis rechargez." offline: "Vous êtes hors ligne. S'il vous plaît connectez-vous à Internet." online: "Vous êtes hors ligne." session_participate_error: "Mot de passe incorrect ou séance complète." session_not_active: "Cette séance est terminée." experiment_error: "Le calcul de l'expérience est arrêté avec une erreur: " no_active_sessions: "Il n'y a pas de séances actives en ce moment." already_answered: "Vous avez déjà envoyé des données pour cette étape." loading_sessions: "Chargement des séances actives..." loading_experiment: "Chargement de l’expérience..." loading: "En train de charger..." not_active_experiment: "Cette expérience n’est pas active. Elle va commencer {{startDate}}." active_waiting: "S'il vous plaît attendez que la prochaine étape commence: {{endDate}}." ended_waiting: "La prochaine étape a commencé. Appuyez sur \"Suivant\" pour continuer." ended_experiment: "Cette expérience est terminée." lastmoney: "Vous remportez ${{amount}}." currentmoneysum: "Vous remportez ${{current}} dans cette étape.<br/>Current sum: ${{amount}}." current_timestep: "Pas de temps actuel: {{timestep}}" incentivizedtask_passive: "S'il vous plaît patientez le choix de votre collègue." texts: login: "S'il vous plaît connectez-vous au serveur pour participer à une séance." register : "Vous devez vous inscrire à un serveur pour pouvoir participer à une séance sur ce serveur." sessions : "S'il vous plaît choisissez une séance active." actions: submit: "Soumettre" choose: "Choisissez" send: "Envoyer" next: "Suivant" ok: "OK" quit: "Quitter" close: "Fermer" errors: required: "exigé" pattern: "type d'entrée incorrecte" email: "courriel mél incorrect" password: "passwords do not match" min: "trop petit" max: "trop large" elements: login: "S'identifier" to_login: "Aller À la page d’identification" register: "S’nscrire" logout: "Se déconnecter" session: "Séances" sessions: "Séances" experiment: "Expérience" change_input: "Changer mode d’entrée" model_output: "Résultat du modèle" profit: "Revenus" username: "Nom d’utilisateur" password: "Mot de passe" password_again: "Mot de passe (ressaisir)" email: "Courriel mél" firstname: "Surnom" lastname: "Nom" you: "Vous" incentivizedtask_fellow: "Partenaire" money: "${{amount}}" variant: "Variante" server: "Serveur" later: "après" enhanced: "optimisé" max: "Max" about: "À Propos" version: "Version" license: "Permis" sourcecode: "Code source" examples: firstname: "John" lastname: "Doe" # $translateProvider.useStaticFilesLoader # prefix: 'app/i18n/', # suffix: '.json' $translateProvider.fallbackLanguage 'en' $translateProvider.preferredLanguage 'en' $translateProvider.determinePreferredLanguage() $translateProvider.useLocalStorage()
30945
# Copyright (c) 2015 naymspace software (<NAME>) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. angular.module 'webClient' .config ($translateProvider) -> $translateProvider.translations 'en', messages: back: "back" hello: "Hello {{name}}!" thankyou: "Thank you!" login_failed: "Login failed!" error_head: "Error!" server_error: "An error occurred." register_server_error_info: "Please try again with a different user name." register_ok_head: "Registration successful" register_ok_info: "You can now login." logged_out: "Logged out." helpemail: "Optionally enter your email address here if you wish to." password_mismatch_head: "Incorrect input!" password_mismatch_info: "The passwords do not match." connection_error: "There seems to be an error with the server connection. Please wait a moment and then reload." offline: "You are offline. Please connect to the internet." online: "You are online." session_participate_error: "Wrong password or session is full." session_not_active: "This session is over." experiment_error: "The experiment calculation stopped with an error: " no_active_sessions: "There are no active sessions right now." already_answered: "You have already sended data for this step." loading_sessions: "Loading active sessions..." loading_experiment: "Loading experiment..." loading: "Loading..." not_active_experiment: "This experiment is not active. It will start {{startDate}}." active_waiting: "Please wait until the next step starts: {{endDate}}." ended_waiting: "The next step has started. Press \"Next\" to proceed." ended_experiment: "This experiment is over." lastmoney: "You have won ${{amount}}." currentmoneysum: "You won ${{current}} in this step.<br/>Current sum: ${{amount}}." current_timestep: "Current timestep: {{timestep}}" incentivizedtask_passive: "Please be patient until your fellow has answered." server_not_reachable: "OGUMI server at given URL is not responding" texts: login: "Please login to the server to participate in a session." register : "You can register to a server to be able to participate in a session on that server." sessions : "Welcome! Please choose a running session." actions: submit: "Submit" choose: "Choose" send: "Send" next: "Next" ok: "OK" quit: "Quit" close: "Close" errors: required: "required" pattern: "incorrect input type" email: "invalid email address" password: "<PASSWORD>" min: "too small" max: "too high" elements: login: "Login" to_login: "Go to login" register: "Register" logout: "Logout" session: "Session" sessions: "Sessions" experiment: "Experiment" change_input: "Change Input" model_output: "Model output" profit: "Profit" username: "Username" password: "<PASSWORD>" password_again: "<PASSWORD>)" email: "Email" firstname: "First name" lastname: "Last name" you: "You" incentivizedtask_fellow: "Other" money: "${{amount}}" variant: "Variant" server: "Server" later: "later" enhanced: "enhanced" max: "Max" about: "About" version: "Version" license: "License" sourcecode: "Sourcecode" examples: firstname: "<NAME>" lastname: "<NAME>" $translateProvider.translations 'de', messages: back: "zurück" hello: "Hallo {{name}}!" thankyou: "<NAME>!" login_failed: "Anmeldung fehlgeschlagen!" error_head: "Fehler!" server_error: "Ein Fehler ist aufgetreten." register_server_error_info: "Bitte versuchen Sie es mit einem anderen Benutzernamen erneut." register_ok_head: "Registrierung erfolgreich" register_ok_info: "Bitte loggen Sie sich ein." logged_out: "Sie haben sich abgemeldet." helpemail: "Optional geben Sie hier Ihre E-Mail-Adresse ein, wenn sie wünschen." password_mismatch_head: "Fehlerhafte Eingabe!" password_mismatch_info: "Die Passwörter stimmen nicht überein." connection_error: "Es scheint einen Fehler mit der Serververbindung zu geben. Bitte warten Sie einen Moment und laden danach neu." offline: "Sie sind offline. Bitte verbinden Sie sich mit dem Internet." online: "Sie sind online." session_participate_error: "Falsches Passwort oder die Veranstaltung ist voll." session_not_active: "Diese Veranstaltung ist beendet." experiment_error: "Die Berechnung des Experiments wurde mit einem Fehler beendet: " no_active_sessions: "Zur Zeit sind keine Veranstaltungen aktiv." already_answered: "Sie haben bereits Daten für diesen Schritt gesendet." loading_sessions: "Lade aktive Veranstaltungen..." loading_experiment: "Lade Experiment..." not_active_experiment: "Dieses Experiment ist noch nicht aktiv. Es wird zum folgenden Zeitpunkt starten: {{startDate}}." active_waiting: "Bitte warten Sie bis der nächste Schritt startet: {{endDate}}." ended_waiting: "Der nächste Schritt ist gestartet. Um Fortzufahren drücke \"Weiter\"." ended_experiment: "Dieses Experiment ist vorbei." lastmoney: "Sie haben ${{amount}} gewonnen." currentmoneysum: "Sie haben ${{current}} in diesem Abschnitt gewonnen.<br/>Aktuelle Summe: ${{amount}}." current_timestep: "Aktueller Zeitschritt: {{timestep}}" incentivizedtask_passive: "Bitte warten Sie bis Ihr Mitspieler antwortet." texts: login: "Bitte melden Sie sich an einem Server an um an einer Veranstaltung teilzunehmen." register : "Sie können sich auf einem Server registrieren, um an Veranstaltungen auf diesem teilzunehmen." sessions : "Willkommen! Bitte wählen Sie eine laufende Veranstaltung." actions: submit: "Absenden" choose: "Auswählen" send: "Senden" next: "Weiter" ok: "OK" quit: "Beenden" close: "Schließen" errors: required: "erforderlich" pattern: "ungültiger Eingabetyp" email: "ungültige E-Mail-Adresse" password: "<PASSWORD>" min: "zu klein" max: "zu groß" elements: login: "Anmeldung" to_login: "Zur Anmeldung" register: "Registrierung" logout: "Abmelden" session: "Veranstaltung" sessions: "Veranstaltungen" experiment: "Experiment" change_input: "Eingabe" model_output: "Ausgabe des Modells" profit: "Gewinn" username: "Benutzername" password: "<PASSWORD>" password_again: "<PASSWORD>)" email: "E-Mail" firstname: "Vorname" lastname: "Nachname" you: "Sie" incentivizedtask_fellow: "<NAME>" money: "${{amount}}" variant: "Variante" server: "Server" later: "später" enhanced: "erweitert" max: "Max" about: "Über" version: "Version" license: "Lizenz" sourcecode: "Sourcecode" examples: firstname: "<NAME>" lastname: "<NAME>" $translateProvider.translations 'fr', messages: hello: "Bonjour {{name}}!" thankyou: "<NAME>!" login_failed: "La connection à échoué!" error_head: "Erreur!" server_error: "Une erreur s'est produite." register_server_error_info: "S'il vous plaît essayez à nouveau avec un nom nouveau d'utilisateur." register_ok_head: "Enregistrement réussit" register_ok_info: "Vous pouvez maintenant vous connecter." logged_out: "Séance fermée." helpemail: "Si vous voulez, vous pouvez aussi rentrer votre courriel mél ici." password_mismatch_head: "Entrée incorrecte!" password_mismatch_info: "Les mots de passe ne correspondent pas." connection_error: "Il semble y avoir une erreur avec la connexion au serveur. S'il vous plaît attendez un moment et puis rechargez." offline: "Vous êtes hors ligne. S'il vous plaît connectez-vous à Internet." online: "Vous êtes hors ligne." session_participate_error: "Mot de passe incorrect ou séance complète." session_not_active: "Cette séance est terminée." experiment_error: "Le calcul de l'expérience est arrêté avec une erreur: " no_active_sessions: "Il n'y a pas de séances actives en ce moment." already_answered: "Vous avez déjà envoyé des données pour cette étape." loading_sessions: "Chargement des séances actives..." loading_experiment: "Chargement de l’expérience..." loading: "En train de charger..." not_active_experiment: "Cette expérience n’est pas active. Elle va commencer {{startDate}}." active_waiting: "S'il vous plaît attendez que la prochaine étape commence: {{endDate}}." ended_waiting: "La prochaine étape a commencé. Appuyez sur \"Suivant\" pour continuer." ended_experiment: "Cette expérience est terminée." lastmoney: "Vous remportez ${{amount}}." currentmoneysum: "Vous remportez ${{current}} dans cette étape.<br/>Current sum: ${{amount}}." current_timestep: "Pas de temps actuel: {{timestep}}" incentivizedtask_passive: "S'il vous plaît patientez le choix de votre collègue." texts: login: "S'il vous plaît connectez-vous au serveur pour participer à une séance." register : "Vous devez vous inscrire à un serveur pour pouvoir participer à une séance sur ce serveur." sessions : "S'il vous plaît choisissez une séance active." actions: submit: "Soumettre" choose: "Choisissez" send: "Envoyer" next: "Suivant" ok: "OK" quit: "Quitter" close: "Fermer" errors: required: "exigé" pattern: "type d'entrée incorrecte" email: "<NAME>" password: "<PASSWORD>" min: "trop petit" max: "trop large" elements: login: "S'identifier" to_login: "Aller À la page d’identification" register: "S’nscrire" logout: "Se déconnecter" session: "Séances" sessions: "Séances" experiment: "Expérience" change_input: "Changer mode d’entrée" model_output: "Résultat du modèle" profit: "Revenus" username: "Nom d’utilisateur" password: "<PASSWORD>" password_again: "<PASSWORD> (ressaisir)" email: "<NAME>" firstname: "<NAME>" lastname: "Nom" you: "Vous" incentivizedtask_fellow: "Partenaire" money: "${{amount}}" variant: "Variante" server: "Serveur" later: "après" enhanced: "optimisé" max: "Max" about: "À Propos" version: "Version" license: "Permis" sourcecode: "Code source" examples: firstname: "<NAME>" lastname: "<NAME>" # $translateProvider.useStaticFilesLoader # prefix: 'app/i18n/', # suffix: '.json' $translateProvider.fallbackLanguage 'en' $translateProvider.preferredLanguage 'en' $translateProvider.determinePreferredLanguage() $translateProvider.useLocalStorage()
true
# Copyright (c) 2015 naymspace software (PI:NAME:<NAME>END_PI) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. angular.module 'webClient' .config ($translateProvider) -> $translateProvider.translations 'en', messages: back: "back" hello: "Hello {{name}}!" thankyou: "Thank you!" login_failed: "Login failed!" error_head: "Error!" server_error: "An error occurred." register_server_error_info: "Please try again with a different user name." register_ok_head: "Registration successful" register_ok_info: "You can now login." logged_out: "Logged out." helpemail: "Optionally enter your email address here if you wish to." password_mismatch_head: "Incorrect input!" password_mismatch_info: "The passwords do not match." connection_error: "There seems to be an error with the server connection. Please wait a moment and then reload." offline: "You are offline. Please connect to the internet." online: "You are online." session_participate_error: "Wrong password or session is full." session_not_active: "This session is over." experiment_error: "The experiment calculation stopped with an error: " no_active_sessions: "There are no active sessions right now." already_answered: "You have already sended data for this step." loading_sessions: "Loading active sessions..." loading_experiment: "Loading experiment..." loading: "Loading..." not_active_experiment: "This experiment is not active. It will start {{startDate}}." active_waiting: "Please wait until the next step starts: {{endDate}}." ended_waiting: "The next step has started. Press \"Next\" to proceed." ended_experiment: "This experiment is over." lastmoney: "You have won ${{amount}}." currentmoneysum: "You won ${{current}} in this step.<br/>Current sum: ${{amount}}." current_timestep: "Current timestep: {{timestep}}" incentivizedtask_passive: "Please be patient until your fellow has answered." server_not_reachable: "OGUMI server at given URL is not responding" texts: login: "Please login to the server to participate in a session." register : "You can register to a server to be able to participate in a session on that server." sessions : "Welcome! Please choose a running session." actions: submit: "Submit" choose: "Choose" send: "Send" next: "Next" ok: "OK" quit: "Quit" close: "Close" errors: required: "required" pattern: "incorrect input type" email: "invalid email address" password: "PI:PASSWORD:<PASSWORD>END_PI" min: "too small" max: "too high" elements: login: "Login" to_login: "Go to login" register: "Register" logout: "Logout" session: "Session" sessions: "Sessions" experiment: "Experiment" change_input: "Change Input" model_output: "Model output" profit: "Profit" username: "Username" password: "PI:PASSWORD:<PASSWORD>END_PI" password_again: "PI:PASSWORD:<PASSWORD>END_PI)" email: "Email" firstname: "First name" lastname: "Last name" you: "You" incentivizedtask_fellow: "Other" money: "${{amount}}" variant: "Variant" server: "Server" later: "later" enhanced: "enhanced" max: "Max" about: "About" version: "Version" license: "License" sourcecode: "Sourcecode" examples: firstname: "PI:NAME:<NAME>END_PI" lastname: "PI:NAME:<NAME>END_PI" $translateProvider.translations 'de', messages: back: "zurück" hello: "Hallo {{name}}!" thankyou: "PI:NAME:<NAME>END_PI!" login_failed: "Anmeldung fehlgeschlagen!" error_head: "Fehler!" server_error: "Ein Fehler ist aufgetreten." register_server_error_info: "Bitte versuchen Sie es mit einem anderen Benutzernamen erneut." register_ok_head: "Registrierung erfolgreich" register_ok_info: "Bitte loggen Sie sich ein." logged_out: "Sie haben sich abgemeldet." helpemail: "Optional geben Sie hier Ihre E-Mail-Adresse ein, wenn sie wünschen." password_mismatch_head: "Fehlerhafte Eingabe!" password_mismatch_info: "Die Passwörter stimmen nicht überein." connection_error: "Es scheint einen Fehler mit der Serververbindung zu geben. Bitte warten Sie einen Moment und laden danach neu." offline: "Sie sind offline. Bitte verbinden Sie sich mit dem Internet." online: "Sie sind online." session_participate_error: "Falsches Passwort oder die Veranstaltung ist voll." session_not_active: "Diese Veranstaltung ist beendet." experiment_error: "Die Berechnung des Experiments wurde mit einem Fehler beendet: " no_active_sessions: "Zur Zeit sind keine Veranstaltungen aktiv." already_answered: "Sie haben bereits Daten für diesen Schritt gesendet." loading_sessions: "Lade aktive Veranstaltungen..." loading_experiment: "Lade Experiment..." not_active_experiment: "Dieses Experiment ist noch nicht aktiv. Es wird zum folgenden Zeitpunkt starten: {{startDate}}." active_waiting: "Bitte warten Sie bis der nächste Schritt startet: {{endDate}}." ended_waiting: "Der nächste Schritt ist gestartet. Um Fortzufahren drücke \"Weiter\"." ended_experiment: "Dieses Experiment ist vorbei." lastmoney: "Sie haben ${{amount}} gewonnen." currentmoneysum: "Sie haben ${{current}} in diesem Abschnitt gewonnen.<br/>Aktuelle Summe: ${{amount}}." current_timestep: "Aktueller Zeitschritt: {{timestep}}" incentivizedtask_passive: "Bitte warten Sie bis Ihr Mitspieler antwortet." texts: login: "Bitte melden Sie sich an einem Server an um an einer Veranstaltung teilzunehmen." register : "Sie können sich auf einem Server registrieren, um an Veranstaltungen auf diesem teilzunehmen." sessions : "Willkommen! Bitte wählen Sie eine laufende Veranstaltung." actions: submit: "Absenden" choose: "Auswählen" send: "Senden" next: "Weiter" ok: "OK" quit: "Beenden" close: "Schließen" errors: required: "erforderlich" pattern: "ungültiger Eingabetyp" email: "ungültige E-Mail-Adresse" password: "PI:PASSWORD:<PASSWORD>END_PI" min: "zu klein" max: "zu groß" elements: login: "Anmeldung" to_login: "Zur Anmeldung" register: "Registrierung" logout: "Abmelden" session: "Veranstaltung" sessions: "Veranstaltungen" experiment: "Experiment" change_input: "Eingabe" model_output: "Ausgabe des Modells" profit: "Gewinn" username: "Benutzername" password: "PI:PASSWORD:<PASSWORD>END_PI" password_again: "PI:PASSWORD:<PASSWORD>END_PI)" email: "E-Mail" firstname: "Vorname" lastname: "Nachname" you: "Sie" incentivizedtask_fellow: "PI:NAME:<NAME>END_PI" money: "${{amount}}" variant: "Variante" server: "Server" later: "später" enhanced: "erweitert" max: "Max" about: "Über" version: "Version" license: "Lizenz" sourcecode: "Sourcecode" examples: firstname: "PI:NAME:<NAME>END_PI" lastname: "PI:NAME:<NAME>END_PI" $translateProvider.translations 'fr', messages: hello: "Bonjour {{name}}!" thankyou: "PI:NAME:<NAME>END_PI!" login_failed: "La connection à échoué!" error_head: "Erreur!" server_error: "Une erreur s'est produite." register_server_error_info: "S'il vous plaît essayez à nouveau avec un nom nouveau d'utilisateur." register_ok_head: "Enregistrement réussit" register_ok_info: "Vous pouvez maintenant vous connecter." logged_out: "Séance fermée." helpemail: "Si vous voulez, vous pouvez aussi rentrer votre courriel mél ici." password_mismatch_head: "Entrée incorrecte!" password_mismatch_info: "Les mots de passe ne correspondent pas." connection_error: "Il semble y avoir une erreur avec la connexion au serveur. S'il vous plaît attendez un moment et puis rechargez." offline: "Vous êtes hors ligne. S'il vous plaît connectez-vous à Internet." online: "Vous êtes hors ligne." session_participate_error: "Mot de passe incorrect ou séance complète." session_not_active: "Cette séance est terminée." experiment_error: "Le calcul de l'expérience est arrêté avec une erreur: " no_active_sessions: "Il n'y a pas de séances actives en ce moment." already_answered: "Vous avez déjà envoyé des données pour cette étape." loading_sessions: "Chargement des séances actives..." loading_experiment: "Chargement de l’expérience..." loading: "En train de charger..." not_active_experiment: "Cette expérience n’est pas active. Elle va commencer {{startDate}}." active_waiting: "S'il vous plaît attendez que la prochaine étape commence: {{endDate}}." ended_waiting: "La prochaine étape a commencé. Appuyez sur \"Suivant\" pour continuer." ended_experiment: "Cette expérience est terminée." lastmoney: "Vous remportez ${{amount}}." currentmoneysum: "Vous remportez ${{current}} dans cette étape.<br/>Current sum: ${{amount}}." current_timestep: "Pas de temps actuel: {{timestep}}" incentivizedtask_passive: "S'il vous plaît patientez le choix de votre collègue." texts: login: "S'il vous plaît connectez-vous au serveur pour participer à une séance." register : "Vous devez vous inscrire à un serveur pour pouvoir participer à une séance sur ce serveur." sessions : "S'il vous plaît choisissez une séance active." actions: submit: "Soumettre" choose: "Choisissez" send: "Envoyer" next: "Suivant" ok: "OK" quit: "Quitter" close: "Fermer" errors: required: "exigé" pattern: "type d'entrée incorrecte" email: "PI:NAME:<NAME>END_PI" password: "PI:PASSWORD:<PASSWORD>END_PI" min: "trop petit" max: "trop large" elements: login: "S'identifier" to_login: "Aller À la page d’identification" register: "S’nscrire" logout: "Se déconnecter" session: "Séances" sessions: "Séances" experiment: "Expérience" change_input: "Changer mode d’entrée" model_output: "Résultat du modèle" profit: "Revenus" username: "Nom d’utilisateur" password: "PI:PASSWORD:<PASSWORD>END_PI" password_again: "PI:PASSWORD:<PASSWORD>END_PI (ressaisir)" email: "PI:NAME:<NAME>END_PI" firstname: "PI:NAME:<NAME>END_PI" lastname: "Nom" you: "Vous" incentivizedtask_fellow: "Partenaire" money: "${{amount}}" variant: "Variante" server: "Serveur" later: "après" enhanced: "optimisé" max: "Max" about: "À Propos" version: "Version" license: "Permis" sourcecode: "Code source" examples: firstname: "PI:NAME:<NAME>END_PI" lastname: "PI:NAME:<NAME>END_PI" # $translateProvider.useStaticFilesLoader # prefix: 'app/i18n/', # suffix: '.json' $translateProvider.fallbackLanguage 'en' $translateProvider.preferredLanguage 'en' $translateProvider.determinePreferredLanguage() $translateProvider.useLocalStorage()
[ { "context": " Meteor.users.findOne('emails.address': 'admin@fbriders.ch')._id\n autoform:\n options: ->\n _.m", "end": 1044, "score": 0.9998884201049805, "start": 1027, "tag": "EMAIL", "value": "admin@fbriders.ch" } ]
collections/events.coffee
meip/vmt
0
@Events = new Meteor.Collection('events'); Schemas.Events = new SimpleSchema title: type: String location: type: String description: type: String autoform: rows: 5 gameCode: type: Number regEx: /[0-9]{1,3}/ organizerCode: type: Number regEx: /[0-9]{1,3}/ startDate: type: Date autoValue: -> if this.isInsert new Date() endDate: type: Date autoValue: -> if this.isInsert new Date() deadlineDate: type: Date autoValue: -> if this.isInsert new Date() helpertasks: type: [String] regEx: SimpleSchema.RegEx.Id optional: true autoform: options: -> _.map Helpertasks.find().fetch(), (helpertask)-> label: helpertask.title value: helpertask._id owner: type: String regEx: SimpleSchema.RegEx.Id autoValue: -> if this.isInsert try Meteor.userId() catch error Meteor.users.findOne('emails.address': 'admin@fbriders.ch')._id autoform: options: -> _.map Meteor.users.find().fetch(), (user)-> label: user.emails[0].address value: user._id createdAt: type: Date autoValue: -> if this.isInsert new Date() updatedAt: type: Date optional: true autoValue: -> if this.isUpdate new Date() Events.attachSchema(Schemas.Events) Events.helpers helpertaskDescription: -> Helpertasks.findOne(@doc)?.description TabularTables.Events = new Tabular.Table name: "EventsList" collection: Events columns: [ {data: "id", title: "Event ID"} {data: "title", title: "Title"} {data: "location", title: "Locaiton"} {data: "description", title: "Description"} {data: "gameCode", title: "Game Code"} {data: "startDate", title: "Start Date"} {data: "endDate", title: "End Date"} { tmpl: Meteor.isClient && Template.editEventButton } ]
196397
@Events = new Meteor.Collection('events'); Schemas.Events = new SimpleSchema title: type: String location: type: String description: type: String autoform: rows: 5 gameCode: type: Number regEx: /[0-9]{1,3}/ organizerCode: type: Number regEx: /[0-9]{1,3}/ startDate: type: Date autoValue: -> if this.isInsert new Date() endDate: type: Date autoValue: -> if this.isInsert new Date() deadlineDate: type: Date autoValue: -> if this.isInsert new Date() helpertasks: type: [String] regEx: SimpleSchema.RegEx.Id optional: true autoform: options: -> _.map Helpertasks.find().fetch(), (helpertask)-> label: helpertask.title value: helpertask._id owner: type: String regEx: SimpleSchema.RegEx.Id autoValue: -> if this.isInsert try Meteor.userId() catch error Meteor.users.findOne('emails.address': '<EMAIL>')._id autoform: options: -> _.map Meteor.users.find().fetch(), (user)-> label: user.emails[0].address value: user._id createdAt: type: Date autoValue: -> if this.isInsert new Date() updatedAt: type: Date optional: true autoValue: -> if this.isUpdate new Date() Events.attachSchema(Schemas.Events) Events.helpers helpertaskDescription: -> Helpertasks.findOne(@doc)?.description TabularTables.Events = new Tabular.Table name: "EventsList" collection: Events columns: [ {data: "id", title: "Event ID"} {data: "title", title: "Title"} {data: "location", title: "Locaiton"} {data: "description", title: "Description"} {data: "gameCode", title: "Game Code"} {data: "startDate", title: "Start Date"} {data: "endDate", title: "End Date"} { tmpl: Meteor.isClient && Template.editEventButton } ]
true
@Events = new Meteor.Collection('events'); Schemas.Events = new SimpleSchema title: type: String location: type: String description: type: String autoform: rows: 5 gameCode: type: Number regEx: /[0-9]{1,3}/ organizerCode: type: Number regEx: /[0-9]{1,3}/ startDate: type: Date autoValue: -> if this.isInsert new Date() endDate: type: Date autoValue: -> if this.isInsert new Date() deadlineDate: type: Date autoValue: -> if this.isInsert new Date() helpertasks: type: [String] regEx: SimpleSchema.RegEx.Id optional: true autoform: options: -> _.map Helpertasks.find().fetch(), (helpertask)-> label: helpertask.title value: helpertask._id owner: type: String regEx: SimpleSchema.RegEx.Id autoValue: -> if this.isInsert try Meteor.userId() catch error Meteor.users.findOne('emails.address': 'PI:EMAIL:<EMAIL>END_PI')._id autoform: options: -> _.map Meteor.users.find().fetch(), (user)-> label: user.emails[0].address value: user._id createdAt: type: Date autoValue: -> if this.isInsert new Date() updatedAt: type: Date optional: true autoValue: -> if this.isUpdate new Date() Events.attachSchema(Schemas.Events) Events.helpers helpertaskDescription: -> Helpertasks.findOne(@doc)?.description TabularTables.Events = new Tabular.Table name: "EventsList" collection: Events columns: [ {data: "id", title: "Event ID"} {data: "title", title: "Title"} {data: "location", title: "Locaiton"} {data: "description", title: "Description"} {data: "gameCode", title: "Game Code"} {data: "startDate", title: "Start Date"} {data: "endDate", title: "End Date"} { tmpl: Meteor.isClient && Template.editEventButton } ]
[ { "context": "#\n# Date main file\n#\n# Copyright (C) 2011 Nikolay Nemshilov\n#\n\n# hook up dependencies\ncore = require('co", "end": 59, "score": 0.9998806715011597, "start": 42, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/date/main.coffee
lovely-io/lovely.io-stl
2
# # Date main file # # Copyright (C) 2011 Nikolay Nemshilov # # hook up dependencies core = require('core') L = core.L ext = core.ext trim = core.trim zerofy = (value)-> (if value < 10 then '0' else '') + value re_escape = (string)-> string.replace(/([.*+?\^=!:${}()|\[\]\/\\])/g, '\\$1') # glueing in the files include 'src/i18n' include 'src/parse' include 'src/format' exports = ext Date, version: '%{version}'
141755
# # Date main file # # Copyright (C) 2011 <NAME> # # hook up dependencies core = require('core') L = core.L ext = core.ext trim = core.trim zerofy = (value)-> (if value < 10 then '0' else '') + value re_escape = (string)-> string.replace(/([.*+?\^=!:${}()|\[\]\/\\])/g, '\\$1') # glueing in the files include 'src/i18n' include 'src/parse' include 'src/format' exports = ext Date, version: '%{version}'
true
# # Date main file # # Copyright (C) 2011 PI:NAME:<NAME>END_PI # # hook up dependencies core = require('core') L = core.L ext = core.ext trim = core.trim zerofy = (value)-> (if value < 10 then '0' else '') + value re_escape = (string)-> string.replace(/([.*+?\^=!:${}()|\[\]\/\\])/g, '\\$1') # glueing in the files include 'src/i18n' include 'src/parse' include 'src/format' exports = ext Date, version: '%{version}'
[ { "context": " immediate assistance? Please [contact us](mailto:specialist@artsy.net)\n '\n pages:\n 'Bidding': 'how-auctions-", "end": 280, "score": 0.9999290108680725, "start": 260, "tag": "EMAIL", "value": "specialist@artsy.net" } ]
src/mobile/components/multi_page/config.coffee
kanaabe/force
1
module.exports = 'auction-faqs': title: 'Auction FAQs' description: ' How can we help you? Below are a few general categories to help you find the answers you’re looking for.\n\n Need more immediate assistance? Please [contact us](mailto:specialist@artsy.net) ' pages: 'Bidding': 'how-auctions-work-bidding' 'Buyers premium, taxes, & fees': 'how-auctions-work-buyers-premium-taxes-and-fees' 'Payments and Shipping': 'how-auctions-work-payments-and-shipping' 'Emails and alerts': 'how-auctions-work-emails-and-alerts' 'Conditions of sale': 'how-auctions-work-conditions-of-sale'
148069
module.exports = 'auction-faqs': title: 'Auction FAQs' description: ' How can we help you? Below are a few general categories to help you find the answers you’re looking for.\n\n Need more immediate assistance? Please [contact us](mailto:<EMAIL>) ' pages: 'Bidding': 'how-auctions-work-bidding' 'Buyers premium, taxes, & fees': 'how-auctions-work-buyers-premium-taxes-and-fees' 'Payments and Shipping': 'how-auctions-work-payments-and-shipping' 'Emails and alerts': 'how-auctions-work-emails-and-alerts' 'Conditions of sale': 'how-auctions-work-conditions-of-sale'
true
module.exports = 'auction-faqs': title: 'Auction FAQs' description: ' How can we help you? Below are a few general categories to help you find the answers you’re looking for.\n\n Need more immediate assistance? Please [contact us](mailto:PI:EMAIL:<EMAIL>END_PI) ' pages: 'Bidding': 'how-auctions-work-bidding' 'Buyers premium, taxes, & fees': 'how-auctions-work-buyers-premium-taxes-and-fees' 'Payments and Shipping': 'how-auctions-work-payments-and-shipping' 'Emails and alerts': 'how-auctions-work-emails-and-alerts' 'Conditions of sale': 'how-auctions-work-conditions-of-sale'
[ { "context": "done) ->\n \n App.User.insert firstName: \"Lance\", (error, record) =>\n user = record\n ", "end": 209, "score": 0.9997400045394897, "start": 204, "tag": "NAME", "value": "Lance" }, { "context": "user = record\n App.User.insert firstName: \"Dane\", done\n \n test 'hEach(\"App.User\")', ->\n ", "end": 293, "score": 0.999808132648468, "start": 289, "tag": "NAME", "value": "Dane" } ]
test/cases/view/shared/handlebarsHelperTest.coffee
jivagoalves/tower
1
describe "Tower.ViewEmberHelper", -> view = null user = null beforeEach -> view = Tower.View.create() describe 'each', -> beforeEach (done) -> App.User.insert firstName: "Lance", (error, record) => user = record App.User.insert firstName: "Dane", done test 'hEach("App.User")', -> template = -> hEach 'App.User' view.render template: template, (error, result) -> assert.equal result, """ {{#each App.User}} """ test 'hEach("App.User", ->)', -> template = -> hEach 'App.User', -> view.render template: template, (error, result) -> assert.equal result, """ {{#each App.User}} {{/each}} """ test 'hEach("App.User", key: "value")', -> template = -> hEach 'App.User', key: "value" view.render template: template, (error, result) -> assert.equal result, """ {{#each App.User key="value"}} """ test 'hEach("App.User", -> li "{{firstName}}")', -> template = -> hEach 'App.User', -> li '{{firstName}}' view.render template: template, (error, result) -> assert.equal result, """ {{#each App.User}} <li>{{firstName}}</li> {{/each}} """ test 'hWith("App.User", ->)', -> template = -> hWith 'App.User', -> view.render template: template, (error, result) -> assert.equal result, """ {{#with App.User}} {{/with}} """ test 'hBindAttr(src: "src")', -> template = -> hBindAttr src: "src", -> view.render template: template, (error, result) -> assert.equal result, """ {{bindAttr src="src"}} """ test 'hAction("anAction", target: "App.viewStates")', -> template = -> hAction("anAction", target: "App.viewStates") view.render template: template, (error, result) -> assert.equal result, """ {{action "anAction" target="App.viewStates"}} """ test 'a "{{action "select" target="App"}}", href: "#"', (done) -> template = -> a '{{action "select" target="App"}}', href: '#', 'Select' view.render template: template, (error, result) -> assert.equal result, """ <a href="#" {{action "select" target="App"}}>Select</a> """ done()
178938
describe "Tower.ViewEmberHelper", -> view = null user = null beforeEach -> view = Tower.View.create() describe 'each', -> beforeEach (done) -> App.User.insert firstName: "<NAME>", (error, record) => user = record App.User.insert firstName: "<NAME>", done test 'hEach("App.User")', -> template = -> hEach 'App.User' view.render template: template, (error, result) -> assert.equal result, """ {{#each App.User}} """ test 'hEach("App.User", ->)', -> template = -> hEach 'App.User', -> view.render template: template, (error, result) -> assert.equal result, """ {{#each App.User}} {{/each}} """ test 'hEach("App.User", key: "value")', -> template = -> hEach 'App.User', key: "value" view.render template: template, (error, result) -> assert.equal result, """ {{#each App.User key="value"}} """ test 'hEach("App.User", -> li "{{firstName}}")', -> template = -> hEach 'App.User', -> li '{{firstName}}' view.render template: template, (error, result) -> assert.equal result, """ {{#each App.User}} <li>{{firstName}}</li> {{/each}} """ test 'hWith("App.User", ->)', -> template = -> hWith 'App.User', -> view.render template: template, (error, result) -> assert.equal result, """ {{#with App.User}} {{/with}} """ test 'hBindAttr(src: "src")', -> template = -> hBindAttr src: "src", -> view.render template: template, (error, result) -> assert.equal result, """ {{bindAttr src="src"}} """ test 'hAction("anAction", target: "App.viewStates")', -> template = -> hAction("anAction", target: "App.viewStates") view.render template: template, (error, result) -> assert.equal result, """ {{action "anAction" target="App.viewStates"}} """ test 'a "{{action "select" target="App"}}", href: "#"', (done) -> template = -> a '{{action "select" target="App"}}', href: '#', 'Select' view.render template: template, (error, result) -> assert.equal result, """ <a href="#" {{action "select" target="App"}}>Select</a> """ done()
true
describe "Tower.ViewEmberHelper", -> view = null user = null beforeEach -> view = Tower.View.create() describe 'each', -> beforeEach (done) -> App.User.insert firstName: "PI:NAME:<NAME>END_PI", (error, record) => user = record App.User.insert firstName: "PI:NAME:<NAME>END_PI", done test 'hEach("App.User")', -> template = -> hEach 'App.User' view.render template: template, (error, result) -> assert.equal result, """ {{#each App.User}} """ test 'hEach("App.User", ->)', -> template = -> hEach 'App.User', -> view.render template: template, (error, result) -> assert.equal result, """ {{#each App.User}} {{/each}} """ test 'hEach("App.User", key: "value")', -> template = -> hEach 'App.User', key: "value" view.render template: template, (error, result) -> assert.equal result, """ {{#each App.User key="value"}} """ test 'hEach("App.User", -> li "{{firstName}}")', -> template = -> hEach 'App.User', -> li '{{firstName}}' view.render template: template, (error, result) -> assert.equal result, """ {{#each App.User}} <li>{{firstName}}</li> {{/each}} """ test 'hWith("App.User", ->)', -> template = -> hWith 'App.User', -> view.render template: template, (error, result) -> assert.equal result, """ {{#with App.User}} {{/with}} """ test 'hBindAttr(src: "src")', -> template = -> hBindAttr src: "src", -> view.render template: template, (error, result) -> assert.equal result, """ {{bindAttr src="src"}} """ test 'hAction("anAction", target: "App.viewStates")', -> template = -> hAction("anAction", target: "App.viewStates") view.render template: template, (error, result) -> assert.equal result, """ {{action "anAction" target="App.viewStates"}} """ test 'a "{{action "select" target="App"}}", href: "#"', (done) -> template = -> a '{{action "select" target="App"}}', href: '#', 'Select' view.render template: template, (error, result) -> assert.equal result, """ <a href="#" {{action "select" target="App"}}>Select</a> """ done()
[ { "context": "\"0\", team: [attacker]}\n {id: \"1\", name: \"1\", team: [defender]}\n ]\n battle = ne", "end": 4732, "score": 0.5456040501594543, "start": 4731, "tag": "NAME", "value": "1" }, { "context": "eServer\n name: 'pokebattle-api'\n version: '0.0.0'\n server.pre(restify.pre.sanitizePath())\n serve", "end": 6204, "score": 0.6312636733055115, "start": 6201, "tag": "IP_ADDRESS", "value": "0.0" } ]
api/index.coffee
sarenji/pokebattle-sim
5
restify = require('restify') generations = require('../server/generations') learnsets = require('../shared/learnsets') {makeBiasedRng} = require("../shared/bias_rng") GenerationJSON = generations.GenerationJSON getName = (name) -> require('./name_map.json')[name] slugify = (str) -> str.toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/\-{2,}/g, '-') slugifyArray = (array) -> hash = {} for element in array hash[slugify(element)] = element hash attachAPIEndpoints = (server) -> for gen in generations.ALL_GENERATIONS do (gen) -> json = GenerationJSON[gen.toUpperCase()] GenMoves = slugifyArray(json.MoveList) GenAbilities = slugifyArray(json.AbilityList) GenTypes = slugifyArray(json.TypeList) try # Preload Battle {Battle} = require("../server/#{gen}/battle") catch # TODO: There is no Battle object for this gen intGeneration = generations.GENERATION_TO_INT[gen] server.get "#{gen}/moves", (req, res, next) -> res.send(json.MoveData) return next() server.get "#{gen}/pokemon", (req, res, next) -> res.send(json.FormeData) return next() server.get "#{gen}/pokemon/:species", (req, res, next) -> species = getName(req.params.species) return next(new restify.ResourceNotFoundError("Could not find Pokemon: #{req.params.species}")) if !species pokemon = json.FormeData[species] res.send(pokemon) return next() server.get "#{gen}/items", (req, res, next) -> res.send(items: json.ItemList) return next() server.get "#{gen}/moves", (req, res, next) -> res.send(moves: json.MoveList) return next() server.get "#{gen}/moves/:name", (req, res, next) -> move = GenMoves[req.params.name] return next(new restify.ResourceNotFoundError("Could not find Move: #{req.params.name}")) if !move res.send(pokemon: json.MoveMap[move]) return next() server.get "#{gen}/abilities", (req, res, next) -> res.send(abilities: json.AbilityList) return next() server.get "#{gen}/abilities/:name", (req, res, next) -> ability = GenAbilities[req.params.name] return next(new restify.ResourceNotFoundError("Could not find Ability: #{req.params.name}")) if !ability res.send(pokemon: json.AbilityMap[ability]) return next() server.get "#{gen}/types", (req, res, next) -> res.send(types: json.TypeList) return next() server.get "#{gen}/types/:name", (req, res, next) -> type = GenTypes[req.params.name] return next(new restify.ResourceNotFoundError("Could not find Type: #{req.params.name}")) if !type res.send(pokemon: json.TypeMap[type]) return next() server.get "#{gen}/pokemon/:species/moves", (req, res, next) -> species = getName(req.params.species) pokemon = {species: species} moves = learnsets.learnableMoves(GenerationJSON, pokemon, intGeneration) return next(new restify.ResourceNotFoundError("Could not find moves for Pokemon: #{req.params.species}")) if !moves || moves.length == 0 res.send(moves: moves) return next() server.get "#{gen}/pokemon/:species/:forme/moves", (req, res, next) -> species = getName(req.params.species) pokemon = {species: species, forme: req.params.forme} moves = learnsets.learnableMoves(GenerationJSON, pokemon, intGeneration) return next(new restify.ResourceNotFoundError("Could not find moves for Pokemon: #{req.params.species}")) if !moves || moves.length == 0 res.send(moves: moves) return next() checkMoveset = (req, res, next) -> species = getName(req.params.species) return next(new restify.ResourceNotFoundError("Could not find Pokemon: #{req.params.species}")) if !species pokemon = {species: species} pokemon.forme = req.params.forme if req.params.forme moveset = req.query.moves?.split(/,/) || [] valid = learnsets.checkMoveset(GenerationJSON, pokemon, intGeneration, moveset) errors = [] errors.push("Invalid moveset") if !valid res.send(errors: errors) return next() server.get "#{gen}/pokemon/:species/check", checkMoveset server.get "#{gen}/pokemon/:species/:forme/check", checkMoveset server.put "#{gen}/damagecalc", (req, res, next) -> # todo: catch any invalid data. moveName = req.params.move attacker = req.params.attacker defender = req.params.defender players = [ {id: "0", name: "0", team: [attacker]} {id: "1", name: "1", team: [defender]} ] battle = new Battle('id', players, numActive: 1) move = battle.getMove(moveName) if not move return next(new restify.BadRequest("Invalid move #{moveName}")) battle.begin() attackerPokemon = battle.getTeam("0").at(0) defenderPokemon = battle.getTeam("1").at(0) # bias the RNG to remove randmomness like critical hits makeBiasedRng(battle) battle.rng.bias("next", "ch", 1) battle.rng.bias("randInt", "miss", 0) battle.rng.bias("next", "secondary effect", 0) battle.rng.bias("randInt", "flinch", 100) # calculate min damage battle.rng.bias("randInt", "damage roll", 15) minDamage = move.calculateDamage(battle, attackerPokemon, defenderPokemon) # calculate max damage battle.rng.bias("randInt", "damage roll", 0) maxDamage = move.calculateDamage(battle, attackerPokemon, defenderPokemon) # TODO: Add remaining HP or anything else that's requested res.send( moveType: move.getType(battle, attackerPokemon, defenderPokemon) basePower: move.basePower(battle, attackerPokemon, defenderPokemon) minDamage: minDamage maxDamage: maxDamage defenderMaxHP: defenderPokemon.stat('hp') ) return next() @createServer = (port, done) -> server = restify.createServer name: 'pokebattle-api' version: '0.0.0' server.pre(restify.pre.sanitizePath()) server.use(restify.acceptParser(server.acceptable)) server.use(restify.queryParser()) server.use(restify.bodyParser()) server.use(restify.gzipResponse()) server.use (req, res, next) -> res.charSet('utf8') return next() attachAPIEndpoints(server) server.listen port, -> console.log('%s listening at %s', server.name, server.url) done?() server
138510
restify = require('restify') generations = require('../server/generations') learnsets = require('../shared/learnsets') {makeBiasedRng} = require("../shared/bias_rng") GenerationJSON = generations.GenerationJSON getName = (name) -> require('./name_map.json')[name] slugify = (str) -> str.toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/\-{2,}/g, '-') slugifyArray = (array) -> hash = {} for element in array hash[slugify(element)] = element hash attachAPIEndpoints = (server) -> for gen in generations.ALL_GENERATIONS do (gen) -> json = GenerationJSON[gen.toUpperCase()] GenMoves = slugifyArray(json.MoveList) GenAbilities = slugifyArray(json.AbilityList) GenTypes = slugifyArray(json.TypeList) try # Preload Battle {Battle} = require("../server/#{gen}/battle") catch # TODO: There is no Battle object for this gen intGeneration = generations.GENERATION_TO_INT[gen] server.get "#{gen}/moves", (req, res, next) -> res.send(json.MoveData) return next() server.get "#{gen}/pokemon", (req, res, next) -> res.send(json.FormeData) return next() server.get "#{gen}/pokemon/:species", (req, res, next) -> species = getName(req.params.species) return next(new restify.ResourceNotFoundError("Could not find Pokemon: #{req.params.species}")) if !species pokemon = json.FormeData[species] res.send(pokemon) return next() server.get "#{gen}/items", (req, res, next) -> res.send(items: json.ItemList) return next() server.get "#{gen}/moves", (req, res, next) -> res.send(moves: json.MoveList) return next() server.get "#{gen}/moves/:name", (req, res, next) -> move = GenMoves[req.params.name] return next(new restify.ResourceNotFoundError("Could not find Move: #{req.params.name}")) if !move res.send(pokemon: json.MoveMap[move]) return next() server.get "#{gen}/abilities", (req, res, next) -> res.send(abilities: json.AbilityList) return next() server.get "#{gen}/abilities/:name", (req, res, next) -> ability = GenAbilities[req.params.name] return next(new restify.ResourceNotFoundError("Could not find Ability: #{req.params.name}")) if !ability res.send(pokemon: json.AbilityMap[ability]) return next() server.get "#{gen}/types", (req, res, next) -> res.send(types: json.TypeList) return next() server.get "#{gen}/types/:name", (req, res, next) -> type = GenTypes[req.params.name] return next(new restify.ResourceNotFoundError("Could not find Type: #{req.params.name}")) if !type res.send(pokemon: json.TypeMap[type]) return next() server.get "#{gen}/pokemon/:species/moves", (req, res, next) -> species = getName(req.params.species) pokemon = {species: species} moves = learnsets.learnableMoves(GenerationJSON, pokemon, intGeneration) return next(new restify.ResourceNotFoundError("Could not find moves for Pokemon: #{req.params.species}")) if !moves || moves.length == 0 res.send(moves: moves) return next() server.get "#{gen}/pokemon/:species/:forme/moves", (req, res, next) -> species = getName(req.params.species) pokemon = {species: species, forme: req.params.forme} moves = learnsets.learnableMoves(GenerationJSON, pokemon, intGeneration) return next(new restify.ResourceNotFoundError("Could not find moves for Pokemon: #{req.params.species}")) if !moves || moves.length == 0 res.send(moves: moves) return next() checkMoveset = (req, res, next) -> species = getName(req.params.species) return next(new restify.ResourceNotFoundError("Could not find Pokemon: #{req.params.species}")) if !species pokemon = {species: species} pokemon.forme = req.params.forme if req.params.forme moveset = req.query.moves?.split(/,/) || [] valid = learnsets.checkMoveset(GenerationJSON, pokemon, intGeneration, moveset) errors = [] errors.push("Invalid moveset") if !valid res.send(errors: errors) return next() server.get "#{gen}/pokemon/:species/check", checkMoveset server.get "#{gen}/pokemon/:species/:forme/check", checkMoveset server.put "#{gen}/damagecalc", (req, res, next) -> # todo: catch any invalid data. moveName = req.params.move attacker = req.params.attacker defender = req.params.defender players = [ {id: "0", name: "0", team: [attacker]} {id: "1", name: "<NAME>", team: [defender]} ] battle = new Battle('id', players, numActive: 1) move = battle.getMove(moveName) if not move return next(new restify.BadRequest("Invalid move #{moveName}")) battle.begin() attackerPokemon = battle.getTeam("0").at(0) defenderPokemon = battle.getTeam("1").at(0) # bias the RNG to remove randmomness like critical hits makeBiasedRng(battle) battle.rng.bias("next", "ch", 1) battle.rng.bias("randInt", "miss", 0) battle.rng.bias("next", "secondary effect", 0) battle.rng.bias("randInt", "flinch", 100) # calculate min damage battle.rng.bias("randInt", "damage roll", 15) minDamage = move.calculateDamage(battle, attackerPokemon, defenderPokemon) # calculate max damage battle.rng.bias("randInt", "damage roll", 0) maxDamage = move.calculateDamage(battle, attackerPokemon, defenderPokemon) # TODO: Add remaining HP or anything else that's requested res.send( moveType: move.getType(battle, attackerPokemon, defenderPokemon) basePower: move.basePower(battle, attackerPokemon, defenderPokemon) minDamage: minDamage maxDamage: maxDamage defenderMaxHP: defenderPokemon.stat('hp') ) return next() @createServer = (port, done) -> server = restify.createServer name: 'pokebattle-api' version: '0.0.0' server.pre(restify.pre.sanitizePath()) server.use(restify.acceptParser(server.acceptable)) server.use(restify.queryParser()) server.use(restify.bodyParser()) server.use(restify.gzipResponse()) server.use (req, res, next) -> res.charSet('utf8') return next() attachAPIEndpoints(server) server.listen port, -> console.log('%s listening at %s', server.name, server.url) done?() server
true
restify = require('restify') generations = require('../server/generations') learnsets = require('../shared/learnsets') {makeBiasedRng} = require("../shared/bias_rng") GenerationJSON = generations.GenerationJSON getName = (name) -> require('./name_map.json')[name] slugify = (str) -> str.toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/\-{2,}/g, '-') slugifyArray = (array) -> hash = {} for element in array hash[slugify(element)] = element hash attachAPIEndpoints = (server) -> for gen in generations.ALL_GENERATIONS do (gen) -> json = GenerationJSON[gen.toUpperCase()] GenMoves = slugifyArray(json.MoveList) GenAbilities = slugifyArray(json.AbilityList) GenTypes = slugifyArray(json.TypeList) try # Preload Battle {Battle} = require("../server/#{gen}/battle") catch # TODO: There is no Battle object for this gen intGeneration = generations.GENERATION_TO_INT[gen] server.get "#{gen}/moves", (req, res, next) -> res.send(json.MoveData) return next() server.get "#{gen}/pokemon", (req, res, next) -> res.send(json.FormeData) return next() server.get "#{gen}/pokemon/:species", (req, res, next) -> species = getName(req.params.species) return next(new restify.ResourceNotFoundError("Could not find Pokemon: #{req.params.species}")) if !species pokemon = json.FormeData[species] res.send(pokemon) return next() server.get "#{gen}/items", (req, res, next) -> res.send(items: json.ItemList) return next() server.get "#{gen}/moves", (req, res, next) -> res.send(moves: json.MoveList) return next() server.get "#{gen}/moves/:name", (req, res, next) -> move = GenMoves[req.params.name] return next(new restify.ResourceNotFoundError("Could not find Move: #{req.params.name}")) if !move res.send(pokemon: json.MoveMap[move]) return next() server.get "#{gen}/abilities", (req, res, next) -> res.send(abilities: json.AbilityList) return next() server.get "#{gen}/abilities/:name", (req, res, next) -> ability = GenAbilities[req.params.name] return next(new restify.ResourceNotFoundError("Could not find Ability: #{req.params.name}")) if !ability res.send(pokemon: json.AbilityMap[ability]) return next() server.get "#{gen}/types", (req, res, next) -> res.send(types: json.TypeList) return next() server.get "#{gen}/types/:name", (req, res, next) -> type = GenTypes[req.params.name] return next(new restify.ResourceNotFoundError("Could not find Type: #{req.params.name}")) if !type res.send(pokemon: json.TypeMap[type]) return next() server.get "#{gen}/pokemon/:species/moves", (req, res, next) -> species = getName(req.params.species) pokemon = {species: species} moves = learnsets.learnableMoves(GenerationJSON, pokemon, intGeneration) return next(new restify.ResourceNotFoundError("Could not find moves for Pokemon: #{req.params.species}")) if !moves || moves.length == 0 res.send(moves: moves) return next() server.get "#{gen}/pokemon/:species/:forme/moves", (req, res, next) -> species = getName(req.params.species) pokemon = {species: species, forme: req.params.forme} moves = learnsets.learnableMoves(GenerationJSON, pokemon, intGeneration) return next(new restify.ResourceNotFoundError("Could not find moves for Pokemon: #{req.params.species}")) if !moves || moves.length == 0 res.send(moves: moves) return next() checkMoveset = (req, res, next) -> species = getName(req.params.species) return next(new restify.ResourceNotFoundError("Could not find Pokemon: #{req.params.species}")) if !species pokemon = {species: species} pokemon.forme = req.params.forme if req.params.forme moveset = req.query.moves?.split(/,/) || [] valid = learnsets.checkMoveset(GenerationJSON, pokemon, intGeneration, moveset) errors = [] errors.push("Invalid moveset") if !valid res.send(errors: errors) return next() server.get "#{gen}/pokemon/:species/check", checkMoveset server.get "#{gen}/pokemon/:species/:forme/check", checkMoveset server.put "#{gen}/damagecalc", (req, res, next) -> # todo: catch any invalid data. moveName = req.params.move attacker = req.params.attacker defender = req.params.defender players = [ {id: "0", name: "0", team: [attacker]} {id: "1", name: "PI:NAME:<NAME>END_PI", team: [defender]} ] battle = new Battle('id', players, numActive: 1) move = battle.getMove(moveName) if not move return next(new restify.BadRequest("Invalid move #{moveName}")) battle.begin() attackerPokemon = battle.getTeam("0").at(0) defenderPokemon = battle.getTeam("1").at(0) # bias the RNG to remove randmomness like critical hits makeBiasedRng(battle) battle.rng.bias("next", "ch", 1) battle.rng.bias("randInt", "miss", 0) battle.rng.bias("next", "secondary effect", 0) battle.rng.bias("randInt", "flinch", 100) # calculate min damage battle.rng.bias("randInt", "damage roll", 15) minDamage = move.calculateDamage(battle, attackerPokemon, defenderPokemon) # calculate max damage battle.rng.bias("randInt", "damage roll", 0) maxDamage = move.calculateDamage(battle, attackerPokemon, defenderPokemon) # TODO: Add remaining HP or anything else that's requested res.send( moveType: move.getType(battle, attackerPokemon, defenderPokemon) basePower: move.basePower(battle, attackerPokemon, defenderPokemon) minDamage: minDamage maxDamage: maxDamage defenderMaxHP: defenderPokemon.stat('hp') ) return next() @createServer = (port, done) -> server = restify.createServer name: 'pokebattle-api' version: '0.0.0' server.pre(restify.pre.sanitizePath()) server.use(restify.acceptParser(server.acceptable)) server.use(restify.queryParser()) server.use(restify.bodyParser()) server.use(restify.gzipResponse()) server.use (req, res, next) -> res.charSet('utf8') return next() attachAPIEndpoints(server) server.listen port, -> console.log('%s listening at %s', server.name, server.url) done?() server
[ { "context": " process.env.HUBOT_HIPCHAT_JID\n password: process.env.HUBOT_HIPCHAT_PASSWORD\n token: process.env.HUBO", "end": 1457, "score": 0.7733325362205505, "start": 1440, "tag": "PASSWORD", "value": "process.env.HUBOT" }, { "context": "nect =>\n console.log \"Connected to HipChat as @#{bot.mention_name}!\"\n\n # Provide our name to", "end": 2037, "score": 0.8203421235084534, "start": 2037, "tag": "USERNAME", "value": "" }, { "context": " =>\n console.log \"Connected to HipChat as @#{bot.mention_name}!\"\n\n # Provide our name to Hubot\n self.", "end": 2057, "score": 0.958969235420227, "start": 2041, "tag": "USERNAME", "value": "bot.mention_name" } ]
src/hipchat.coffee
idealprojectgroup/hubot-hipchat
0
Robot = require('hubot').Robot Adapter = require('hubot').Adapter TextMessage = require('hubot').TextMessage HTTPS = require 'https' Wobot = require('wobot').Bot class HipChat extends Adapter send: (envelope, strings...) -> user = null room = null target_jid = null # as of hubot 2.4.2, the first param to send() is an object with 'user' # and 'room' data inside. detect the old style here. if envelope.reply_to user = envelope else # expand envelope user = envelope.user room = envelope.room if user # most common case - we're replying to a user in a room or 1-1 if user.reply_to target_jid = user.reply_to # allows user objects to be passed in else if user.jid target_jid = user.jid # allows user to be a jid string else if user.search /@/ != -1 target_jid = user else if room # this will happen if someone uses robot.messageRoom(jid, ...) target_jid = room if not target_jid console.log "ERROR: Not sure who to send to. envelope=", envelope return for str in strings @bot.message target_jid, str reply: (envelope, strings...) -> user = if envelope.user then envelope.user else envelope for str in strings @send envelope, "@#{user.mention_name} #{str}" run: -> self = @ @options = jid: process.env.HUBOT_HIPCHAT_JID password: process.env.HUBOT_HIPCHAT_PASSWORD token: process.env.HUBOT_HIPCHAT_TOKEN or null rooms: process.env.HUBOT_HIPCHAT_ROOMS or "All" debug: process.env.HUBOT_HIPCHAT_DEBUG or false host: process.env.HUBOT_HIPCHAT_HOST or null console.log "HipChat adapter options:", @options # create Wobot bot object bot = new Wobot( jid: @options.jid, password: @options.password, debug: @options.debug == 'true', host: @options.host ) console.log "Wobot object:", bot bot.onConnect => console.log "Connected to HipChat as @#{bot.mention_name}!" # Provide our name to Hubot self.robot.name = bot.mention_name # Tell Hubot we're connected so it can load scripts self.emit "connected" # Join requested rooms if @options.rooms is "All" or @options.rooms is '@All' bot.getRooms (err, rooms, stanza) -> if rooms for room in rooms console.log "Joining #{room.jid}" bot.join room.jid else console.log "Can't list rooms: #{err}" else for room_jid in @options.rooms.split(',') console.log "Joining #{room_jid}" bot.join room_jid # Fetch user info bot.getRoster (err, users, stanza) -> if users for user in users self.userForId self.userIdFromJid(user.jid), user else console.log "Can't list users: #{err}" bot.onError (message) -> # If HipChat sends an error, we get the error message from XMPP. # Otherwise, we get an Error object from the Node connection. if message.message console.log "Error talking to HipChat:", message.message else console.log "Received error from HipChat:", message bot.onMessage (channel, from, message) -> author = {} author.name = from author.reply_to = channel author.room = self.roomNameFromJid(channel) # add extra details if this message is from a known user author_data = self.userForName(from) if author_data author.name = author_data.name author.mention_name = author_data.mention_name author.jid = author_data.jid # reformat leading @mention name to be like "name: message" which is # what hubot expects regex = new RegExp("^@#{bot.mention_name}\\b", "i") hubot_msg = message.replace(regex, "#{bot.mention_name}: ") self.receive new TextMessage(author, hubot_msg) bot.onPrivateMessage (from, message) -> author = {} author.reply_to = from # add extra details if this message is from a known user author_data = self.userForId(self.userIdFromJid(from)) if author_data author.name = author_data.name author.mention_name = author_data.mention_name author.jid = author_data.jid # remove leading @mention name if present and format the message like # "name: message" which is what hubot expects regex = new RegExp("^@#{bot.mention_name}\\b", "i") message = message.replace(regex, "") hubot_msg = "#{bot.mention_name}: #{message}" self.receive new TextMessage(author, hubot_msg) # Join rooms automatically when invited bot.onInvite (room_jid, from_jid, message) => console.log "Got invite to #{room_jid} from #{from_jid} - joining" bot.join room_jid bot.connect() @bot = bot userIdFromJid: (jid) -> try return jid.match(/^\d+_(\d+)@chat\./)[1] catch e console.log "Bad user JID: #{jid}" return null roomNameFromJid: (jid) -> try return jid.match(/^\d+_(.+)@conf\./)[1] catch e console.log "Bad room JID: #{jid}" return null # Convenience HTTP Methods for posting on behalf of the token"d user get: (path, callback) -> @request "GET", path, null, callback post: (path, body, callback) -> @request "POST", path, body, callback request: (method, path, body, callback) -> console.log method, path, body host = @options.host or "api.hipchat.com" headers = "Host": host unless @options.token callback "No API token provided to Hubot", null return options = "agent" : false "host" : host "port" : 443 "path" : path += "?auth_token=#{@options.token}" "method" : method "headers": headers if method is "POST" headers["Content-Type"] = "application/x-www-form-urlencoded" options.headers["Content-Length"] = body.length request = HTTPS.request options, (response) -> data = "" response.on "data", (chunk) -> data += chunk response.on "end", -> if response.statusCode >= 400 console.log "HipChat API error: #{response.statusCode}" try callback null, JSON.parse(data) catch err callback null, data or { } response.on "error", (err) -> callback err, null if method is "POST" request.end(body, 'binary') else request.end() request.on "error", (err) -> console.log err console.log err.stack callback err exports.use = (robot) -> new HipChat robot
138591
Robot = require('hubot').Robot Adapter = require('hubot').Adapter TextMessage = require('hubot').TextMessage HTTPS = require 'https' Wobot = require('wobot').Bot class HipChat extends Adapter send: (envelope, strings...) -> user = null room = null target_jid = null # as of hubot 2.4.2, the first param to send() is an object with 'user' # and 'room' data inside. detect the old style here. if envelope.reply_to user = envelope else # expand envelope user = envelope.user room = envelope.room if user # most common case - we're replying to a user in a room or 1-1 if user.reply_to target_jid = user.reply_to # allows user objects to be passed in else if user.jid target_jid = user.jid # allows user to be a jid string else if user.search /@/ != -1 target_jid = user else if room # this will happen if someone uses robot.messageRoom(jid, ...) target_jid = room if not target_jid console.log "ERROR: Not sure who to send to. envelope=", envelope return for str in strings @bot.message target_jid, str reply: (envelope, strings...) -> user = if envelope.user then envelope.user else envelope for str in strings @send envelope, "@#{user.mention_name} #{str}" run: -> self = @ @options = jid: process.env.HUBOT_HIPCHAT_JID password: <PASSWORD>_HIPCHAT_PASSWORD token: process.env.HUBOT_HIPCHAT_TOKEN or null rooms: process.env.HUBOT_HIPCHAT_ROOMS or "All" debug: process.env.HUBOT_HIPCHAT_DEBUG or false host: process.env.HUBOT_HIPCHAT_HOST or null console.log "HipChat adapter options:", @options # create Wobot bot object bot = new Wobot( jid: @options.jid, password: @options.password, debug: @options.debug == 'true', host: @options.host ) console.log "Wobot object:", bot bot.onConnect => console.log "Connected to HipChat as @#{bot.mention_name}!" # Provide our name to Hubot self.robot.name = bot.mention_name # Tell Hubot we're connected so it can load scripts self.emit "connected" # Join requested rooms if @options.rooms is "All" or @options.rooms is '@All' bot.getRooms (err, rooms, stanza) -> if rooms for room in rooms console.log "Joining #{room.jid}" bot.join room.jid else console.log "Can't list rooms: #{err}" else for room_jid in @options.rooms.split(',') console.log "Joining #{room_jid}" bot.join room_jid # Fetch user info bot.getRoster (err, users, stanza) -> if users for user in users self.userForId self.userIdFromJid(user.jid), user else console.log "Can't list users: #{err}" bot.onError (message) -> # If HipChat sends an error, we get the error message from XMPP. # Otherwise, we get an Error object from the Node connection. if message.message console.log "Error talking to HipChat:", message.message else console.log "Received error from HipChat:", message bot.onMessage (channel, from, message) -> author = {} author.name = from author.reply_to = channel author.room = self.roomNameFromJid(channel) # add extra details if this message is from a known user author_data = self.userForName(from) if author_data author.name = author_data.name author.mention_name = author_data.mention_name author.jid = author_data.jid # reformat leading @mention name to be like "name: message" which is # what hubot expects regex = new RegExp("^@#{bot.mention_name}\\b", "i") hubot_msg = message.replace(regex, "#{bot.mention_name}: ") self.receive new TextMessage(author, hubot_msg) bot.onPrivateMessage (from, message) -> author = {} author.reply_to = from # add extra details if this message is from a known user author_data = self.userForId(self.userIdFromJid(from)) if author_data author.name = author_data.name author.mention_name = author_data.mention_name author.jid = author_data.jid # remove leading @mention name if present and format the message like # "name: message" which is what hubot expects regex = new RegExp("^@#{bot.mention_name}\\b", "i") message = message.replace(regex, "") hubot_msg = "#{bot.mention_name}: #{message}" self.receive new TextMessage(author, hubot_msg) # Join rooms automatically when invited bot.onInvite (room_jid, from_jid, message) => console.log "Got invite to #{room_jid} from #{from_jid} - joining" bot.join room_jid bot.connect() @bot = bot userIdFromJid: (jid) -> try return jid.match(/^\d+_(\d+)@chat\./)[1] catch e console.log "Bad user JID: #{jid}" return null roomNameFromJid: (jid) -> try return jid.match(/^\d+_(.+)@conf\./)[1] catch e console.log "Bad room JID: #{jid}" return null # Convenience HTTP Methods for posting on behalf of the token"d user get: (path, callback) -> @request "GET", path, null, callback post: (path, body, callback) -> @request "POST", path, body, callback request: (method, path, body, callback) -> console.log method, path, body host = @options.host or "api.hipchat.com" headers = "Host": host unless @options.token callback "No API token provided to Hubot", null return options = "agent" : false "host" : host "port" : 443 "path" : path += "?auth_token=#{@options.token}" "method" : method "headers": headers if method is "POST" headers["Content-Type"] = "application/x-www-form-urlencoded" options.headers["Content-Length"] = body.length request = HTTPS.request options, (response) -> data = "" response.on "data", (chunk) -> data += chunk response.on "end", -> if response.statusCode >= 400 console.log "HipChat API error: #{response.statusCode}" try callback null, JSON.parse(data) catch err callback null, data or { } response.on "error", (err) -> callback err, null if method is "POST" request.end(body, 'binary') else request.end() request.on "error", (err) -> console.log err console.log err.stack callback err exports.use = (robot) -> new HipChat robot
true
Robot = require('hubot').Robot Adapter = require('hubot').Adapter TextMessage = require('hubot').TextMessage HTTPS = require 'https' Wobot = require('wobot').Bot class HipChat extends Adapter send: (envelope, strings...) -> user = null room = null target_jid = null # as of hubot 2.4.2, the first param to send() is an object with 'user' # and 'room' data inside. detect the old style here. if envelope.reply_to user = envelope else # expand envelope user = envelope.user room = envelope.room if user # most common case - we're replying to a user in a room or 1-1 if user.reply_to target_jid = user.reply_to # allows user objects to be passed in else if user.jid target_jid = user.jid # allows user to be a jid string else if user.search /@/ != -1 target_jid = user else if room # this will happen if someone uses robot.messageRoom(jid, ...) target_jid = room if not target_jid console.log "ERROR: Not sure who to send to. envelope=", envelope return for str in strings @bot.message target_jid, str reply: (envelope, strings...) -> user = if envelope.user then envelope.user else envelope for str in strings @send envelope, "@#{user.mention_name} #{str}" run: -> self = @ @options = jid: process.env.HUBOT_HIPCHAT_JID password: PI:PASSWORD:<PASSWORD>END_PI_HIPCHAT_PASSWORD token: process.env.HUBOT_HIPCHAT_TOKEN or null rooms: process.env.HUBOT_HIPCHAT_ROOMS or "All" debug: process.env.HUBOT_HIPCHAT_DEBUG or false host: process.env.HUBOT_HIPCHAT_HOST or null console.log "HipChat adapter options:", @options # create Wobot bot object bot = new Wobot( jid: @options.jid, password: @options.password, debug: @options.debug == 'true', host: @options.host ) console.log "Wobot object:", bot bot.onConnect => console.log "Connected to HipChat as @#{bot.mention_name}!" # Provide our name to Hubot self.robot.name = bot.mention_name # Tell Hubot we're connected so it can load scripts self.emit "connected" # Join requested rooms if @options.rooms is "All" or @options.rooms is '@All' bot.getRooms (err, rooms, stanza) -> if rooms for room in rooms console.log "Joining #{room.jid}" bot.join room.jid else console.log "Can't list rooms: #{err}" else for room_jid in @options.rooms.split(',') console.log "Joining #{room_jid}" bot.join room_jid # Fetch user info bot.getRoster (err, users, stanza) -> if users for user in users self.userForId self.userIdFromJid(user.jid), user else console.log "Can't list users: #{err}" bot.onError (message) -> # If HipChat sends an error, we get the error message from XMPP. # Otherwise, we get an Error object from the Node connection. if message.message console.log "Error talking to HipChat:", message.message else console.log "Received error from HipChat:", message bot.onMessage (channel, from, message) -> author = {} author.name = from author.reply_to = channel author.room = self.roomNameFromJid(channel) # add extra details if this message is from a known user author_data = self.userForName(from) if author_data author.name = author_data.name author.mention_name = author_data.mention_name author.jid = author_data.jid # reformat leading @mention name to be like "name: message" which is # what hubot expects regex = new RegExp("^@#{bot.mention_name}\\b", "i") hubot_msg = message.replace(regex, "#{bot.mention_name}: ") self.receive new TextMessage(author, hubot_msg) bot.onPrivateMessage (from, message) -> author = {} author.reply_to = from # add extra details if this message is from a known user author_data = self.userForId(self.userIdFromJid(from)) if author_data author.name = author_data.name author.mention_name = author_data.mention_name author.jid = author_data.jid # remove leading @mention name if present and format the message like # "name: message" which is what hubot expects regex = new RegExp("^@#{bot.mention_name}\\b", "i") message = message.replace(regex, "") hubot_msg = "#{bot.mention_name}: #{message}" self.receive new TextMessage(author, hubot_msg) # Join rooms automatically when invited bot.onInvite (room_jid, from_jid, message) => console.log "Got invite to #{room_jid} from #{from_jid} - joining" bot.join room_jid bot.connect() @bot = bot userIdFromJid: (jid) -> try return jid.match(/^\d+_(\d+)@chat\./)[1] catch e console.log "Bad user JID: #{jid}" return null roomNameFromJid: (jid) -> try return jid.match(/^\d+_(.+)@conf\./)[1] catch e console.log "Bad room JID: #{jid}" return null # Convenience HTTP Methods for posting on behalf of the token"d user get: (path, callback) -> @request "GET", path, null, callback post: (path, body, callback) -> @request "POST", path, body, callback request: (method, path, body, callback) -> console.log method, path, body host = @options.host or "api.hipchat.com" headers = "Host": host unless @options.token callback "No API token provided to Hubot", null return options = "agent" : false "host" : host "port" : 443 "path" : path += "?auth_token=#{@options.token}" "method" : method "headers": headers if method is "POST" headers["Content-Type"] = "application/x-www-form-urlencoded" options.headers["Content-Length"] = body.length request = HTTPS.request options, (response) -> data = "" response.on "data", (chunk) -> data += chunk response.on "end", -> if response.statusCode >= 400 console.log "HipChat API error: #{response.statusCode}" try callback null, JSON.parse(data) catch err callback null, data or { } response.on "error", (err) -> callback err, null if method is "POST" request.end(body, 'binary') else request.end() request.on "error", (err) -> console.log err console.log err.stack callback err exports.use = (robot) -> new HipChat robot
[ { "context": "checked', true)\n # else if el.attr('name') == 'Body Carve'\n # otherEl = $(\"[name='Capture']\")\n # ", "end": 1964, "score": 0.9997100830078125, "start": 1954, "tag": "NAME", "value": "Body Carve" } ]
app/assets/javascripts/drops_calculator/dropsView.js.coffee
dwinings/drop-hunter
2
class desire.DropsView constructor: (@el) -> Handlebars.registerHelper 'ifValue', (conditional, options) -> if options.hash.value == conditional options.fn(@) else options.inverse(@) Handlebars.registerHelper 'formatDropQuantity', (qty) -> return '' if qty <= 1 || qty == null || qty == undefined return " (x#{qty})" @template = HandlebarsTemplates['drops_calculator/drop_list'] @context = {} @loaded = false @listeners = $.Callbacks() render: (@context) -> @el.html(@template(@context)) @checkboxes = $('input.check-box', @el) @toggleClickables = $('.drop-data-header', @el) @shinyInput = @el.find('.shiny-input') @checkboxes.each -> el = $(this) unless el.attr('name') == 'Capture' || el.attr('name') == 'Virus Reward' el.prop('checked', true) @bind() @loaded = true bind: -> @toggleClickables.click @toggleDropTable @checkboxes.change @onCheckboxChange @checkboxes.click (e) -> e.stopPropagation() @shinyInput.click (e) -> e.stopPropagation() numShinies: -> @shinyInput.val() || null selectedBreaks: -> result = [] $('.check-box:checked', @el).each (_, el) => result.push parseInt($(el).attr('breakid')) result container: (el) -> el.parents('.drop-data-container') expanderDiv: (container) -> $('.part-group-expander', container) expanderIcon: (container) -> expanderIcon = $('.glyphicon-triangle-right', container) onCheckboxChange: (e) => # Disable this for now, since MHGen has multiple capture/carve groups. # el = $(e.target) # I know, body carve and capture should be radio buttons... # if el.attr('name') == 'Capture' # otherEl = $("[name='Body Carve']") # if otherEl.is(':checked') # otherEl.prop('checked', false) # else # otherEl.prop('checked', true) # else if el.attr('name') == 'Body Carve' # otherEl = $("[name='Capture']") # if otherEl.is(':checked') # otherEl.prop('checked', false) # else # otherEl.prop('checked', true) toggleDropTable: (e) => container = @container($(e.target)) expanderDiv = @expanderDiv(container) expanderIcon = @expanderIcon(container) if !expanderDiv.attr('expanded') || expanderDiv.attr('expanded') == 'false' trueHeight = expanderDiv.children().outerHeight() transform = "rotate(90deg)" expanderDiv.attr('expanded', true) else trueHeight = 0 transform = "rotate(0deg)" expanderDiv.attr('expanded', false) expanderIcon.css("transform", transform) expanderDiv.css('max-height', trueHeight)
88339
class desire.DropsView constructor: (@el) -> Handlebars.registerHelper 'ifValue', (conditional, options) -> if options.hash.value == conditional options.fn(@) else options.inverse(@) Handlebars.registerHelper 'formatDropQuantity', (qty) -> return '' if qty <= 1 || qty == null || qty == undefined return " (x#{qty})" @template = HandlebarsTemplates['drops_calculator/drop_list'] @context = {} @loaded = false @listeners = $.Callbacks() render: (@context) -> @el.html(@template(@context)) @checkboxes = $('input.check-box', @el) @toggleClickables = $('.drop-data-header', @el) @shinyInput = @el.find('.shiny-input') @checkboxes.each -> el = $(this) unless el.attr('name') == 'Capture' || el.attr('name') == 'Virus Reward' el.prop('checked', true) @bind() @loaded = true bind: -> @toggleClickables.click @toggleDropTable @checkboxes.change @onCheckboxChange @checkboxes.click (e) -> e.stopPropagation() @shinyInput.click (e) -> e.stopPropagation() numShinies: -> @shinyInput.val() || null selectedBreaks: -> result = [] $('.check-box:checked', @el).each (_, el) => result.push parseInt($(el).attr('breakid')) result container: (el) -> el.parents('.drop-data-container') expanderDiv: (container) -> $('.part-group-expander', container) expanderIcon: (container) -> expanderIcon = $('.glyphicon-triangle-right', container) onCheckboxChange: (e) => # Disable this for now, since MHGen has multiple capture/carve groups. # el = $(e.target) # I know, body carve and capture should be radio buttons... # if el.attr('name') == 'Capture' # otherEl = $("[name='Body Carve']") # if otherEl.is(':checked') # otherEl.prop('checked', false) # else # otherEl.prop('checked', true) # else if el.attr('name') == '<NAME>' # otherEl = $("[name='Capture']") # if otherEl.is(':checked') # otherEl.prop('checked', false) # else # otherEl.prop('checked', true) toggleDropTable: (e) => container = @container($(e.target)) expanderDiv = @expanderDiv(container) expanderIcon = @expanderIcon(container) if !expanderDiv.attr('expanded') || expanderDiv.attr('expanded') == 'false' trueHeight = expanderDiv.children().outerHeight() transform = "rotate(90deg)" expanderDiv.attr('expanded', true) else trueHeight = 0 transform = "rotate(0deg)" expanderDiv.attr('expanded', false) expanderIcon.css("transform", transform) expanderDiv.css('max-height', trueHeight)
true
class desire.DropsView constructor: (@el) -> Handlebars.registerHelper 'ifValue', (conditional, options) -> if options.hash.value == conditional options.fn(@) else options.inverse(@) Handlebars.registerHelper 'formatDropQuantity', (qty) -> return '' if qty <= 1 || qty == null || qty == undefined return " (x#{qty})" @template = HandlebarsTemplates['drops_calculator/drop_list'] @context = {} @loaded = false @listeners = $.Callbacks() render: (@context) -> @el.html(@template(@context)) @checkboxes = $('input.check-box', @el) @toggleClickables = $('.drop-data-header', @el) @shinyInput = @el.find('.shiny-input') @checkboxes.each -> el = $(this) unless el.attr('name') == 'Capture' || el.attr('name') == 'Virus Reward' el.prop('checked', true) @bind() @loaded = true bind: -> @toggleClickables.click @toggleDropTable @checkboxes.change @onCheckboxChange @checkboxes.click (e) -> e.stopPropagation() @shinyInput.click (e) -> e.stopPropagation() numShinies: -> @shinyInput.val() || null selectedBreaks: -> result = [] $('.check-box:checked', @el).each (_, el) => result.push parseInt($(el).attr('breakid')) result container: (el) -> el.parents('.drop-data-container') expanderDiv: (container) -> $('.part-group-expander', container) expanderIcon: (container) -> expanderIcon = $('.glyphicon-triangle-right', container) onCheckboxChange: (e) => # Disable this for now, since MHGen has multiple capture/carve groups. # el = $(e.target) # I know, body carve and capture should be radio buttons... # if el.attr('name') == 'Capture' # otherEl = $("[name='Body Carve']") # if otherEl.is(':checked') # otherEl.prop('checked', false) # else # otherEl.prop('checked', true) # else if el.attr('name') == 'PI:NAME:<NAME>END_PI' # otherEl = $("[name='Capture']") # if otherEl.is(':checked') # otherEl.prop('checked', false) # else # otherEl.prop('checked', true) toggleDropTable: (e) => container = @container($(e.target)) expanderDiv = @expanderDiv(container) expanderIcon = @expanderIcon(container) if !expanderDiv.attr('expanded') || expanderDiv.attr('expanded') == 'false' trueHeight = expanderDiv.children().outerHeight() transform = "rotate(90deg)" expanderDiv.attr('expanded', true) else trueHeight = 0 transform = "rotate(0deg)" expanderDiv.attr('expanded', false) expanderIcon.css("transform", transform) expanderDiv.css('max-height', trueHeight)
[ { "context": "gnatedCronHandler req, res\n res.send('Great work, Captain Cron! I can take it from here.')\n res.end()\n # TODO:", "end": 1580, "score": 0.9979657530784607, "start": 1568, "tag": "NAME", "value": "Captain Cron" }, { "context": "l\n to:\n email: if DEBUGGING then 'nick@codecombat.com' else user.get('email')\n name: name\n ", "end": 4989, "score": 0.9999259114265442, "start": 4970, "tag": "EMAIL", "value": "nick@codecombat.com" }, { "context": " email: config.mail.username\n name: 'CodeCombat'\n subject: \"Your #{session.levelName} #{se", "end": 5114, "score": 0.9651476740837097, "start": 5104, "tag": "USERNAME", "value": "CodeCombat" }, { "context": "Scores\"\n substitutions:\n username: name\n days_ago: daysAgo\n wins: victo", "end": 5273, "score": 0.6628978252410889, "start": 5269, "tag": "USERNAME", "value": "name" }, { "context": "gnatedCronHandler req, res\n res.send('Great work, Captain Cron! I can take it from here.')\n res.end()\n emailDa", "end": 8907, "score": 0.986571192741394, "start": 8895, "tag": "NAME", "value": "Captain Cron" }, { "context": "firstName')}\" else user.get('name')\n name = 'Hero' if not name or name in ['Anoner', 'Anonymous']\n ", "end": 11472, "score": 0.7670045495033264, "start": 11468, "tag": "NAME", "value": "Hero" }, { "context": "me')\n name = 'Hero' if not name or name in ['Anoner', 'Anonymous']\n #secretLevel = switch user.g", "end": 11505, "score": 0.9848208427429199, "start": 11499, "tag": "NAME", "value": "Anoner" }, { "context": "Number') % 8\n # when 0, 1, 2, 3 then name: 'Forgetful Gemsmith', slug: 'forgetful-gemsmith'\n # when 4, 5, ", "end": 11636, "score": 0.9659350514411926, "start": 11618, "tag": "NAME", "value": "Forgetful Gemsmith" }, { "context": "l\n to:\n email: if DEBUGGING then 'nick@codecombat.com' else user.get('email')\n name: name\n ", "end": 12684, "score": 0.9999241232872009, "start": 12665, "tag": "EMAIL", "value": "nick@codecombat.com" }, { "context": " email: config.mail.username\n name: 'CodeCombat'\n substitutions:\n username: name\n", "end": 12809, "score": 0.9959573149681091, "start": 12799, "tag": "USERNAME", "value": "CodeCombat" }, { "context": "Combat'\n substitutions:\n username: name\n days_ago: daysAgo\n nextLevelNa", "end": 12858, "score": 0.8942802548408508, "start": 12854, "tag": "USERNAME", "value": "name" } ]
server/routes/mail.coffee
IngJuanRuiz/codecombat
0
mailChimp = require '../lib/mail-chimp' User = require '../models/User' errors = require '../commons/errors' config = require '../../server_config' LevelSession = require '../models/LevelSession' Level = require '../models/Level' log = require 'winston' sendgrid = require '../sendgrid' wrap = require 'co-express' unsubscribe = require '../commons/unsubscribe' co = require 'co' module.exports.setup = (app) -> app.all config.mail.mailChimpWebhook, handleMailChimpWebHook app.get '/mail/cron/ladder-update', handleLadderUpdate app.get '/mail/cron/next-steps', handleNextSteps DEBUGGING = false LADDER_PREGAME_INTERVAL = 2 * 3600 * 1000 # Send emails two hours before players last submitted. getTimeFromDaysAgo = (now, daysAgo) -> t = now - 86400 * 1000 * daysAgo - LADDER_PREGAME_INTERVAL isRequestFromDesignatedCronHandler = (req, res) -> requestIP = req.headers['x-forwarded-for']?.replace(' ', '').split(',')[0] if requestIP isnt config.mail.cronHandlerPublicIP and requestIP isnt config.mail.cronHandlerPrivateIP console.log "RECEIVED REQUEST FROM IP #{requestIP}(headers indicate #{req.headers['x-forwarded-for']}" console.log 'UNAUTHORIZED ATTEMPT TO SEND TRANSACTIONAL LADDER EMAIL THROUGH CRON MAIL HANDLER' res.send('You aren\'t authorized to perform that action. Only the specified Cron handler may perform that action.') res.end() return false return true ### Ladder Update Email ### handleLadderUpdate = (req, res) -> return unless DEBUGGING or isRequestFromDesignatedCronHandler req, res res.send('Great work, Captain Cron! I can take it from here.') res.end() # TODO: Sendgrid cannot do the kind of logical conditions and collection iteration that Sendwithus could, so we need to do the template in our code. For now, these emails are disabled. return # TODO: somehow fetch the histograms #emailDays = [1, 2, 4, 7, 14, 30] emailDays = [1, 3, 7] # Reduced to keep smaller monthly recipient footprint now = new Date() for daysAgo in emailDays # Get every session that was submitted in a 5-minute window after the time. startTime = getTimeFromDaysAgo now, daysAgo endTime = startTime + 5 * 60 * 1000 if DEBUGGING endTime = startTime + 15 * 60 * 1000 # Debugging: make sure there's something to send findParameters = {submitted: true, submitDate: {$gt: new Date(startTime), $lte: new Date(endTime)}} # TODO: think about putting screenshots in the email selectString = 'creator team levelName levelID totalScore matches submitted submitDate scoreHistory level.original unsubscribed' query = LevelSession.find(findParameters) .select(selectString) .lean() do (daysAgo) -> query.exec (err, results) -> if err log.error "Couldn't fetch ladder updates for #{findParameters}\nError: #{err}" return errors.serverError res, "Ladder update email query failed: #{JSON.stringify(err)}" #log.info "Found #{results.length} ladder sessions to email updates about for #{daysAgo} day(s) ago." sendLadderUpdateEmail result, now, daysAgo for result in results sendLadderUpdateEmail = (session, now, daysAgo) -> User.findOne({_id: session.creator}).select('name email firstName lastName emailSubscriptions emails preferredLanguage').exec (err, user) -> return if not user.get('email') if err log.error "Couldn't find user for #{session.creator} from session #{session._id}" return allowNotes = user.isEmailSubscriptionEnabled 'anyNotes' unless user.get('email') and allowNotes and not session.unsubscribed #log.info "Not sending email to #{user.get('email')} #{user.get('name')} because they only want emails about #{user.get('emailSubscriptions')}, #{user.get('emails')} - session unsubscribed: #{session.unsubscribed}" return unless session.levelName and session.team #log.info "Not sending email to #{user.get('email')} #{user.get('name')} because the session had levelName #{session.levelName} or team #{session.team} in it." return name = if user.get('firstName') and user.get('lastName') then "#{user.get('firstName')}" else user.get('name') name = 'Wizard' if not name or name is 'Anonymous' # Fetch the most recent defeat and victory, if there are any. # (We could look at strongest/weakest, but we'd have to fetch everyone, or denormalize more.) matches = _.filter session.matches, (match) -> match.date >= getTimeFromDaysAgo now, daysAgo defeats = _.filter matches, (match) -> match.metrics.rank is 1 and match.opponents[0].metrics.rank is 0 victories = _.filter matches, (match) -> match.metrics.rank is 0 and match.opponents[0].metrics.rank is 1 defeat = _.last defeats victory = _.last victories sendEmail = co.wrap (defeatContext, victoryContext, levelVersionsContext) -> message = templateId: sendgrid.templates.ladder_update_email to: email: if DEBUGGING then 'nick@codecombat.com' else user.get('email') name: name from: email: config.mail.username name: 'CodeCombat' subject: "Your #{session.levelName} #{session.team[0].toUpperCase() + session.team.substr(1)} Scores" substitutions: username: name days_ago: daysAgo wins: victories.length losses: defeats.length total_score: Math.round(session.totalScore * 100) team: session.team team_name: session.team[0].toUpperCase() + session.team.substr(1) level_name: session.levelName session_id: session._id ladder_url: "http://codecombat.com/play/ladder/#{session.levelID}#my-matches" score_history_graph_url: getScoreHistoryGraphURL session, daysAgo defeat: defeatContext victory: victoryContext levelVersions: levelVersionsContext #log.info "Sending ladder update email to #{message.to.email} with #{message.substitutions.wins} wins and #{message.substitutions.losses} losses since #{daysAgo} day(s) ago." try yield sendgrid.api.send message catch err console.error "Error sending ladder update email:", err urlForMatch = (match) -> "http://codecombat.com/play/level/#{session.levelID}?team=#{session.team}&opponent=#{match.opponents[0].sessionID}" onFetchedDefeatedOpponent = (err, defeatedOpponent) -> if err log.error "Couldn't find defeateded opponent: #{err}" defeatedOpponent = null victoryContext = {opponent_name: defeatedOpponent?.name ? 'Anonymous', url: urlForMatch(victory)} if victory onFetchedVictoriousOpponent = (err, victoriousOpponent) -> if err log.error "Couldn't find victorious opponent: #{err}" victoriousOpponent = null defeatContext = {opponent_name: victoriousOpponent?.name ? 'Anonymous', url: urlForMatch(defeat)} if defeat Level.find({original: session.level.original, created: {$gt: session.submitDate}}).select('created commitMessage version').sort('-created').lean().exec (err, levelVersions) -> sendEmail defeatContext, victoryContext, (if levelVersions.length then levelVersions else null) if defeat User.findOne({_id: defeat.opponents[0].userID}).select('name').lean().exec onFetchedVictoriousOpponent else onFetchedVictoriousOpponent null, null if victory User.findOne({_id: victory.opponents[0].userID}).select('name').lean().exec onFetchedDefeatedOpponent else onFetchedDefeatedOpponent null, null getScoreHistoryGraphURL = (session, daysAgo) -> # Totally duplicated in My Matches tab for now until we figure out what we're doing. since = new Date() - 86400 * 1000 * daysAgo scoreHistory = (s for s in session.scoreHistory ? [] when s[0] >= since) return '' unless scoreHistory.length > 1 scoreHistory = _.last scoreHistory, 100 # Chart URL needs to be under 2048 characters for GET times = (s[0] for s in scoreHistory) times = ((100 * (t - times[0]) / (times[times.length - 1] - times[0])).toFixed(1) for t in times) scores = (s[1] for s in scoreHistory) lowest = _.min scores #.concat([0]) highest = _.max scores #.concat(50) scores = (Math.round(100 * (s - lowest) / (highest - lowest)) for s in scores) currentScore = Math.round scoreHistory[scoreHistory.length - 1][1] * 100 minScore = Math.round(100 * lowest) maxScore = Math.round(100 * highest) chartData = times.join(',') + '|' + scores.join(',') "https://chart.googleapis.com/chart?chs=600x75&cht=lxy&chtt=Score%3A+#{currentScore}&chts=222222,12,r&chf=a,s,000000FF&chls=2&chd=t:#{chartData}&chxt=y&chxr=0,#{minScore},#{maxScore}" ### End Ladder Update Email ### ### Next Steps Email ### handleNextSteps = (req, res) -> return unless DEBUGGING or isRequestFromDesignatedCronHandler req, res res.send('Great work, Captain Cron! I can take it from here.') res.end() emailDays = [1] now = new Date() for daysAgo in emailDays # Get every User that was created in a 5-minute window after the time. startTime = getTimeFromDaysAgo now, daysAgo endTime = startTime + 5 * 60 * 1000 findParameters = {dateCreated: {$gt: new Date(startTime), $lte: new Date(endTime)}, emailLower: {$exists: true}} selectString = 'name firstName lastName lastLevel points email gender emailSubscriptions emails dateCreated preferredLanguage aceConfig.language activity stats earned testGroupNumber ageRange courseInstances' query = User.find(findParameters).select(selectString) do (daysAgo) -> query.exec (err, results) -> if err log.error "Couldn't fetch next steps users for #{findParameters}\nError: #{err}" return errors.serverError res, "Next steps email query failed: #{JSON.stringify(err)}" log.info "Found #{results.length} next-steps users to email updates about for #{daysAgo} day(s) ago." if DEBUGGING sendNextStepsEmail result, now, daysAgo for result in results module.exports.sendNextStepsEmail = sendNextStepsEmail = (user, now, daysAgo) -> return log.info "Not sending next steps email to user with no email address" if not user.get('email') return log.debug "Not sending next steps email to teacher based on role" if user.isTeacher() unless user.isEmailSubscriptionEnabled('generalNews') and user.isEmailSubscriptionEnabled('anyNotes') log.info "Not sending email to #{user.get('email')} #{user.get('name')} because they only want emails about #{JSON.stringify(user.get('emails'))}" if DEBUGGING return LevelSession.find({creator: user.get('_id') + ''}).select('levelName levelID changed state.complete playtime').lean().exec (err, sessions) -> return log.error "Couldn't find sessions for #{user.get('email')} #{user.get('name')}: #{err}" if err complete = (s for s in sessions when s.state?.complete) incomplete = (s for s in sessions when not s.state?.complete) return if complete.length < 2 # TODO: find the next level to do somehow, for real if incomplete.length nextLevel = name: incomplete[0].levelName, slug: incomplete[0].levelID else nextLevel = null err = null do co.wrap (err, nextLevel) -> return log.error "Couldn't find next level for #{user.get('email')} #{user.get('name')}: #{err}" if err name = if user.get('firstName') and user.get('lastName') then "#{user.get('firstName')}" else user.get('name') name = 'Hero' if not name or name in ['Anoner', 'Anonymous'] #secretLevel = switch user.get('testGroupNumber') % 8 # when 0, 1, 2, 3 then name: 'Forgetful Gemsmith', slug: 'forgetful-gemsmith' # when 4, 5, 6, 7 then name: 'Signs and Portents', slug: 'signs-and-portents' secretLevel = name: 'Signs and Portents', slug: 'signs-and-portents' # We turned off this test for now and are sending everyone to forgetful-gemsmith # TODO: make this smarter, actually data-driven, looking at all available sessions shadowGuardSession = _.find sessions, levelID: 'shadow-guard' isFast = shadowGuardSession and shadowGuardSession.playtime < 90 # Average is 107s isVeryFast = shadowGuardSession and shadowGuardSession.playtime < 75 isAdult = user.get('ageRange') in ['18-24', '25-34', '35-44', '45-100'] isKid = not isAdult # Assume kid if not specified # Used to use these categories to customize the email; not doing it right now. TODO: customize it again in Sendgrid. # TODO: do something with the preferredLanguage? message = templateId: sendgrid.templates.next_steps_email to: email: if DEBUGGING then 'nick@codecombat.com' else user.get('email') name: name from: email: config.mail.username name: 'CodeCombat' substitutions: username: name days_ago: daysAgo nextLevelName: nextLevel?.name nextLevelLink: if nextLevel then "http://codecombat.com/play/level/#{nextLevel.slug}" else null secretLevelName: secretLevel.name secretLevelLink: "http://codecombat.com/play/level/#{secretLevel.slug}" levelsComplete: complete.length isCoursePlayer: user.get('role') is 'student' # I hate Sendgrid variable interpolation; it works so inconsistently. Hack around it for now. message.substitutions.nextLevelTemplate = """ <p>Hail, #{message.substitutions.username}!</p> <p>You've done #{message.substitutions.levelsComplete} levels; now what?</p> <ul> #{if message.substitutions.nextLevelLink then '<li>Play the next level: <strong><a href="{{ message.substitutions.nextLevelLink }}">{{ message.substitutions.nextLevelName }}</a></strong></li' else ''} <li>Play this <em>secret</em> level: <strong><a href="#{message.substitutions.secretLevelLink}">#{message.substitutions.secretLevelName}</a></strong></li> <li><strong><a href="http://codecombat.com/#{if message.substitutions.isCoursePlayer then 'students">Choose a level</a></strong> to play next</li>' else 'play">Choose a level</a></strong> from one of the five worlds</li>'} </ul> """ log.info "Sending next steps email to #{message.to.email} with #{message.substitutions.nextLevelName} next and #{message.substitutions.levelsComplete} levels complete since #{daysAgo} day(s) ago." if DEBUGGING try yield sendgrid.api.send message catch err console.error "Error sending next steps email:", err ### End Next Steps Email ### handleMailChimpWebHook = wrap (req, res) -> post = req.body unless post.type in ['unsubscribe', 'profile', 'upemail'] res.send 'Bad post type' return res.end() email = post.data.email or post.data.old_email unless email res.send 'No email provided' return res.end() if post.data.web_id user = yield User.findOne { 'mailChimp.leid': post.data.web_id } if not user user = yield User.findOne { 'mailChimp.email': email } if not user throw new errors.NotFound('MailChimp subscriber not found') if not user.get('emailVerified') return res.send('User email unverified') if post.type is 'profile' handleProfileUpdate(user, post) else if post.type is 'upemail' handleUnsubscribe(user) # just unsubscribe from MailChimp else if post.type is 'unsubscribe' yield unsubscribe.unsubscribeEmailFromMarketingEmails(user.get('emailLower')) # unsubscribe all emails user.updatedMailChimp = true # so as not to echo back to mailchimp yield user.save() res.end('Success') module.exports.handleProfileUpdate = handleProfileUpdate = (user, post) -> mailChimpSubs = post.data.merges.INTERESTS.split(', ') for interest in mailChimp.interests user.setEmailSubscription interest.property, interest.mailChimpLabel in mailChimpSubs fname = post.data.merges.FNAME user.set('firstName', fname) if fname lname = post.data.merges.LNAME user.set('lastName', lname) if lname user.set 'mailChimp.email', post.data.email user.set 'mailChimp.euid', post.data.id module.exports.handleUnsubscribe = handleUnsubscribe = (user) -> user.set 'emailSubscriptions', [] for interest in mailChimp.interests user.setEmailSubscription interest.property, false user.set 'mailChimp', undefined
115615
mailChimp = require '../lib/mail-chimp' User = require '../models/User' errors = require '../commons/errors' config = require '../../server_config' LevelSession = require '../models/LevelSession' Level = require '../models/Level' log = require 'winston' sendgrid = require '../sendgrid' wrap = require 'co-express' unsubscribe = require '../commons/unsubscribe' co = require 'co' module.exports.setup = (app) -> app.all config.mail.mailChimpWebhook, handleMailChimpWebHook app.get '/mail/cron/ladder-update', handleLadderUpdate app.get '/mail/cron/next-steps', handleNextSteps DEBUGGING = false LADDER_PREGAME_INTERVAL = 2 * 3600 * 1000 # Send emails two hours before players last submitted. getTimeFromDaysAgo = (now, daysAgo) -> t = now - 86400 * 1000 * daysAgo - LADDER_PREGAME_INTERVAL isRequestFromDesignatedCronHandler = (req, res) -> requestIP = req.headers['x-forwarded-for']?.replace(' ', '').split(',')[0] if requestIP isnt config.mail.cronHandlerPublicIP and requestIP isnt config.mail.cronHandlerPrivateIP console.log "RECEIVED REQUEST FROM IP #{requestIP}(headers indicate #{req.headers['x-forwarded-for']}" console.log 'UNAUTHORIZED ATTEMPT TO SEND TRANSACTIONAL LADDER EMAIL THROUGH CRON MAIL HANDLER' res.send('You aren\'t authorized to perform that action. Only the specified Cron handler may perform that action.') res.end() return false return true ### Ladder Update Email ### handleLadderUpdate = (req, res) -> return unless DEBUGGING or isRequestFromDesignatedCronHandler req, res res.send('Great work, <NAME>! I can take it from here.') res.end() # TODO: Sendgrid cannot do the kind of logical conditions and collection iteration that Sendwithus could, so we need to do the template in our code. For now, these emails are disabled. return # TODO: somehow fetch the histograms #emailDays = [1, 2, 4, 7, 14, 30] emailDays = [1, 3, 7] # Reduced to keep smaller monthly recipient footprint now = new Date() for daysAgo in emailDays # Get every session that was submitted in a 5-minute window after the time. startTime = getTimeFromDaysAgo now, daysAgo endTime = startTime + 5 * 60 * 1000 if DEBUGGING endTime = startTime + 15 * 60 * 1000 # Debugging: make sure there's something to send findParameters = {submitted: true, submitDate: {$gt: new Date(startTime), $lte: new Date(endTime)}} # TODO: think about putting screenshots in the email selectString = 'creator team levelName levelID totalScore matches submitted submitDate scoreHistory level.original unsubscribed' query = LevelSession.find(findParameters) .select(selectString) .lean() do (daysAgo) -> query.exec (err, results) -> if err log.error "Couldn't fetch ladder updates for #{findParameters}\nError: #{err}" return errors.serverError res, "Ladder update email query failed: #{JSON.stringify(err)}" #log.info "Found #{results.length} ladder sessions to email updates about for #{daysAgo} day(s) ago." sendLadderUpdateEmail result, now, daysAgo for result in results sendLadderUpdateEmail = (session, now, daysAgo) -> User.findOne({_id: session.creator}).select('name email firstName lastName emailSubscriptions emails preferredLanguage').exec (err, user) -> return if not user.get('email') if err log.error "Couldn't find user for #{session.creator} from session #{session._id}" return allowNotes = user.isEmailSubscriptionEnabled 'anyNotes' unless user.get('email') and allowNotes and not session.unsubscribed #log.info "Not sending email to #{user.get('email')} #{user.get('name')} because they only want emails about #{user.get('emailSubscriptions')}, #{user.get('emails')} - session unsubscribed: #{session.unsubscribed}" return unless session.levelName and session.team #log.info "Not sending email to #{user.get('email')} #{user.get('name')} because the session had levelName #{session.levelName} or team #{session.team} in it." return name = if user.get('firstName') and user.get('lastName') then "#{user.get('firstName')}" else user.get('name') name = 'Wizard' if not name or name is 'Anonymous' # Fetch the most recent defeat and victory, if there are any. # (We could look at strongest/weakest, but we'd have to fetch everyone, or denormalize more.) matches = _.filter session.matches, (match) -> match.date >= getTimeFromDaysAgo now, daysAgo defeats = _.filter matches, (match) -> match.metrics.rank is 1 and match.opponents[0].metrics.rank is 0 victories = _.filter matches, (match) -> match.metrics.rank is 0 and match.opponents[0].metrics.rank is 1 defeat = _.last defeats victory = _.last victories sendEmail = co.wrap (defeatContext, victoryContext, levelVersionsContext) -> message = templateId: sendgrid.templates.ladder_update_email to: email: if DEBUGGING then '<EMAIL>' else user.get('email') name: name from: email: config.mail.username name: 'CodeCombat' subject: "Your #{session.levelName} #{session.team[0].toUpperCase() + session.team.substr(1)} Scores" substitutions: username: name days_ago: daysAgo wins: victories.length losses: defeats.length total_score: Math.round(session.totalScore * 100) team: session.team team_name: session.team[0].toUpperCase() + session.team.substr(1) level_name: session.levelName session_id: session._id ladder_url: "http://codecombat.com/play/ladder/#{session.levelID}#my-matches" score_history_graph_url: getScoreHistoryGraphURL session, daysAgo defeat: defeatContext victory: victoryContext levelVersions: levelVersionsContext #log.info "Sending ladder update email to #{message.to.email} with #{message.substitutions.wins} wins and #{message.substitutions.losses} losses since #{daysAgo} day(s) ago." try yield sendgrid.api.send message catch err console.error "Error sending ladder update email:", err urlForMatch = (match) -> "http://codecombat.com/play/level/#{session.levelID}?team=#{session.team}&opponent=#{match.opponents[0].sessionID}" onFetchedDefeatedOpponent = (err, defeatedOpponent) -> if err log.error "Couldn't find defeateded opponent: #{err}" defeatedOpponent = null victoryContext = {opponent_name: defeatedOpponent?.name ? 'Anonymous', url: urlForMatch(victory)} if victory onFetchedVictoriousOpponent = (err, victoriousOpponent) -> if err log.error "Couldn't find victorious opponent: #{err}" victoriousOpponent = null defeatContext = {opponent_name: victoriousOpponent?.name ? 'Anonymous', url: urlForMatch(defeat)} if defeat Level.find({original: session.level.original, created: {$gt: session.submitDate}}).select('created commitMessage version').sort('-created').lean().exec (err, levelVersions) -> sendEmail defeatContext, victoryContext, (if levelVersions.length then levelVersions else null) if defeat User.findOne({_id: defeat.opponents[0].userID}).select('name').lean().exec onFetchedVictoriousOpponent else onFetchedVictoriousOpponent null, null if victory User.findOne({_id: victory.opponents[0].userID}).select('name').lean().exec onFetchedDefeatedOpponent else onFetchedDefeatedOpponent null, null getScoreHistoryGraphURL = (session, daysAgo) -> # Totally duplicated in My Matches tab for now until we figure out what we're doing. since = new Date() - 86400 * 1000 * daysAgo scoreHistory = (s for s in session.scoreHistory ? [] when s[0] >= since) return '' unless scoreHistory.length > 1 scoreHistory = _.last scoreHistory, 100 # Chart URL needs to be under 2048 characters for GET times = (s[0] for s in scoreHistory) times = ((100 * (t - times[0]) / (times[times.length - 1] - times[0])).toFixed(1) for t in times) scores = (s[1] for s in scoreHistory) lowest = _.min scores #.concat([0]) highest = _.max scores #.concat(50) scores = (Math.round(100 * (s - lowest) / (highest - lowest)) for s in scores) currentScore = Math.round scoreHistory[scoreHistory.length - 1][1] * 100 minScore = Math.round(100 * lowest) maxScore = Math.round(100 * highest) chartData = times.join(',') + '|' + scores.join(',') "https://chart.googleapis.com/chart?chs=600x75&cht=lxy&chtt=Score%3A+#{currentScore}&chts=222222,12,r&chf=a,s,000000FF&chls=2&chd=t:#{chartData}&chxt=y&chxr=0,#{minScore},#{maxScore}" ### End Ladder Update Email ### ### Next Steps Email ### handleNextSteps = (req, res) -> return unless DEBUGGING or isRequestFromDesignatedCronHandler req, res res.send('Great work, <NAME>! I can take it from here.') res.end() emailDays = [1] now = new Date() for daysAgo in emailDays # Get every User that was created in a 5-minute window after the time. startTime = getTimeFromDaysAgo now, daysAgo endTime = startTime + 5 * 60 * 1000 findParameters = {dateCreated: {$gt: new Date(startTime), $lte: new Date(endTime)}, emailLower: {$exists: true}} selectString = 'name firstName lastName lastLevel points email gender emailSubscriptions emails dateCreated preferredLanguage aceConfig.language activity stats earned testGroupNumber ageRange courseInstances' query = User.find(findParameters).select(selectString) do (daysAgo) -> query.exec (err, results) -> if err log.error "Couldn't fetch next steps users for #{findParameters}\nError: #{err}" return errors.serverError res, "Next steps email query failed: #{JSON.stringify(err)}" log.info "Found #{results.length} next-steps users to email updates about for #{daysAgo} day(s) ago." if DEBUGGING sendNextStepsEmail result, now, daysAgo for result in results module.exports.sendNextStepsEmail = sendNextStepsEmail = (user, now, daysAgo) -> return log.info "Not sending next steps email to user with no email address" if not user.get('email') return log.debug "Not sending next steps email to teacher based on role" if user.isTeacher() unless user.isEmailSubscriptionEnabled('generalNews') and user.isEmailSubscriptionEnabled('anyNotes') log.info "Not sending email to #{user.get('email')} #{user.get('name')} because they only want emails about #{JSON.stringify(user.get('emails'))}" if DEBUGGING return LevelSession.find({creator: user.get('_id') + ''}).select('levelName levelID changed state.complete playtime').lean().exec (err, sessions) -> return log.error "Couldn't find sessions for #{user.get('email')} #{user.get('name')}: #{err}" if err complete = (s for s in sessions when s.state?.complete) incomplete = (s for s in sessions when not s.state?.complete) return if complete.length < 2 # TODO: find the next level to do somehow, for real if incomplete.length nextLevel = name: incomplete[0].levelName, slug: incomplete[0].levelID else nextLevel = null err = null do co.wrap (err, nextLevel) -> return log.error "Couldn't find next level for #{user.get('email')} #{user.get('name')}: #{err}" if err name = if user.get('firstName') and user.get('lastName') then "#{user.get('firstName')}" else user.get('name') name = '<NAME>' if not name or name in ['<NAME>', 'Anonymous'] #secretLevel = switch user.get('testGroupNumber') % 8 # when 0, 1, 2, 3 then name: '<NAME>', slug: 'forgetful-gemsmith' # when 4, 5, 6, 7 then name: 'Signs and Portents', slug: 'signs-and-portents' secretLevel = name: 'Signs and Portents', slug: 'signs-and-portents' # We turned off this test for now and are sending everyone to forgetful-gemsmith # TODO: make this smarter, actually data-driven, looking at all available sessions shadowGuardSession = _.find sessions, levelID: 'shadow-guard' isFast = shadowGuardSession and shadowGuardSession.playtime < 90 # Average is 107s isVeryFast = shadowGuardSession and shadowGuardSession.playtime < 75 isAdult = user.get('ageRange') in ['18-24', '25-34', '35-44', '45-100'] isKid = not isAdult # Assume kid if not specified # Used to use these categories to customize the email; not doing it right now. TODO: customize it again in Sendgrid. # TODO: do something with the preferredLanguage? message = templateId: sendgrid.templates.next_steps_email to: email: if DEBUGGING then '<EMAIL>' else user.get('email') name: name from: email: config.mail.username name: 'CodeCombat' substitutions: username: name days_ago: daysAgo nextLevelName: nextLevel?.name nextLevelLink: if nextLevel then "http://codecombat.com/play/level/#{nextLevel.slug}" else null secretLevelName: secretLevel.name secretLevelLink: "http://codecombat.com/play/level/#{secretLevel.slug}" levelsComplete: complete.length isCoursePlayer: user.get('role') is 'student' # I hate Sendgrid variable interpolation; it works so inconsistently. Hack around it for now. message.substitutions.nextLevelTemplate = """ <p>Hail, #{message.substitutions.username}!</p> <p>You've done #{message.substitutions.levelsComplete} levels; now what?</p> <ul> #{if message.substitutions.nextLevelLink then '<li>Play the next level: <strong><a href="{{ message.substitutions.nextLevelLink }}">{{ message.substitutions.nextLevelName }}</a></strong></li' else ''} <li>Play this <em>secret</em> level: <strong><a href="#{message.substitutions.secretLevelLink}">#{message.substitutions.secretLevelName}</a></strong></li> <li><strong><a href="http://codecombat.com/#{if message.substitutions.isCoursePlayer then 'students">Choose a level</a></strong> to play next</li>' else 'play">Choose a level</a></strong> from one of the five worlds</li>'} </ul> """ log.info "Sending next steps email to #{message.to.email} with #{message.substitutions.nextLevelName} next and #{message.substitutions.levelsComplete} levels complete since #{daysAgo} day(s) ago." if DEBUGGING try yield sendgrid.api.send message catch err console.error "Error sending next steps email:", err ### End Next Steps Email ### handleMailChimpWebHook = wrap (req, res) -> post = req.body unless post.type in ['unsubscribe', 'profile', 'upemail'] res.send 'Bad post type' return res.end() email = post.data.email or post.data.old_email unless email res.send 'No email provided' return res.end() if post.data.web_id user = yield User.findOne { 'mailChimp.leid': post.data.web_id } if not user user = yield User.findOne { 'mailChimp.email': email } if not user throw new errors.NotFound('MailChimp subscriber not found') if not user.get('emailVerified') return res.send('User email unverified') if post.type is 'profile' handleProfileUpdate(user, post) else if post.type is 'upemail' handleUnsubscribe(user) # just unsubscribe from MailChimp else if post.type is 'unsubscribe' yield unsubscribe.unsubscribeEmailFromMarketingEmails(user.get('emailLower')) # unsubscribe all emails user.updatedMailChimp = true # so as not to echo back to mailchimp yield user.save() res.end('Success') module.exports.handleProfileUpdate = handleProfileUpdate = (user, post) -> mailChimpSubs = post.data.merges.INTERESTS.split(', ') for interest in mailChimp.interests user.setEmailSubscription interest.property, interest.mailChimpLabel in mailChimpSubs fname = post.data.merges.FNAME user.set('firstName', fname) if fname lname = post.data.merges.LNAME user.set('lastName', lname) if lname user.set 'mailChimp.email', post.data.email user.set 'mailChimp.euid', post.data.id module.exports.handleUnsubscribe = handleUnsubscribe = (user) -> user.set 'emailSubscriptions', [] for interest in mailChimp.interests user.setEmailSubscription interest.property, false user.set 'mailChimp', undefined
true
mailChimp = require '../lib/mail-chimp' User = require '../models/User' errors = require '../commons/errors' config = require '../../server_config' LevelSession = require '../models/LevelSession' Level = require '../models/Level' log = require 'winston' sendgrid = require '../sendgrid' wrap = require 'co-express' unsubscribe = require '../commons/unsubscribe' co = require 'co' module.exports.setup = (app) -> app.all config.mail.mailChimpWebhook, handleMailChimpWebHook app.get '/mail/cron/ladder-update', handleLadderUpdate app.get '/mail/cron/next-steps', handleNextSteps DEBUGGING = false LADDER_PREGAME_INTERVAL = 2 * 3600 * 1000 # Send emails two hours before players last submitted. getTimeFromDaysAgo = (now, daysAgo) -> t = now - 86400 * 1000 * daysAgo - LADDER_PREGAME_INTERVAL isRequestFromDesignatedCronHandler = (req, res) -> requestIP = req.headers['x-forwarded-for']?.replace(' ', '').split(',')[0] if requestIP isnt config.mail.cronHandlerPublicIP and requestIP isnt config.mail.cronHandlerPrivateIP console.log "RECEIVED REQUEST FROM IP #{requestIP}(headers indicate #{req.headers['x-forwarded-for']}" console.log 'UNAUTHORIZED ATTEMPT TO SEND TRANSACTIONAL LADDER EMAIL THROUGH CRON MAIL HANDLER' res.send('You aren\'t authorized to perform that action. Only the specified Cron handler may perform that action.') res.end() return false return true ### Ladder Update Email ### handleLadderUpdate = (req, res) -> return unless DEBUGGING or isRequestFromDesignatedCronHandler req, res res.send('Great work, PI:NAME:<NAME>END_PI! I can take it from here.') res.end() # TODO: Sendgrid cannot do the kind of logical conditions and collection iteration that Sendwithus could, so we need to do the template in our code. For now, these emails are disabled. return # TODO: somehow fetch the histograms #emailDays = [1, 2, 4, 7, 14, 30] emailDays = [1, 3, 7] # Reduced to keep smaller monthly recipient footprint now = new Date() for daysAgo in emailDays # Get every session that was submitted in a 5-minute window after the time. startTime = getTimeFromDaysAgo now, daysAgo endTime = startTime + 5 * 60 * 1000 if DEBUGGING endTime = startTime + 15 * 60 * 1000 # Debugging: make sure there's something to send findParameters = {submitted: true, submitDate: {$gt: new Date(startTime), $lte: new Date(endTime)}} # TODO: think about putting screenshots in the email selectString = 'creator team levelName levelID totalScore matches submitted submitDate scoreHistory level.original unsubscribed' query = LevelSession.find(findParameters) .select(selectString) .lean() do (daysAgo) -> query.exec (err, results) -> if err log.error "Couldn't fetch ladder updates for #{findParameters}\nError: #{err}" return errors.serverError res, "Ladder update email query failed: #{JSON.stringify(err)}" #log.info "Found #{results.length} ladder sessions to email updates about for #{daysAgo} day(s) ago." sendLadderUpdateEmail result, now, daysAgo for result in results sendLadderUpdateEmail = (session, now, daysAgo) -> User.findOne({_id: session.creator}).select('name email firstName lastName emailSubscriptions emails preferredLanguage').exec (err, user) -> return if not user.get('email') if err log.error "Couldn't find user for #{session.creator} from session #{session._id}" return allowNotes = user.isEmailSubscriptionEnabled 'anyNotes' unless user.get('email') and allowNotes and not session.unsubscribed #log.info "Not sending email to #{user.get('email')} #{user.get('name')} because they only want emails about #{user.get('emailSubscriptions')}, #{user.get('emails')} - session unsubscribed: #{session.unsubscribed}" return unless session.levelName and session.team #log.info "Not sending email to #{user.get('email')} #{user.get('name')} because the session had levelName #{session.levelName} or team #{session.team} in it." return name = if user.get('firstName') and user.get('lastName') then "#{user.get('firstName')}" else user.get('name') name = 'Wizard' if not name or name is 'Anonymous' # Fetch the most recent defeat and victory, if there are any. # (We could look at strongest/weakest, but we'd have to fetch everyone, or denormalize more.) matches = _.filter session.matches, (match) -> match.date >= getTimeFromDaysAgo now, daysAgo defeats = _.filter matches, (match) -> match.metrics.rank is 1 and match.opponents[0].metrics.rank is 0 victories = _.filter matches, (match) -> match.metrics.rank is 0 and match.opponents[0].metrics.rank is 1 defeat = _.last defeats victory = _.last victories sendEmail = co.wrap (defeatContext, victoryContext, levelVersionsContext) -> message = templateId: sendgrid.templates.ladder_update_email to: email: if DEBUGGING then 'PI:EMAIL:<EMAIL>END_PI' else user.get('email') name: name from: email: config.mail.username name: 'CodeCombat' subject: "Your #{session.levelName} #{session.team[0].toUpperCase() + session.team.substr(1)} Scores" substitutions: username: name days_ago: daysAgo wins: victories.length losses: defeats.length total_score: Math.round(session.totalScore * 100) team: session.team team_name: session.team[0].toUpperCase() + session.team.substr(1) level_name: session.levelName session_id: session._id ladder_url: "http://codecombat.com/play/ladder/#{session.levelID}#my-matches" score_history_graph_url: getScoreHistoryGraphURL session, daysAgo defeat: defeatContext victory: victoryContext levelVersions: levelVersionsContext #log.info "Sending ladder update email to #{message.to.email} with #{message.substitutions.wins} wins and #{message.substitutions.losses} losses since #{daysAgo} day(s) ago." try yield sendgrid.api.send message catch err console.error "Error sending ladder update email:", err urlForMatch = (match) -> "http://codecombat.com/play/level/#{session.levelID}?team=#{session.team}&opponent=#{match.opponents[0].sessionID}" onFetchedDefeatedOpponent = (err, defeatedOpponent) -> if err log.error "Couldn't find defeateded opponent: #{err}" defeatedOpponent = null victoryContext = {opponent_name: defeatedOpponent?.name ? 'Anonymous', url: urlForMatch(victory)} if victory onFetchedVictoriousOpponent = (err, victoriousOpponent) -> if err log.error "Couldn't find victorious opponent: #{err}" victoriousOpponent = null defeatContext = {opponent_name: victoriousOpponent?.name ? 'Anonymous', url: urlForMatch(defeat)} if defeat Level.find({original: session.level.original, created: {$gt: session.submitDate}}).select('created commitMessage version').sort('-created').lean().exec (err, levelVersions) -> sendEmail defeatContext, victoryContext, (if levelVersions.length then levelVersions else null) if defeat User.findOne({_id: defeat.opponents[0].userID}).select('name').lean().exec onFetchedVictoriousOpponent else onFetchedVictoriousOpponent null, null if victory User.findOne({_id: victory.opponents[0].userID}).select('name').lean().exec onFetchedDefeatedOpponent else onFetchedDefeatedOpponent null, null getScoreHistoryGraphURL = (session, daysAgo) -> # Totally duplicated in My Matches tab for now until we figure out what we're doing. since = new Date() - 86400 * 1000 * daysAgo scoreHistory = (s for s in session.scoreHistory ? [] when s[0] >= since) return '' unless scoreHistory.length > 1 scoreHistory = _.last scoreHistory, 100 # Chart URL needs to be under 2048 characters for GET times = (s[0] for s in scoreHistory) times = ((100 * (t - times[0]) / (times[times.length - 1] - times[0])).toFixed(1) for t in times) scores = (s[1] for s in scoreHistory) lowest = _.min scores #.concat([0]) highest = _.max scores #.concat(50) scores = (Math.round(100 * (s - lowest) / (highest - lowest)) for s in scores) currentScore = Math.round scoreHistory[scoreHistory.length - 1][1] * 100 minScore = Math.round(100 * lowest) maxScore = Math.round(100 * highest) chartData = times.join(',') + '|' + scores.join(',') "https://chart.googleapis.com/chart?chs=600x75&cht=lxy&chtt=Score%3A+#{currentScore}&chts=222222,12,r&chf=a,s,000000FF&chls=2&chd=t:#{chartData}&chxt=y&chxr=0,#{minScore},#{maxScore}" ### End Ladder Update Email ### ### Next Steps Email ### handleNextSteps = (req, res) -> return unless DEBUGGING or isRequestFromDesignatedCronHandler req, res res.send('Great work, PI:NAME:<NAME>END_PI! I can take it from here.') res.end() emailDays = [1] now = new Date() for daysAgo in emailDays # Get every User that was created in a 5-minute window after the time. startTime = getTimeFromDaysAgo now, daysAgo endTime = startTime + 5 * 60 * 1000 findParameters = {dateCreated: {$gt: new Date(startTime), $lte: new Date(endTime)}, emailLower: {$exists: true}} selectString = 'name firstName lastName lastLevel points email gender emailSubscriptions emails dateCreated preferredLanguage aceConfig.language activity stats earned testGroupNumber ageRange courseInstances' query = User.find(findParameters).select(selectString) do (daysAgo) -> query.exec (err, results) -> if err log.error "Couldn't fetch next steps users for #{findParameters}\nError: #{err}" return errors.serverError res, "Next steps email query failed: #{JSON.stringify(err)}" log.info "Found #{results.length} next-steps users to email updates about for #{daysAgo} day(s) ago." if DEBUGGING sendNextStepsEmail result, now, daysAgo for result in results module.exports.sendNextStepsEmail = sendNextStepsEmail = (user, now, daysAgo) -> return log.info "Not sending next steps email to user with no email address" if not user.get('email') return log.debug "Not sending next steps email to teacher based on role" if user.isTeacher() unless user.isEmailSubscriptionEnabled('generalNews') and user.isEmailSubscriptionEnabled('anyNotes') log.info "Not sending email to #{user.get('email')} #{user.get('name')} because they only want emails about #{JSON.stringify(user.get('emails'))}" if DEBUGGING return LevelSession.find({creator: user.get('_id') + ''}).select('levelName levelID changed state.complete playtime').lean().exec (err, sessions) -> return log.error "Couldn't find sessions for #{user.get('email')} #{user.get('name')}: #{err}" if err complete = (s for s in sessions when s.state?.complete) incomplete = (s for s in sessions when not s.state?.complete) return if complete.length < 2 # TODO: find the next level to do somehow, for real if incomplete.length nextLevel = name: incomplete[0].levelName, slug: incomplete[0].levelID else nextLevel = null err = null do co.wrap (err, nextLevel) -> return log.error "Couldn't find next level for #{user.get('email')} #{user.get('name')}: #{err}" if err name = if user.get('firstName') and user.get('lastName') then "#{user.get('firstName')}" else user.get('name') name = 'PI:NAME:<NAME>END_PI' if not name or name in ['PI:NAME:<NAME>END_PI', 'Anonymous'] #secretLevel = switch user.get('testGroupNumber') % 8 # when 0, 1, 2, 3 then name: 'PI:NAME:<NAME>END_PI', slug: 'forgetful-gemsmith' # when 4, 5, 6, 7 then name: 'Signs and Portents', slug: 'signs-and-portents' secretLevel = name: 'Signs and Portents', slug: 'signs-and-portents' # We turned off this test for now and are sending everyone to forgetful-gemsmith # TODO: make this smarter, actually data-driven, looking at all available sessions shadowGuardSession = _.find sessions, levelID: 'shadow-guard' isFast = shadowGuardSession and shadowGuardSession.playtime < 90 # Average is 107s isVeryFast = shadowGuardSession and shadowGuardSession.playtime < 75 isAdult = user.get('ageRange') in ['18-24', '25-34', '35-44', '45-100'] isKid = not isAdult # Assume kid if not specified # Used to use these categories to customize the email; not doing it right now. TODO: customize it again in Sendgrid. # TODO: do something with the preferredLanguage? message = templateId: sendgrid.templates.next_steps_email to: email: if DEBUGGING then 'PI:EMAIL:<EMAIL>END_PI' else user.get('email') name: name from: email: config.mail.username name: 'CodeCombat' substitutions: username: name days_ago: daysAgo nextLevelName: nextLevel?.name nextLevelLink: if nextLevel then "http://codecombat.com/play/level/#{nextLevel.slug}" else null secretLevelName: secretLevel.name secretLevelLink: "http://codecombat.com/play/level/#{secretLevel.slug}" levelsComplete: complete.length isCoursePlayer: user.get('role') is 'student' # I hate Sendgrid variable interpolation; it works so inconsistently. Hack around it for now. message.substitutions.nextLevelTemplate = """ <p>Hail, #{message.substitutions.username}!</p> <p>You've done #{message.substitutions.levelsComplete} levels; now what?</p> <ul> #{if message.substitutions.nextLevelLink then '<li>Play the next level: <strong><a href="{{ message.substitutions.nextLevelLink }}">{{ message.substitutions.nextLevelName }}</a></strong></li' else ''} <li>Play this <em>secret</em> level: <strong><a href="#{message.substitutions.secretLevelLink}">#{message.substitutions.secretLevelName}</a></strong></li> <li><strong><a href="http://codecombat.com/#{if message.substitutions.isCoursePlayer then 'students">Choose a level</a></strong> to play next</li>' else 'play">Choose a level</a></strong> from one of the five worlds</li>'} </ul> """ log.info "Sending next steps email to #{message.to.email} with #{message.substitutions.nextLevelName} next and #{message.substitutions.levelsComplete} levels complete since #{daysAgo} day(s) ago." if DEBUGGING try yield sendgrid.api.send message catch err console.error "Error sending next steps email:", err ### End Next Steps Email ### handleMailChimpWebHook = wrap (req, res) -> post = req.body unless post.type in ['unsubscribe', 'profile', 'upemail'] res.send 'Bad post type' return res.end() email = post.data.email or post.data.old_email unless email res.send 'No email provided' return res.end() if post.data.web_id user = yield User.findOne { 'mailChimp.leid': post.data.web_id } if not user user = yield User.findOne { 'mailChimp.email': email } if not user throw new errors.NotFound('MailChimp subscriber not found') if not user.get('emailVerified') return res.send('User email unverified') if post.type is 'profile' handleProfileUpdate(user, post) else if post.type is 'upemail' handleUnsubscribe(user) # just unsubscribe from MailChimp else if post.type is 'unsubscribe' yield unsubscribe.unsubscribeEmailFromMarketingEmails(user.get('emailLower')) # unsubscribe all emails user.updatedMailChimp = true # so as not to echo back to mailchimp yield user.save() res.end('Success') module.exports.handleProfileUpdate = handleProfileUpdate = (user, post) -> mailChimpSubs = post.data.merges.INTERESTS.split(', ') for interest in mailChimp.interests user.setEmailSubscription interest.property, interest.mailChimpLabel in mailChimpSubs fname = post.data.merges.FNAME user.set('firstName', fname) if fname lname = post.data.merges.LNAME user.set('lastName', lname) if lname user.set 'mailChimp.email', post.data.email user.set 'mailChimp.euid', post.data.id module.exports.handleUnsubscribe = handleUnsubscribe = (user) -> user.set 'emailSubscriptions', [] for interest in mailChimp.interests user.setEmailSubscription interest.property, false user.set 'mailChimp', undefined
[ { "context": "->\n ops = options()\n ops.body =\n firstName: 'Test'\n lastName: 'User'\n email: uuid.v1() + 'sup", "end": 867, "score": 0.9995096921920776, "start": 863, "tag": "NAME", "value": "Test" }, { "context": " ops.body =\n firstName: 'Test'\n lastName: 'User'\n email: uuid.v1() + 'super-awesome-email@emai", "end": 888, "score": 0.9997401833534241, "start": 884, "tag": "NAME", "value": "User" }, { "context": "est'\n lastName: 'User'\n email: uuid.v1() + 'super-awesome-email@email.com'\n password: 'keyboard cats'\n request.post (ba", "end": 943, "score": 0.9993259906768799, "start": 914, "tag": "EMAIL", "value": "super-awesome-email@email.com" }, { "context": " + 'super-awesome-email@email.com'\n password: 'keyboard cats'\n request.post (base '/users'), ops, (e,r,b)->\n ", "end": 973, "score": 0.9992028474807739, "start": 960, "tag": "PASSWORD", "value": "keyboard cats" } ]
test/routes/user_test_helper.coffee
t3mpus/tempus-api
3
async = require 'async' should = require 'should' _ = require 'underscore' uuid = require 'uuid' request = require 'request' User = require "#{__dirname}/../../models/user" options = require "#{__dirname}/../options" base = require "#{__dirname}/../base" exports.addUsers = (done) -> done() exports.isEqual = (users) -> yes exports.users = [] exports.validate = (returnedUser) -> user = new User returnedUser props = _.clone user.public props.push 'id' hasProps = _.every props, (property)-> typeof returnedUser[property] isnt 'undefined' hasProps.should.be.true privateProps = _.difference user.required, user.public doesntHaveProps = _.every privateProps, (property) -> typeof returnedUser[property] is 'undefined' doesntHaveProps.should.be.true exports.makeUser = (callback) -> ops = options() ops.body = firstName: 'Test' lastName: 'User' email: uuid.v1() + 'super-awesome-email@email.com' password: 'keyboard cats' request.post (base '/users'), ops, (e,r,b)-> r.statusCode.should.be.equal 200 callback b
59925
async = require 'async' should = require 'should' _ = require 'underscore' uuid = require 'uuid' request = require 'request' User = require "#{__dirname}/../../models/user" options = require "#{__dirname}/../options" base = require "#{__dirname}/../base" exports.addUsers = (done) -> done() exports.isEqual = (users) -> yes exports.users = [] exports.validate = (returnedUser) -> user = new User returnedUser props = _.clone user.public props.push 'id' hasProps = _.every props, (property)-> typeof returnedUser[property] isnt 'undefined' hasProps.should.be.true privateProps = _.difference user.required, user.public doesntHaveProps = _.every privateProps, (property) -> typeof returnedUser[property] is 'undefined' doesntHaveProps.should.be.true exports.makeUser = (callback) -> ops = options() ops.body = firstName: '<NAME>' lastName: '<NAME>' email: uuid.v1() + '<EMAIL>' password: '<PASSWORD>' request.post (base '/users'), ops, (e,r,b)-> r.statusCode.should.be.equal 200 callback b
true
async = require 'async' should = require 'should' _ = require 'underscore' uuid = require 'uuid' request = require 'request' User = require "#{__dirname}/../../models/user" options = require "#{__dirname}/../options" base = require "#{__dirname}/../base" exports.addUsers = (done) -> done() exports.isEqual = (users) -> yes exports.users = [] exports.validate = (returnedUser) -> user = new User returnedUser props = _.clone user.public props.push 'id' hasProps = _.every props, (property)-> typeof returnedUser[property] isnt 'undefined' hasProps.should.be.true privateProps = _.difference user.required, user.public doesntHaveProps = _.every privateProps, (property) -> typeof returnedUser[property] is 'undefined' doesntHaveProps.should.be.true exports.makeUser = (callback) -> ops = options() ops.body = firstName: 'PI:NAME:<NAME>END_PI' lastName: 'PI:NAME:<NAME>END_PI' email: uuid.v1() + 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' request.post (base '/users'), ops, (e,r,b)-> r.statusCode.should.be.equal 200 callback b
[ { "context": "###\n# \n# countUp.js\n# by @inorganik\n# v 1.1.2\n#\n# Example:\n# numAnim = new countUp \"S", "end": 35, "score": 0.9996851682662964, "start": 25, "tag": "USERNAME", "value": "@inorganik" }, { "context": "wsers without native support\n # by Opera engineer Erik Möller\n while x < vendors.length and not window.request", "end": 1442, "score": 0.9997798800468445, "start": 1431, "tag": "NAME", "value": "Erik Möller" }, { "context": " clearTimeout id\n\n @version = () -> '1.1.2'\n\n # Robert Penner's easeOutExpo\n @easeOutExpo = (t, b, c, d) ->\n ", "end": 2207, "score": 0.9423252940177917, "start": 2194, "tag": "NAME", "value": "Robert Penner" } ]
public/assets/vendors/countUp/countUp.coffee
aaslannn/bakkal
1
### # # countUp.js # by @inorganik # v 1.1.2 # # Example: # numAnim = new countUp "SomeElementYouWantToAnimate", 99.99, 2, 1.5 # numAnim.start() # ### # target = id of Html element where counting occurs # @startVal = the value you want to start at # @endVal = the value you want to arrive at # decimals = number of decimal places, default 0 # duration = duration of animation in seconds, default 2 # options = optional object of options (see below) countUp = (target, startVal, endVal, decimals, duration, options) -> # default options @options = options || { useEasing: true # toggle easing useGrouping: true # 1,000,000 vs 1000000 separator: ',' # character to use as a separator decimal: '.' # character to use as a decimal } if @options.separator == '' then @options.useGrouping = false; lastTime = 0 vendors = [ 'webkit' 'moz' 'ms' ] @doc = if (typeof target == 'string') then document.getElementById target else target @startVal = Number @startVal @endVal = Number @endVal @countDown = if (@startVal > @endVal) then true else false @startTime = null @remaining = null @frameVal = @startVal @rAF = null @dec = Math.pow(10, decimals) @decimals = Math.max(0, decimals or 0) @duration = duration * 1000 or 2000 # make sure requestAnimationFrame and cancelAnimationFrame are defined # polyfill for browsers without native support # by Opera engineer Erik Möller while x < vendors.length and not window.requestAnimationFrame window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'] window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'] unless window.requestAnimationFrame window.requestAnimationFrame = (callback, element) -> currTime = new Date().getTime() timeToCall = Math.max 0, 16 - (currTime - lastTime) id = window.setTimeout(-> callback currTime + timeToCall , timeToCall) lastTime = currTime + timeToCall id unless window.cancelAnimationFrame window.cancelAnimationFrame = (id) -> clearTimeout id @version = () -> '1.1.2' # Robert Penner's easeOutExpo @easeOutExpo = (t, b, c, d) -> c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b @count = (timestamp) -> @startTime = timestamp if @startTime is null @timestamp = timestamp progress = timestamp - @startTime # to ease or not to ease is the question if @options.useEasing if @countDown i = @easeOutExpo progress, 0, @startVal - @endVal, @duration @frameVal = @startVal - i else @frameVal = @easeOutExpo(progress, @startVal, @endVal - @startVal, @duration) else if @countDown i = (@startVal - @endVal) * (progress / @duration) @frameVal = @startVal - i else @frameVal = @startVal + (@endVal - @startVal) * (progress / @duration) # decimal @frameVal = Math.round(@frameVal * @dec) / @dec # don't go past enVal since progress can exceed duration in last grame if @countDown @frameVal = if (@framVal < @endVal) then @endVal else @frameVal else @frameVal = if (@framVal > @endVal) then @endVal else @frameVal # formate and print value @doc.innerHTML = @formatNumber @frameVal.toFixed(decimals) # weather to continue if progress < @duration @rAF = requestAnimationFrame @count else @callback() if @callback? @start = (callback) -> @callback = callback # make sure @endVal is a number requestAnimationFrame @count unless isNaN(@endVal) and isNan(@startVal) isnt null else console.log('countUp error: @startVal or @endVal is not a number') @doc.innerHTML = '--' false @stop = () -> cancelAnimationFrame @rAF @reset = () -> @startTime = null @startVal = startVal cancelAnimationFrame @rAF @doc.innerHTML = @formatNumber @startVal.toFixed(decimals) @resume = () -> @startTime = null @duration = @remaining @startVal = @framVal requestAnimationFrame @count @formatNumber = (nStr) -> nStr += '' x = nStr.split('.') x1 = x[0] x2 = if x.length > 1 then @options.decimal + x[1] else '' rgx = /(\d+)(\d{3})/ if @options.useGrouping while rgx.test(x1) x1 = x1.replace(rgx, '$1' + @options.separator + '$2') x1 + x2 # format @startVal on initialization @doc.innerHTML = @formatNumber @startVal.toFixed(decimals)
211832
### # # countUp.js # by @inorganik # v 1.1.2 # # Example: # numAnim = new countUp "SomeElementYouWantToAnimate", 99.99, 2, 1.5 # numAnim.start() # ### # target = id of Html element where counting occurs # @startVal = the value you want to start at # @endVal = the value you want to arrive at # decimals = number of decimal places, default 0 # duration = duration of animation in seconds, default 2 # options = optional object of options (see below) countUp = (target, startVal, endVal, decimals, duration, options) -> # default options @options = options || { useEasing: true # toggle easing useGrouping: true # 1,000,000 vs 1000000 separator: ',' # character to use as a separator decimal: '.' # character to use as a decimal } if @options.separator == '' then @options.useGrouping = false; lastTime = 0 vendors = [ 'webkit' 'moz' 'ms' ] @doc = if (typeof target == 'string') then document.getElementById target else target @startVal = Number @startVal @endVal = Number @endVal @countDown = if (@startVal > @endVal) then true else false @startTime = null @remaining = null @frameVal = @startVal @rAF = null @dec = Math.pow(10, decimals) @decimals = Math.max(0, decimals or 0) @duration = duration * 1000 or 2000 # make sure requestAnimationFrame and cancelAnimationFrame are defined # polyfill for browsers without native support # by Opera engineer <NAME> while x < vendors.length and not window.requestAnimationFrame window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'] window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'] unless window.requestAnimationFrame window.requestAnimationFrame = (callback, element) -> currTime = new Date().getTime() timeToCall = Math.max 0, 16 - (currTime - lastTime) id = window.setTimeout(-> callback currTime + timeToCall , timeToCall) lastTime = currTime + timeToCall id unless window.cancelAnimationFrame window.cancelAnimationFrame = (id) -> clearTimeout id @version = () -> '1.1.2' # <NAME>'s easeOutExpo @easeOutExpo = (t, b, c, d) -> c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b @count = (timestamp) -> @startTime = timestamp if @startTime is null @timestamp = timestamp progress = timestamp - @startTime # to ease or not to ease is the question if @options.useEasing if @countDown i = @easeOutExpo progress, 0, @startVal - @endVal, @duration @frameVal = @startVal - i else @frameVal = @easeOutExpo(progress, @startVal, @endVal - @startVal, @duration) else if @countDown i = (@startVal - @endVal) * (progress / @duration) @frameVal = @startVal - i else @frameVal = @startVal + (@endVal - @startVal) * (progress / @duration) # decimal @frameVal = Math.round(@frameVal * @dec) / @dec # don't go past enVal since progress can exceed duration in last grame if @countDown @frameVal = if (@framVal < @endVal) then @endVal else @frameVal else @frameVal = if (@framVal > @endVal) then @endVal else @frameVal # formate and print value @doc.innerHTML = @formatNumber @frameVal.toFixed(decimals) # weather to continue if progress < @duration @rAF = requestAnimationFrame @count else @callback() if @callback? @start = (callback) -> @callback = callback # make sure @endVal is a number requestAnimationFrame @count unless isNaN(@endVal) and isNan(@startVal) isnt null else console.log('countUp error: @startVal or @endVal is not a number') @doc.innerHTML = '--' false @stop = () -> cancelAnimationFrame @rAF @reset = () -> @startTime = null @startVal = startVal cancelAnimationFrame @rAF @doc.innerHTML = @formatNumber @startVal.toFixed(decimals) @resume = () -> @startTime = null @duration = @remaining @startVal = @framVal requestAnimationFrame @count @formatNumber = (nStr) -> nStr += '' x = nStr.split('.') x1 = x[0] x2 = if x.length > 1 then @options.decimal + x[1] else '' rgx = /(\d+)(\d{3})/ if @options.useGrouping while rgx.test(x1) x1 = x1.replace(rgx, '$1' + @options.separator + '$2') x1 + x2 # format @startVal on initialization @doc.innerHTML = @formatNumber @startVal.toFixed(decimals)
true
### # # countUp.js # by @inorganik # v 1.1.2 # # Example: # numAnim = new countUp "SomeElementYouWantToAnimate", 99.99, 2, 1.5 # numAnim.start() # ### # target = id of Html element where counting occurs # @startVal = the value you want to start at # @endVal = the value you want to arrive at # decimals = number of decimal places, default 0 # duration = duration of animation in seconds, default 2 # options = optional object of options (see below) countUp = (target, startVal, endVal, decimals, duration, options) -> # default options @options = options || { useEasing: true # toggle easing useGrouping: true # 1,000,000 vs 1000000 separator: ',' # character to use as a separator decimal: '.' # character to use as a decimal } if @options.separator == '' then @options.useGrouping = false; lastTime = 0 vendors = [ 'webkit' 'moz' 'ms' ] @doc = if (typeof target == 'string') then document.getElementById target else target @startVal = Number @startVal @endVal = Number @endVal @countDown = if (@startVal > @endVal) then true else false @startTime = null @remaining = null @frameVal = @startVal @rAF = null @dec = Math.pow(10, decimals) @decimals = Math.max(0, decimals or 0) @duration = duration * 1000 or 2000 # make sure requestAnimationFrame and cancelAnimationFrame are defined # polyfill for browsers without native support # by Opera engineer PI:NAME:<NAME>END_PI while x < vendors.length and not window.requestAnimationFrame window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'] window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'] unless window.requestAnimationFrame window.requestAnimationFrame = (callback, element) -> currTime = new Date().getTime() timeToCall = Math.max 0, 16 - (currTime - lastTime) id = window.setTimeout(-> callback currTime + timeToCall , timeToCall) lastTime = currTime + timeToCall id unless window.cancelAnimationFrame window.cancelAnimationFrame = (id) -> clearTimeout id @version = () -> '1.1.2' # PI:NAME:<NAME>END_PI's easeOutExpo @easeOutExpo = (t, b, c, d) -> c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b @count = (timestamp) -> @startTime = timestamp if @startTime is null @timestamp = timestamp progress = timestamp - @startTime # to ease or not to ease is the question if @options.useEasing if @countDown i = @easeOutExpo progress, 0, @startVal - @endVal, @duration @frameVal = @startVal - i else @frameVal = @easeOutExpo(progress, @startVal, @endVal - @startVal, @duration) else if @countDown i = (@startVal - @endVal) * (progress / @duration) @frameVal = @startVal - i else @frameVal = @startVal + (@endVal - @startVal) * (progress / @duration) # decimal @frameVal = Math.round(@frameVal * @dec) / @dec # don't go past enVal since progress can exceed duration in last grame if @countDown @frameVal = if (@framVal < @endVal) then @endVal else @frameVal else @frameVal = if (@framVal > @endVal) then @endVal else @frameVal # formate and print value @doc.innerHTML = @formatNumber @frameVal.toFixed(decimals) # weather to continue if progress < @duration @rAF = requestAnimationFrame @count else @callback() if @callback? @start = (callback) -> @callback = callback # make sure @endVal is a number requestAnimationFrame @count unless isNaN(@endVal) and isNan(@startVal) isnt null else console.log('countUp error: @startVal or @endVal is not a number') @doc.innerHTML = '--' false @stop = () -> cancelAnimationFrame @rAF @reset = () -> @startTime = null @startVal = startVal cancelAnimationFrame @rAF @doc.innerHTML = @formatNumber @startVal.toFixed(decimals) @resume = () -> @startTime = null @duration = @remaining @startVal = @framVal requestAnimationFrame @count @formatNumber = (nStr) -> nStr += '' x = nStr.split('.') x1 = x[0] x2 = if x.length > 1 then @options.decimal + x[1] else '' rgx = /(\d+)(\d{3})/ if @options.useGrouping while rgx.test(x1) x1 = x1.replace(rgx, '$1' + @options.separator + '$2') x1 + x2 # format @startVal on initialization @doc.innerHTML = @formatNumber @startVal.toFixed(decimals)
[ { "context": "###*\n* Represent a standard graphic\n*\n* @author David Jegat <david.jegat@gmail.com>\n###\nclass BaseGraphic ext", "end": 59, "score": 0.9998903274536133, "start": 48, "tag": "NAME", "value": "David Jegat" }, { "context": "esent a standard graphic\n*\n* @author David Jegat <david.jegat@gmail.com>\n###\nclass BaseGraphic extends BaseCollector\n ##", "end": 82, "score": 0.9999315738677979, "start": 61, "tag": "EMAIL", "value": "david.jegat@gmail.com" } ]
src/Graphic/BaseGraphic.coffee
Djeg/MicroRacing
1
###* * Represent a standard graphic * * @author David Jegat <david.jegat@gmail.com> ### class BaseGraphic extends BaseCollector ###* * @consructor * @param {string} name ### constructor: () -> @name = @constructor.name.replace('Graphic', '') @game = null ###* * Set up the game * * @param {Game} game * @throws String, is game is not a Game ### setUp: (game) -> if not game instanceof Game throw "Invalid game" @game = game ###* * Test is the graphic is loaded * * @return {boolean} ### isLoad: () -> true ###* * Initialize graphics ### init: () -> ###* * Draw the graphic * * @throws String ### draw: () -> throw "Please implement this method"
4246
###* * Represent a standard graphic * * @author <NAME> <<EMAIL>> ### class BaseGraphic extends BaseCollector ###* * @consructor * @param {string} name ### constructor: () -> @name = @constructor.name.replace('Graphic', '') @game = null ###* * Set up the game * * @param {Game} game * @throws String, is game is not a Game ### setUp: (game) -> if not game instanceof Game throw "Invalid game" @game = game ###* * Test is the graphic is loaded * * @return {boolean} ### isLoad: () -> true ###* * Initialize graphics ### init: () -> ###* * Draw the graphic * * @throws String ### draw: () -> throw "Please implement this method"
true
###* * Represent a standard graphic * * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### class BaseGraphic extends BaseCollector ###* * @consructor * @param {string} name ### constructor: () -> @name = @constructor.name.replace('Graphic', '') @game = null ###* * Set up the game * * @param {Game} game * @throws String, is game is not a Game ### setUp: (game) -> if not game instanceof Game throw "Invalid game" @game = game ###* * Test is the graphic is loaded * * @return {boolean} ### isLoad: () -> true ###* * Initialize graphics ### init: () -> ###* * Draw the graphic * * @throws String ### draw: () -> throw "Please implement this method"
[ { "context": "\"\nform.add \"email\", \"email\"\nform.add \"password\", \"password\"\nform.add \"password_confirmation\", \"password\"\n\nCo", "end": 131, "score": 0.9983741641044617, "start": 123, "tag": "PASSWORD", "value": "password" }, { "context": "d\", \"password\"\nform.add \"password_confirmation\", \"password\"\n\nComponent.create \"Public.Users.Edit\",\n compone", "end": 176, "score": 0.9977255463600159, "start": 168, "tag": "PASSWORD", "value": "password" } ]
src/react/components/public/users/edit.coffee
tomprats/tomify-js
0
form = new Form form.add "first_name", "text" form.add "last_name", "text" form.add "email", "email" form.add "password", "password" form.add "password_confirmation", "password" Component.create "Public.Users.Edit", componentWillInitialize: -> @model = Model.find "Public.User" @store = Store.findOrCreate "Public.Users.Edit" @form = form.setComponent @ @follow @model.on "update", @modelUpdate @follow Store.find("User").on "change", @userChange @userChange() userChange: -> @form.record.set Store.find("User").get() @form.setDefaultValues() modelUpdate: (response) -> message type: response.type, text: response.message Store.find("User").merge response.data if response.type == "success" submit: (e) -> e.preventDefault() if @form.changes.empty() message type: "warning", text: "Profile was not updated" else @model.update @form.changes.get() false show: (e) -> e.preventDefault() Model.findOrCreate("Public.User").show() destroy: (e) -> e.preventDefault() Model.find("Public.User").destroy().then (response) -> return redirect response.redirect if response.message == "Profile Deleted" message type: response.type, text: response.message false render: -> <div> <h3>Edit Profile</h3> <form onSubmit={@submit}> {@form.render()} <div className="form-group"> <div className="btn-group"> <input type="submit" name="commit" value="Save" className="btn btn-primary" /> <a href="#" onClick={@show} className="btn btn-default">Back</a> </div> </div> <div className="form-group"> <small> <a href="#{path 'subscription'}?email=#{@form.record.get 'email'}">Email Subscription</a> <span> | </span> <a href="#" onClick={@destroy} data-confirm="Are you sure you want to permanently delete your account?">Delete Account</a> </small> </div> </form> </div>
170097
form = new Form form.add "first_name", "text" form.add "last_name", "text" form.add "email", "email" form.add "password", "<PASSWORD>" form.add "password_confirmation", "<PASSWORD>" Component.create "Public.Users.Edit", componentWillInitialize: -> @model = Model.find "Public.User" @store = Store.findOrCreate "Public.Users.Edit" @form = form.setComponent @ @follow @model.on "update", @modelUpdate @follow Store.find("User").on "change", @userChange @userChange() userChange: -> @form.record.set Store.find("User").get() @form.setDefaultValues() modelUpdate: (response) -> message type: response.type, text: response.message Store.find("User").merge response.data if response.type == "success" submit: (e) -> e.preventDefault() if @form.changes.empty() message type: "warning", text: "Profile was not updated" else @model.update @form.changes.get() false show: (e) -> e.preventDefault() Model.findOrCreate("Public.User").show() destroy: (e) -> e.preventDefault() Model.find("Public.User").destroy().then (response) -> return redirect response.redirect if response.message == "Profile Deleted" message type: response.type, text: response.message false render: -> <div> <h3>Edit Profile</h3> <form onSubmit={@submit}> {@form.render()} <div className="form-group"> <div className="btn-group"> <input type="submit" name="commit" value="Save" className="btn btn-primary" /> <a href="#" onClick={@show} className="btn btn-default">Back</a> </div> </div> <div className="form-group"> <small> <a href="#{path 'subscription'}?email=#{@form.record.get 'email'}">Email Subscription</a> <span> | </span> <a href="#" onClick={@destroy} data-confirm="Are you sure you want to permanently delete your account?">Delete Account</a> </small> </div> </form> </div>
true
form = new Form form.add "first_name", "text" form.add "last_name", "text" form.add "email", "email" form.add "password", "PI:PASSWORD:<PASSWORD>END_PI" form.add "password_confirmation", "PI:PASSWORD:<PASSWORD>END_PI" Component.create "Public.Users.Edit", componentWillInitialize: -> @model = Model.find "Public.User" @store = Store.findOrCreate "Public.Users.Edit" @form = form.setComponent @ @follow @model.on "update", @modelUpdate @follow Store.find("User").on "change", @userChange @userChange() userChange: -> @form.record.set Store.find("User").get() @form.setDefaultValues() modelUpdate: (response) -> message type: response.type, text: response.message Store.find("User").merge response.data if response.type == "success" submit: (e) -> e.preventDefault() if @form.changes.empty() message type: "warning", text: "Profile was not updated" else @model.update @form.changes.get() false show: (e) -> e.preventDefault() Model.findOrCreate("Public.User").show() destroy: (e) -> e.preventDefault() Model.find("Public.User").destroy().then (response) -> return redirect response.redirect if response.message == "Profile Deleted" message type: response.type, text: response.message false render: -> <div> <h3>Edit Profile</h3> <form onSubmit={@submit}> {@form.render()} <div className="form-group"> <div className="btn-group"> <input type="submit" name="commit" value="Save" className="btn btn-primary" /> <a href="#" onClick={@show} className="btn btn-default">Back</a> </div> </div> <div className="form-group"> <small> <a href="#{path 'subscription'}?email=#{@form.record.get 'email'}">Email Subscription</a> <span> | </span> <a href="#" onClick={@destroy} data-confirm="Are you sure you want to permanently delete your account?">Delete Account</a> </small> </div> </form> </div>
[ { "context": "s_rate: 0\r\n avg_ack_egress_rate: 0\r\n name: '/api.eyJJRCI6IjBmYmM2OGEwNjE2YjdmOTFjMzliIiwiQ3JlYXRlT24iOjE0NjIzNTk3MjQyNjUsIkhvc3ROYW1lIjoiYWxpLXBjIn0'\r\n vhost: '/'\r\n durable: true\r\n auto_del", "end": 2180, "score": 0.9996877908706665, "start": 2075, "tag": "KEY", "value": "'/api.eyJJRCI6IjBmYmM2OGEwNjE2YjdmOTFjMzliIiwiQ3JlYXRlT24iOjE0NjIzNTk3MjQyNjUsIkhvc3ROYW1lIjoiYWxpLXBjIn0" }, { "context": "s_rate: 0\r\n avg_ack_egress_rate: 0\r\n name: '/zbadmin.eyJJRCI6IjQ4N2Q0NDU5ZDNmODAyOWUwYjA2IiwiQ3JlYXRlT24iOjE0NjIzNTk3MTg2OTYsIkhvc3ROYW1lIjoiYWxpLXBjIn0'\r\n vhost: '/'\r\n durable: true\r\n auto_del", "end": 4728, "score": 0.9994143843650818, "start": 4619, "tag": "KEY", "value": "'/zbadmin.eyJJRCI6IjQ4N2Q0NDU5ZDNmODAyOWUwYjA2IiwiQ3JlYXRlT24iOjE0NjIzNTk3MTg2OTYsIkhvc3ROYW1lIjoiYWxpLXBjIn0" }, { "context": "s_rate: 0\r\n avg_ack_egress_rate: 0\r\n name: '/zbadmin.eyJJRCI6ImFlNDA2OTQ5MWVkNDgxOTI3ZTUzIiwiQ3JlYXRlT24iOjE0NjIzNTk2MzA4OTQsIkhvc3ROYW1lIjoiYWxpLXBjIn0'\r\n vhost: '/'\r\n durable: true\r\n auto_del", "end": 5900, "score": 0.9943926334381104, "start": 5791, "tag": "KEY", "value": "'/zbadmin.eyJJRCI6ImFlNDA2OTQ5MWVkNDgxOTI3ZTUzIiwiQ3JlYXRlT24iOjE0NjIzNTk2MzA4OTQsIkhvc3ROYW1lIjoiYWxpLXBjIn0" }, { "context": "rate: 0\r\n avg_ack_egress_rate: 0\r\n name: 'serviceTesta797f744.eyJJRCI6IjM3MmZiODcyYzA2ODZmZWJhZWE5IiwiQ3JlYXRlT24iOjE0NjIzNTk3MTg2OTYsIkhvc3ROYW1lIjoiYWxpLXBjIn0'\r\n vhost: '/'\r\n durable: true\r\n auto_del", "end": 9766, "score": 0.9917716383934021, "start": 9647, "tag": "KEY", "value": "serviceTesta797f744.eyJJRCI6IjM3MmZiODcyYzA2ODZmZWJhZWE5IiwiQ3JlYXRlT24iOjE0NjIzNTk3MTg2OTYsIkhvc3ROYW1lIjoiYWxpLXBjIn0" }, { "context": "rate: 0\r\n avg_ack_egress_rate: 0\r\n name: 'serviceTestf936c1bf.eyJJRCI6IjQ2OWU2ZWUyNWZmMzRiNThmNTE5IiwiQ3JlYXRlT24iOjE0NjIzNTk2MzA4OTQsIkhvc3ROYW1lIjoiYWxpLXBjIn0'\r\n vhost: '/'\r\n durable: true\r\n auto_del", "end": 12264, "score": 0.9986858367919922, "start": 12145, "tag": "KEY", "value": "serviceTestf936c1bf.eyJJRCI6IjQ2OWU2ZWUyNWZmMzRiNThmNTE5IiwiQ3JlYXRlT24iOjE0NjIzNTk2MzA4OTQsIkhvc3ROYW1lIjoiYWxpLXBjIn0" } ]
test/helper.coffee
HoS0/hosqueues
0
Promise = require('bluebird') getQueueResponse = [ { memory: 14200 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:02:05' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 2 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: '/api' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 14200 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:02:05' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 2 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: '/api.eyJJRCI6IjBmYmM2OGEwNjE2YjdmOTFjMzliIiwiQ3JlYXRlT24iOjE0NjIzNTk3MjQyNjUsIkhvc3ROYW1lIjoiYWxpLXBjIn0' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 15144 message_stats: ack: 4 ack_details: [ Object ] deliver: 4 deliver_details: [ Object ] deliver_get: 4 deliver_get_details: [ Object ] publish: 4 publish_details: [ Object ] messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:02:00' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 5 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 4 avg_ingress_rate: 0.23966192782053877 avg_egress_rate: 0.23966192782053877 avg_ack_ingress_rate: 0.23966192782053877 avg_ack_egress_rate: 0.23966192782053877 name: '/zbadmin' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 14488 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:01:59' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 4 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: '/zbadmin.eyJJRCI6IjQ4N2Q0NDU5ZDNmODAyOWUwYjA2IiwiQ3JlYXRlT24iOjE0NjIzNTk3MTg2OTYsIkhvc3ROYW1lIjoiYWxpLXBjIn0' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 21960 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:00:32' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 1 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: '/zbadmin.eyJJRCI6ImFlNDA2OTQ5MWVkNDgxOTI3ZTUzIiwiQ3JlYXRlT24iOjE0NjIzNTk2MzA4OTQsIkhvc3ROYW1lIjoiYWxpLXBjIn0' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 15432 message_stats: ack: 8 ack_details: [ Object ] deliver: 8 deliver_details: [ Object ] deliver_get: 8 deliver_get_details: [ Object ] publish: 8 publish_details: [ Object ] messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:02:01' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 4 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 8 avg_ingress_rate: 0.4788191048907202 avg_egress_rate: 0.4788191048907202 avg_ack_ingress_rate: 0.4788191048907202 avg_ack_egress_rate: 0.4788191048907202 name: 'auth' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 14056 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:01:59' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 1 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: 'serviceTesta797f744' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 14416 message_stats: ack: 2 ack_details: [ Object ] deliver: 2 deliver_details: [ Object ] deliver_get: 2 deliver_get_details: [ Object ] publish: 2 publish_details: [ Object ] messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:02:00' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 1 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 2 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: 'serviceTesta797f744.eyJJRCI6IjM3MmZiODcyYzA2ODZmZWJhZWE5IiwiQ3JlYXRlT24iOjE0NjIzNTk3MTg2OTYsIkhvc3ROYW1lIjoiYWxpLXBjIn0' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 21960 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:00:32' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 1 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: 'serviceTestf936c1bf' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 22176 message_stats: ack: 2 ack_details: [ Object ] deliver: 2 deliver_details: [ Object ] deliver_get: 2 deliver_get_details: [ Object ] publish: 2 publish_details: [ Object ] messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:00:33' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 1 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 2 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: 'serviceTestf936c1bf.eyJJRCI6IjQ2OWU2ZWUyNWZmMzRiNThmNTE5IiwiQ3JlYXRlT24iOjE0NjIzNTk2MzA4OTQsIkhvc3ROYW1lIjoiYWxpLXBjIn0' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } ] module.exports = rp: (options)-> return new Promise (fullfil, reject)=> if options.uri.endsWith '/api/queues' fullfil(getQueueResponse) else reject('unknown address for mocking')
53639
Promise = require('bluebird') getQueueResponse = [ { memory: 14200 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:02:05' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 2 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: '/api' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 14200 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:02:05' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 2 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: <KEY>' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 15144 message_stats: ack: 4 ack_details: [ Object ] deliver: 4 deliver_details: [ Object ] deliver_get: 4 deliver_get_details: [ Object ] publish: 4 publish_details: [ Object ] messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:02:00' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 5 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 4 avg_ingress_rate: 0.23966192782053877 avg_egress_rate: 0.23966192782053877 avg_ack_ingress_rate: 0.23966192782053877 avg_ack_egress_rate: 0.23966192782053877 name: '/zbadmin' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 14488 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:01:59' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 4 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: <KEY>' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 21960 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:00:32' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 1 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: <KEY>' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 15432 message_stats: ack: 8 ack_details: [ Object ] deliver: 8 deliver_details: [ Object ] deliver_get: 8 deliver_get_details: [ Object ] publish: 8 publish_details: [ Object ] messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:02:01' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 4 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 8 avg_ingress_rate: 0.4788191048907202 avg_egress_rate: 0.4788191048907202 avg_ack_ingress_rate: 0.4788191048907202 avg_ack_egress_rate: 0.4788191048907202 name: 'auth' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 14056 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:01:59' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 1 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: 'serviceTesta797f744' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 14416 message_stats: ack: 2 ack_details: [ Object ] deliver: 2 deliver_details: [ Object ] deliver_get: 2 deliver_get_details: [ Object ] publish: 2 publish_details: [ Object ] messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:02:00' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 1 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 2 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: '<KEY>' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 21960 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:00:32' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 1 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: 'serviceTestf936c1bf' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 22176 message_stats: ack: 2 ack_details: [ Object ] deliver: 2 deliver_details: [ Object ] deliver_get: 2 deliver_get_details: [ Object ] publish: 2 publish_details: [ Object ] messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:00:33' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 1 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 2 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: '<KEY>' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } ] module.exports = rp: (options)-> return new Promise (fullfil, reject)=> if options.uri.endsWith '/api/queues' fullfil(getQueueResponse) else reject('unknown address for mocking')
true
Promise = require('bluebird') getQueueResponse = [ { memory: 14200 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:02:05' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 2 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: '/api' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 14200 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:02:05' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 2 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: PI:KEY:<KEY>END_PI' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 15144 message_stats: ack: 4 ack_details: [ Object ] deliver: 4 deliver_details: [ Object ] deliver_get: 4 deliver_get_details: [ Object ] publish: 4 publish_details: [ Object ] messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:02:00' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 5 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 4 avg_ingress_rate: 0.23966192782053877 avg_egress_rate: 0.23966192782053877 avg_ack_ingress_rate: 0.23966192782053877 avg_ack_egress_rate: 0.23966192782053877 name: '/zbadmin' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 14488 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:01:59' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 4 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: PI:KEY:<KEY>END_PI' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 21960 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:00:32' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 1 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: PI:KEY:<KEY>END_PI' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 15432 message_stats: ack: 8 ack_details: [ Object ] deliver: 8 deliver_details: [ Object ] deliver_get: 8 deliver_get_details: [ Object ] publish: 8 publish_details: [ Object ] messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:02:01' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 4 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 8 avg_ingress_rate: 0.4788191048907202 avg_egress_rate: 0.4788191048907202 avg_ack_ingress_rate: 0.4788191048907202 avg_ack_egress_rate: 0.4788191048907202 name: 'auth' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 14056 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:01:59' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 1 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: 'serviceTesta797f744' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 14416 message_stats: ack: 2 ack_details: [ Object ] deliver: 2 deliver_details: [ Object ] deliver_get: 2 deliver_get_details: [ Object ] publish: 2 publish_details: [ Object ] messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:02:00' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 1 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 2 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: 'PI:KEY:<KEY>END_PI' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 21960 messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:00:32' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 1 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 0 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: 'serviceTestf936c1bf' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } { memory: 22176 message_stats: ack: 2 ack_details: [ Object ] deliver: 2 deliver_details: [ Object ] deliver_get: 2 deliver_get_details: [ Object ] publish: 2 publish_details: [ Object ] messages: 0 messages_details: rate: 0 messages_ready: 0 messages_ready_details: rate: 0 messages_unacknowledged: 0 messages_unacknowledged_details: rate: 0 idle_since: '2016-05-04 13:00:33' consumer_utilisation: '' policy: '' exclusive_consumer_tag: '' consumers: 1 down_slave_nodes: '' state: 'running' messages_ram: 0 messages_ready_ram: 0 messages_unacknowledged_ram: 0 messages_persistent: 0 message_bytes: 0 message_bytes_ready: 0 message_bytes_unacknowledged: 0 message_bytes_ram: 0 message_bytes_persistent: 0 backing_queue_status: q1: 0 q2: 0 delta: [ Object ] q3: 0 q4: 0 len: 0 target_ram_count: 'infinity' next_seq_id: 2 avg_ingress_rate: 0 avg_egress_rate: 0 avg_ack_ingress_rate: 0 avg_ack_egress_rate: 0 name: 'PI:KEY:<KEY>END_PI' vhost: '/' durable: true auto_delete: true arguments: {} node: 'rabbit@ALI-PC' } ] module.exports = rp: (options)-> return new Promise (fullfil, reject)=> if options.uri.endsWith '/api/queues' fullfil(getQueueResponse) else reject('unknown address for mocking')
[ { "context": "io.com\n\nCopyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>\n\nLicensed under the Apache License, Version 2.0 ", "end": 194, "score": 0.9999210238456726, "start": 178, "tag": "EMAIL", "value": "info@chaibio.com" } ]
frontend/javascripts/app/directives/ampli-slider.coffee
MakerButt/chaipcr
1
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <info@chaibio.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### window.App.directive('ampliSlider', [ '$window' 'TextSelection' '$timeout' ($window, TextSelection, $timeout) -> restrict: 'AE' replace: true require: 'ngModel' template: '<div class="ampli-slider"></div>' link: ($scope, elem, attrs, ngModel) -> elem.css(cursor: 'pointer') width = elem.width() height = 20 elem.parent().height(height) barHeight = 5 circleR = 7 circleStroke = 4 circleShadowR = circleR + (circleStroke/2) + 0.5 held = false offsetClicked = false bgClicked = false oldPageX = 0 oldOffsetWidth = 0 oldHolderCX = 0 oldHolderShadowCX = 0 minOffsetWidth = circleR - circleStroke/2 maxOffsetWidth = width - circleR * 2 minCircleCX = circleShadowR maxCircleCX = width - (circleR + circleStroke/2) - 1 initDynamicVars = -> width = elem.width() maxOffsetWidth = width - circleR * 2 maxCircleCX = width - (circleR + circleStroke/2) - 1 init = -> initDynamicVars() svg = d3.select(elem[0]) .append('svg') .attr('width', width) .attr('height', height) .attr('alignment-baseline', 'middle') sliderBg = svg.append('rect') .attr('fill', '#ccc') .attr('width', width) .attr('height', barHeight) .attr('y', (height)/2 - 2) .attr('rx', 2) .attr('ry', 2) .on 'mousedown', -> bgClicked = true oldHolderCX = handle.attr('cx') * 1 oldHolderShadowCX = handleShadow.attr('cx') * 1 oldOffsetWidth = sliderOffset.attr('width') * 1 .on 'mouseup', -> if bgClicked x = d3.mouse(this)[0] - circleR/2 toadd = x - oldOffsetWidth console.log "toadd: #{toadd}" moveBy(toadd) bgClicked = false sliderOffset = svg.append('rect') .attr('fill', 'gray') .attr('width', circleR - circleStroke/2) .attr('height', barHeight) .attr('y', (height)/2 - 2) .attr('rx', 2) .attr('ry', 2) .on 'mousedown', -> offsetClicked = true oldHolderCX = handle.attr('cx') * 1 oldHolderShadowCX = handleShadow.attr('cx') * 1 oldOffsetWidth = sliderOffset.attr('width') * 1 .on 'mouseup', -> if offsetClicked x = d3.mouse(this)[0] - circleR/2 toadd = x - oldOffsetWidth console.log "toadd: #{toadd}" moveBy(toadd) offsetClicked = false handleShadow = svg.append('circle') .attr('fill', '#aaa') .attr('r', circleShadowR ) .attr('cy', height/2) .attr('cx', circleShadowR) handle = svg.append('circle') .attr('fill', '#8FC742') .attr('stroke', '#fff') .attr('stroke-width', circleStroke) .attr('r', circleR) .attr('cy', height/2) .attr('cx', circleShadowR) angular.element(handle.node()).on 'mousedown', (e) -> held = true oldPageX = e.pageX oldHolderCX = handle.attr('cx') * 1 oldHolderShadowCX = handleShadow.attr('cx') * 1 oldOffsetWidth = sliderOffset.attr('width') * 1 TextSelection.disable() updateModel = (val) -> ngModel.$setViewValue(val) if val isnt ngModel.$viewValue moveBy = (px) -> newHolderCX = oldHolderCX + px newHolderShadowCX = oldHolderShadowCX + px newOffsetWidth = oldOffsetWidth + px if (newOffsetWidth > maxOffsetWidth) newOffsetWidth = maxOffsetWidth newHolderShadowCX = maxCircleCX newHolderCX = maxCircleCX if (newOffsetWidth < minOffsetWidth) newOffsetWidth = minOffsetWidth newHolderShadowCX = minCircleCX newHolderCX = minCircleCX sliderOffset.attr('width', newOffsetWidth) handleShadow.attr('cx', newHolderShadowCX) handle.attr('cx', newHolderCX) x = ((oldOffsetWidth + px) - minOffsetWidth)/(maxOffsetWidth - minOffsetWidth) if x < 0 updateModel(x) else y = -Math.sqrt(1-Math.pow(x, 2)) + 1 updateModel(y) updateViewByValue = (val) -> return if !angular.isNumber(val) or $window.isNaN(val) or held width_percent = Math.sqrt(-Math.pow(-val+1, 2)+1) newOffsetWidth = width_percent * (maxOffsetWidth - minOffsetWidth) newOffsetWidth = newOffsetWidth + minOffsetWidth # console.log "newOffsetWidth: #{newOffsetWidth}" newHolderCX = newOffsetWidth + (circleR/2) if (newOffsetWidth > maxOffsetWidth) newOffsetWidth = maxOffsetWidth if (newHolderCX > maxCircleCX) newHolderCX = maxCircleCX if (newOffsetWidth < minOffsetWidth) newOffsetWidth = minOffsetWidth if (newHolderCX < minCircleCX) newHolderCX = minCircleCX sliderOffset.attr('width', newOffsetWidth) handleShadow.attr('cx', newHolderCX) handle.attr('cx', newHolderCX) $scope.$watch -> ngModel.$viewValue , (val) -> updateViewByValue(val) $scope.$on 'window:mousemove', (event, e) -> if held toadd = e.pageX - oldPageX moveBy(toadd) $scope.$on 'window:mouseup', (event, e) -> TextSelection.enable() if held held = false oldPageX = e.pageX resizeTimeout = null $scope.$on 'window:resize', -> svg.attr('width', elem.parent().width()) sliderBg.attr('width', elem.parent().width()) elem.parent().css(overflow: 'hidden') if (resizeTimeout) $timeout.cancel resizeTimeout resizeTimeout = null resizeTimeout = $timeout -> initDynamicVars() elem.parent().css(overflow: '') svg.attr('width', width) sliderBg.attr('width', width) updateViewByValue(ngModel.$viewValue) resizeTimeout = null , 100 $timeout -> init() , 2000 ]);
6737
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### window.App.directive('ampliSlider', [ '$window' 'TextSelection' '$timeout' ($window, TextSelection, $timeout) -> restrict: 'AE' replace: true require: 'ngModel' template: '<div class="ampli-slider"></div>' link: ($scope, elem, attrs, ngModel) -> elem.css(cursor: 'pointer') width = elem.width() height = 20 elem.parent().height(height) barHeight = 5 circleR = 7 circleStroke = 4 circleShadowR = circleR + (circleStroke/2) + 0.5 held = false offsetClicked = false bgClicked = false oldPageX = 0 oldOffsetWidth = 0 oldHolderCX = 0 oldHolderShadowCX = 0 minOffsetWidth = circleR - circleStroke/2 maxOffsetWidth = width - circleR * 2 minCircleCX = circleShadowR maxCircleCX = width - (circleR + circleStroke/2) - 1 initDynamicVars = -> width = elem.width() maxOffsetWidth = width - circleR * 2 maxCircleCX = width - (circleR + circleStroke/2) - 1 init = -> initDynamicVars() svg = d3.select(elem[0]) .append('svg') .attr('width', width) .attr('height', height) .attr('alignment-baseline', 'middle') sliderBg = svg.append('rect') .attr('fill', '#ccc') .attr('width', width) .attr('height', barHeight) .attr('y', (height)/2 - 2) .attr('rx', 2) .attr('ry', 2) .on 'mousedown', -> bgClicked = true oldHolderCX = handle.attr('cx') * 1 oldHolderShadowCX = handleShadow.attr('cx') * 1 oldOffsetWidth = sliderOffset.attr('width') * 1 .on 'mouseup', -> if bgClicked x = d3.mouse(this)[0] - circleR/2 toadd = x - oldOffsetWidth console.log "toadd: #{toadd}" moveBy(toadd) bgClicked = false sliderOffset = svg.append('rect') .attr('fill', 'gray') .attr('width', circleR - circleStroke/2) .attr('height', barHeight) .attr('y', (height)/2 - 2) .attr('rx', 2) .attr('ry', 2) .on 'mousedown', -> offsetClicked = true oldHolderCX = handle.attr('cx') * 1 oldHolderShadowCX = handleShadow.attr('cx') * 1 oldOffsetWidth = sliderOffset.attr('width') * 1 .on 'mouseup', -> if offsetClicked x = d3.mouse(this)[0] - circleR/2 toadd = x - oldOffsetWidth console.log "toadd: #{toadd}" moveBy(toadd) offsetClicked = false handleShadow = svg.append('circle') .attr('fill', '#aaa') .attr('r', circleShadowR ) .attr('cy', height/2) .attr('cx', circleShadowR) handle = svg.append('circle') .attr('fill', '#8FC742') .attr('stroke', '#fff') .attr('stroke-width', circleStroke) .attr('r', circleR) .attr('cy', height/2) .attr('cx', circleShadowR) angular.element(handle.node()).on 'mousedown', (e) -> held = true oldPageX = e.pageX oldHolderCX = handle.attr('cx') * 1 oldHolderShadowCX = handleShadow.attr('cx') * 1 oldOffsetWidth = sliderOffset.attr('width') * 1 TextSelection.disable() updateModel = (val) -> ngModel.$setViewValue(val) if val isnt ngModel.$viewValue moveBy = (px) -> newHolderCX = oldHolderCX + px newHolderShadowCX = oldHolderShadowCX + px newOffsetWidth = oldOffsetWidth + px if (newOffsetWidth > maxOffsetWidth) newOffsetWidth = maxOffsetWidth newHolderShadowCX = maxCircleCX newHolderCX = maxCircleCX if (newOffsetWidth < minOffsetWidth) newOffsetWidth = minOffsetWidth newHolderShadowCX = minCircleCX newHolderCX = minCircleCX sliderOffset.attr('width', newOffsetWidth) handleShadow.attr('cx', newHolderShadowCX) handle.attr('cx', newHolderCX) x = ((oldOffsetWidth + px) - minOffsetWidth)/(maxOffsetWidth - minOffsetWidth) if x < 0 updateModel(x) else y = -Math.sqrt(1-Math.pow(x, 2)) + 1 updateModel(y) updateViewByValue = (val) -> return if !angular.isNumber(val) or $window.isNaN(val) or held width_percent = Math.sqrt(-Math.pow(-val+1, 2)+1) newOffsetWidth = width_percent * (maxOffsetWidth - minOffsetWidth) newOffsetWidth = newOffsetWidth + minOffsetWidth # console.log "newOffsetWidth: #{newOffsetWidth}" newHolderCX = newOffsetWidth + (circleR/2) if (newOffsetWidth > maxOffsetWidth) newOffsetWidth = maxOffsetWidth if (newHolderCX > maxCircleCX) newHolderCX = maxCircleCX if (newOffsetWidth < minOffsetWidth) newOffsetWidth = minOffsetWidth if (newHolderCX < minCircleCX) newHolderCX = minCircleCX sliderOffset.attr('width', newOffsetWidth) handleShadow.attr('cx', newHolderCX) handle.attr('cx', newHolderCX) $scope.$watch -> ngModel.$viewValue , (val) -> updateViewByValue(val) $scope.$on 'window:mousemove', (event, e) -> if held toadd = e.pageX - oldPageX moveBy(toadd) $scope.$on 'window:mouseup', (event, e) -> TextSelection.enable() if held held = false oldPageX = e.pageX resizeTimeout = null $scope.$on 'window:resize', -> svg.attr('width', elem.parent().width()) sliderBg.attr('width', elem.parent().width()) elem.parent().css(overflow: 'hidden') if (resizeTimeout) $timeout.cancel resizeTimeout resizeTimeout = null resizeTimeout = $timeout -> initDynamicVars() elem.parent().css(overflow: '') svg.attr('width', width) sliderBg.attr('width', width) updateViewByValue(ngModel.$viewValue) resizeTimeout = null , 100 $timeout -> init() , 2000 ]);
true
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <PI:EMAIL:<EMAIL>END_PI> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### window.App.directive('ampliSlider', [ '$window' 'TextSelection' '$timeout' ($window, TextSelection, $timeout) -> restrict: 'AE' replace: true require: 'ngModel' template: '<div class="ampli-slider"></div>' link: ($scope, elem, attrs, ngModel) -> elem.css(cursor: 'pointer') width = elem.width() height = 20 elem.parent().height(height) barHeight = 5 circleR = 7 circleStroke = 4 circleShadowR = circleR + (circleStroke/2) + 0.5 held = false offsetClicked = false bgClicked = false oldPageX = 0 oldOffsetWidth = 0 oldHolderCX = 0 oldHolderShadowCX = 0 minOffsetWidth = circleR - circleStroke/2 maxOffsetWidth = width - circleR * 2 minCircleCX = circleShadowR maxCircleCX = width - (circleR + circleStroke/2) - 1 initDynamicVars = -> width = elem.width() maxOffsetWidth = width - circleR * 2 maxCircleCX = width - (circleR + circleStroke/2) - 1 init = -> initDynamicVars() svg = d3.select(elem[0]) .append('svg') .attr('width', width) .attr('height', height) .attr('alignment-baseline', 'middle') sliderBg = svg.append('rect') .attr('fill', '#ccc') .attr('width', width) .attr('height', barHeight) .attr('y', (height)/2 - 2) .attr('rx', 2) .attr('ry', 2) .on 'mousedown', -> bgClicked = true oldHolderCX = handle.attr('cx') * 1 oldHolderShadowCX = handleShadow.attr('cx') * 1 oldOffsetWidth = sliderOffset.attr('width') * 1 .on 'mouseup', -> if bgClicked x = d3.mouse(this)[0] - circleR/2 toadd = x - oldOffsetWidth console.log "toadd: #{toadd}" moveBy(toadd) bgClicked = false sliderOffset = svg.append('rect') .attr('fill', 'gray') .attr('width', circleR - circleStroke/2) .attr('height', barHeight) .attr('y', (height)/2 - 2) .attr('rx', 2) .attr('ry', 2) .on 'mousedown', -> offsetClicked = true oldHolderCX = handle.attr('cx') * 1 oldHolderShadowCX = handleShadow.attr('cx') * 1 oldOffsetWidth = sliderOffset.attr('width') * 1 .on 'mouseup', -> if offsetClicked x = d3.mouse(this)[0] - circleR/2 toadd = x - oldOffsetWidth console.log "toadd: #{toadd}" moveBy(toadd) offsetClicked = false handleShadow = svg.append('circle') .attr('fill', '#aaa') .attr('r', circleShadowR ) .attr('cy', height/2) .attr('cx', circleShadowR) handle = svg.append('circle') .attr('fill', '#8FC742') .attr('stroke', '#fff') .attr('stroke-width', circleStroke) .attr('r', circleR) .attr('cy', height/2) .attr('cx', circleShadowR) angular.element(handle.node()).on 'mousedown', (e) -> held = true oldPageX = e.pageX oldHolderCX = handle.attr('cx') * 1 oldHolderShadowCX = handleShadow.attr('cx') * 1 oldOffsetWidth = sliderOffset.attr('width') * 1 TextSelection.disable() updateModel = (val) -> ngModel.$setViewValue(val) if val isnt ngModel.$viewValue moveBy = (px) -> newHolderCX = oldHolderCX + px newHolderShadowCX = oldHolderShadowCX + px newOffsetWidth = oldOffsetWidth + px if (newOffsetWidth > maxOffsetWidth) newOffsetWidth = maxOffsetWidth newHolderShadowCX = maxCircleCX newHolderCX = maxCircleCX if (newOffsetWidth < minOffsetWidth) newOffsetWidth = minOffsetWidth newHolderShadowCX = minCircleCX newHolderCX = minCircleCX sliderOffset.attr('width', newOffsetWidth) handleShadow.attr('cx', newHolderShadowCX) handle.attr('cx', newHolderCX) x = ((oldOffsetWidth + px) - minOffsetWidth)/(maxOffsetWidth - minOffsetWidth) if x < 0 updateModel(x) else y = -Math.sqrt(1-Math.pow(x, 2)) + 1 updateModel(y) updateViewByValue = (val) -> return if !angular.isNumber(val) or $window.isNaN(val) or held width_percent = Math.sqrt(-Math.pow(-val+1, 2)+1) newOffsetWidth = width_percent * (maxOffsetWidth - minOffsetWidth) newOffsetWidth = newOffsetWidth + minOffsetWidth # console.log "newOffsetWidth: #{newOffsetWidth}" newHolderCX = newOffsetWidth + (circleR/2) if (newOffsetWidth > maxOffsetWidth) newOffsetWidth = maxOffsetWidth if (newHolderCX > maxCircleCX) newHolderCX = maxCircleCX if (newOffsetWidth < minOffsetWidth) newOffsetWidth = minOffsetWidth if (newHolderCX < minCircleCX) newHolderCX = minCircleCX sliderOffset.attr('width', newOffsetWidth) handleShadow.attr('cx', newHolderCX) handle.attr('cx', newHolderCX) $scope.$watch -> ngModel.$viewValue , (val) -> updateViewByValue(val) $scope.$on 'window:mousemove', (event, e) -> if held toadd = e.pageX - oldPageX moveBy(toadd) $scope.$on 'window:mouseup', (event, e) -> TextSelection.enable() if held held = false oldPageX = e.pageX resizeTimeout = null $scope.$on 'window:resize', -> svg.attr('width', elem.parent().width()) sliderBg.attr('width', elem.parent().width()) elem.parent().css(overflow: 'hidden') if (resizeTimeout) $timeout.cancel resizeTimeout resizeTimeout = null resizeTimeout = $timeout -> initDynamicVars() elem.parent().css(overflow: '') svg.attr('width', width) sliderBg.attr('width', width) updateViewByValue(ngModel.$viewValue) resizeTimeout = null , 100 $timeout -> init() , 2000 ]);
[ { "context": "lback) ->\n\n if isMine account\n owner = 'you'\n auxVerb =\n have : 'have'\n be", "end": 2778, "score": 0.6975342631340027, "start": 2775, "tag": "NAME", "value": "you" } ]
client/members/lib/index.coffee
ezgikaysi/koding
1
kd = require 'kd' KDListViewController = kd.ListViewController KDView = kd.View MemberActivityListController = require './memberactivitylistcontroller' ContentDisplayScrollableView = require './contentdisplays/contentdisplayscrollableview' GroupMembersPageListItemView = require './groupmemberspagelistitemview' ProfileView = require './contentdisplays/profileview' remote = require('app/remote').getInstance() globals = require 'globals' getFullnameFromAccount = require 'app/util/getFullnameFromAccount' getGroup = require 'app/util/getGroup' whoami = require 'app/util/whoami' isMine = require 'app/util/isMine' AppController = require 'app/appcontroller' ActivityListItemView = require 'activity/views/activitylistitemview' FilterLinksView = require 'activity/views/filterlinksview' module.exports = class MembersAppController extends AppController @options = name : 'Members' dependencies : [ 'Activity' ] { externalProfiles } = globals.config constructor: (options = {}, data) -> options.view = new KDView cssClass : 'content-page members' options.appInfo = name : 'Members' @appManager = kd.getSingleton 'appManager' super options, data createContentDisplay: (model, callback = -> ) -> kd.singletons.appManager.setFrontApp this { JAccount } = remote.api type = if model instanceof JAccount then 'profile' else 'members' contentDisplay = new KDView cssClass : 'member content-display' type : type contentDisplay.on 'handleQuery', (query) => @ready => @feedController?.handleQuery? query contentDisplay.once 'KDObjectWillBeDestroyed', -> kd.singleton('appManager').tell 'Activity', 'resetProfileLastTo' kd.getSingleton('groupsController').ready => contentDisplay.$('div.lazy').remove() if type is 'profile' @createProfileView contentDisplay, model else @createGroupMembersView contentDisplay contentDisplay.addSubView new FilterLinksView filters : ['Posts'] default : 'Posts' @showContentDisplay contentDisplay kd.utils.defer -> callback contentDisplay createProfileView: (contentDisplay, model) -> @prepareProfileView model, (profileView) => contentDisplay.addSubView profileView @prepareFeederView model, (feederView) -> contentDisplay.addSubView feederView createGroupMembersView: (contentDisplay) -> # assuming, not being used - sy # contentDisplay.addSubView new HeaderViewSection # title : "Members" # type : "big" @prepareFeederView whoami(), (feederView) -> contentDisplay.addSubView feederView prepareFeederView: (account, callback) -> if isMine account owner = 'you' auxVerb = have : 'have' be : 'are' else owner = getFullnameFromAccount account auxVerb = have : 'has' be : 'is' kd.getSingleton('appManager').tell 'Feeder', 'createContentFeedController', { itemClass : ActivityListItemView listControllerClass : MemberActivityListController listCssClass : 'activity-related' limitPerPage : 8 useHeaderNav : yes delegate : this creator : account filter : statuses : noItemFoundText : "#{owner} #{auxVerb.have} not shared any posts yet." dataSource : (selector, options = {}, callback) -> options.targetId = account.socialApiId kd.singletons.socialapi.channel.fetchProfileFeed options, callback followers : loggedInOnly : yes itemClass : GroupMembersPageListItemView listControllerClass: KDListViewController listCssClass : 'member-related' noItemFoundText : "No one is following #{owner} yet." dataSource : (selector, options, callback) -> options.groupId or= getGroup().getId() account.fetchFollowersWithRelationship selector, options, callback following : loggedInOnly : yes itemClass : GroupMembersPageListItemView listControllerClass: KDListViewController listCssClass : 'member-related' noItemFoundText : "#{owner} #{auxVerb.be} not following anyone." dataSource : (selector, options, callback) -> options.groupId or= getGroup().getId() account.fetchFollowingWithRelationship selector, options, callback likes : loggedInOnly : yes noItemFoundText : "#{owner} #{auxVerb.have} not liked any posts yet." dataSource : (selector, options, callback) -> return callback { message: 'not impplemented feature' } members : noItemFoundText : 'There is no member.' itemClass : GroupMembersPageListItemView listControllerClass: KDListViewController listCssClass : 'member-related' title : '' dataSource : (selector, options, callback) => group = getGroup() group.fetchMembers selector, options, (err, res) => @emit 'MemberListLoaded' unless err callback err, res sort : 'modifiedAt' : title : 'Latest activity' direction : -1 'counts.followers' : title : 'Most followers' direction : -1 'counts.following' : title : 'Most following' direction : -1 'timestamp|new' : title : 'Latest activity' direction : -1 'timestamp|old' : title : 'Most activity' direction : 1 }, (controller) => @feedController = controller callback controller.getView() @emit 'ready' prepareProfileView: (member, callback) -> options = tagName : 'aside' cssClass : 'app-sidebar clearfix' if isMine member options.cssClass = kd.utils.curry 'own-profile', options.cssClass else options.bind = 'mouseenter' unless isMine member callback new ProfileView options, member showContentDisplay: (contentDisplay) -> view = new ContentDisplayScrollableView contentDisplay : contentDisplay @forwardEvent view, 'LazyLoadThresholdReached' kd.singleton('display').emit 'ContentDisplayWantsToBeShown', view return contentDisplay fetchFeedForHomePage: (callback) -> options = limit : 6 skip : 0 sort : { 'meta.modifiedAt' : -1 } selector = {} remote.api.JAccount.someWithRelationship selector, options, callback fetchSomeMembers: (options = {}, callback) -> options.limit or= 6 options.skip or= 0 options.sort or= { 'meta.modifiedAt' : -1 } selector = options.selector or {} console.log { selector } delete options.selector if options.selector remote.api.JAccount.byRelevance selector, options, callback fetchExternalProfiles: (account, callback) -> whitelist = Object.keys(externalProfiles).slice().map (a) -> "ext|profile|#{a}" account.fetchStorages whitelist, callback
223894
kd = require 'kd' KDListViewController = kd.ListViewController KDView = kd.View MemberActivityListController = require './memberactivitylistcontroller' ContentDisplayScrollableView = require './contentdisplays/contentdisplayscrollableview' GroupMembersPageListItemView = require './groupmemberspagelistitemview' ProfileView = require './contentdisplays/profileview' remote = require('app/remote').getInstance() globals = require 'globals' getFullnameFromAccount = require 'app/util/getFullnameFromAccount' getGroup = require 'app/util/getGroup' whoami = require 'app/util/whoami' isMine = require 'app/util/isMine' AppController = require 'app/appcontroller' ActivityListItemView = require 'activity/views/activitylistitemview' FilterLinksView = require 'activity/views/filterlinksview' module.exports = class MembersAppController extends AppController @options = name : 'Members' dependencies : [ 'Activity' ] { externalProfiles } = globals.config constructor: (options = {}, data) -> options.view = new KDView cssClass : 'content-page members' options.appInfo = name : 'Members' @appManager = kd.getSingleton 'appManager' super options, data createContentDisplay: (model, callback = -> ) -> kd.singletons.appManager.setFrontApp this { JAccount } = remote.api type = if model instanceof JAccount then 'profile' else 'members' contentDisplay = new KDView cssClass : 'member content-display' type : type contentDisplay.on 'handleQuery', (query) => @ready => @feedController?.handleQuery? query contentDisplay.once 'KDObjectWillBeDestroyed', -> kd.singleton('appManager').tell 'Activity', 'resetProfileLastTo' kd.getSingleton('groupsController').ready => contentDisplay.$('div.lazy').remove() if type is 'profile' @createProfileView contentDisplay, model else @createGroupMembersView contentDisplay contentDisplay.addSubView new FilterLinksView filters : ['Posts'] default : 'Posts' @showContentDisplay contentDisplay kd.utils.defer -> callback contentDisplay createProfileView: (contentDisplay, model) -> @prepareProfileView model, (profileView) => contentDisplay.addSubView profileView @prepareFeederView model, (feederView) -> contentDisplay.addSubView feederView createGroupMembersView: (contentDisplay) -> # assuming, not being used - sy # contentDisplay.addSubView new HeaderViewSection # title : "Members" # type : "big" @prepareFeederView whoami(), (feederView) -> contentDisplay.addSubView feederView prepareFeederView: (account, callback) -> if isMine account owner = '<NAME>' auxVerb = have : 'have' be : 'are' else owner = getFullnameFromAccount account auxVerb = have : 'has' be : 'is' kd.getSingleton('appManager').tell 'Feeder', 'createContentFeedController', { itemClass : ActivityListItemView listControllerClass : MemberActivityListController listCssClass : 'activity-related' limitPerPage : 8 useHeaderNav : yes delegate : this creator : account filter : statuses : noItemFoundText : "#{owner} #{auxVerb.have} not shared any posts yet." dataSource : (selector, options = {}, callback) -> options.targetId = account.socialApiId kd.singletons.socialapi.channel.fetchProfileFeed options, callback followers : loggedInOnly : yes itemClass : GroupMembersPageListItemView listControllerClass: KDListViewController listCssClass : 'member-related' noItemFoundText : "No one is following #{owner} yet." dataSource : (selector, options, callback) -> options.groupId or= getGroup().getId() account.fetchFollowersWithRelationship selector, options, callback following : loggedInOnly : yes itemClass : GroupMembersPageListItemView listControllerClass: KDListViewController listCssClass : 'member-related' noItemFoundText : "#{owner} #{auxVerb.be} not following anyone." dataSource : (selector, options, callback) -> options.groupId or= getGroup().getId() account.fetchFollowingWithRelationship selector, options, callback likes : loggedInOnly : yes noItemFoundText : "#{owner} #{auxVerb.have} not liked any posts yet." dataSource : (selector, options, callback) -> return callback { message: 'not impplemented feature' } members : noItemFoundText : 'There is no member.' itemClass : GroupMembersPageListItemView listControllerClass: KDListViewController listCssClass : 'member-related' title : '' dataSource : (selector, options, callback) => group = getGroup() group.fetchMembers selector, options, (err, res) => @emit 'MemberListLoaded' unless err callback err, res sort : 'modifiedAt' : title : 'Latest activity' direction : -1 'counts.followers' : title : 'Most followers' direction : -1 'counts.following' : title : 'Most following' direction : -1 'timestamp|new' : title : 'Latest activity' direction : -1 'timestamp|old' : title : 'Most activity' direction : 1 }, (controller) => @feedController = controller callback controller.getView() @emit 'ready' prepareProfileView: (member, callback) -> options = tagName : 'aside' cssClass : 'app-sidebar clearfix' if isMine member options.cssClass = kd.utils.curry 'own-profile', options.cssClass else options.bind = 'mouseenter' unless isMine member callback new ProfileView options, member showContentDisplay: (contentDisplay) -> view = new ContentDisplayScrollableView contentDisplay : contentDisplay @forwardEvent view, 'LazyLoadThresholdReached' kd.singleton('display').emit 'ContentDisplayWantsToBeShown', view return contentDisplay fetchFeedForHomePage: (callback) -> options = limit : 6 skip : 0 sort : { 'meta.modifiedAt' : -1 } selector = {} remote.api.JAccount.someWithRelationship selector, options, callback fetchSomeMembers: (options = {}, callback) -> options.limit or= 6 options.skip or= 0 options.sort or= { 'meta.modifiedAt' : -1 } selector = options.selector or {} console.log { selector } delete options.selector if options.selector remote.api.JAccount.byRelevance selector, options, callback fetchExternalProfiles: (account, callback) -> whitelist = Object.keys(externalProfiles).slice().map (a) -> "ext|profile|#{a}" account.fetchStorages whitelist, callback
true
kd = require 'kd' KDListViewController = kd.ListViewController KDView = kd.View MemberActivityListController = require './memberactivitylistcontroller' ContentDisplayScrollableView = require './contentdisplays/contentdisplayscrollableview' GroupMembersPageListItemView = require './groupmemberspagelistitemview' ProfileView = require './contentdisplays/profileview' remote = require('app/remote').getInstance() globals = require 'globals' getFullnameFromAccount = require 'app/util/getFullnameFromAccount' getGroup = require 'app/util/getGroup' whoami = require 'app/util/whoami' isMine = require 'app/util/isMine' AppController = require 'app/appcontroller' ActivityListItemView = require 'activity/views/activitylistitemview' FilterLinksView = require 'activity/views/filterlinksview' module.exports = class MembersAppController extends AppController @options = name : 'Members' dependencies : [ 'Activity' ] { externalProfiles } = globals.config constructor: (options = {}, data) -> options.view = new KDView cssClass : 'content-page members' options.appInfo = name : 'Members' @appManager = kd.getSingleton 'appManager' super options, data createContentDisplay: (model, callback = -> ) -> kd.singletons.appManager.setFrontApp this { JAccount } = remote.api type = if model instanceof JAccount then 'profile' else 'members' contentDisplay = new KDView cssClass : 'member content-display' type : type contentDisplay.on 'handleQuery', (query) => @ready => @feedController?.handleQuery? query contentDisplay.once 'KDObjectWillBeDestroyed', -> kd.singleton('appManager').tell 'Activity', 'resetProfileLastTo' kd.getSingleton('groupsController').ready => contentDisplay.$('div.lazy').remove() if type is 'profile' @createProfileView contentDisplay, model else @createGroupMembersView contentDisplay contentDisplay.addSubView new FilterLinksView filters : ['Posts'] default : 'Posts' @showContentDisplay contentDisplay kd.utils.defer -> callback contentDisplay createProfileView: (contentDisplay, model) -> @prepareProfileView model, (profileView) => contentDisplay.addSubView profileView @prepareFeederView model, (feederView) -> contentDisplay.addSubView feederView createGroupMembersView: (contentDisplay) -> # assuming, not being used - sy # contentDisplay.addSubView new HeaderViewSection # title : "Members" # type : "big" @prepareFeederView whoami(), (feederView) -> contentDisplay.addSubView feederView prepareFeederView: (account, callback) -> if isMine account owner = 'PI:NAME:<NAME>END_PI' auxVerb = have : 'have' be : 'are' else owner = getFullnameFromAccount account auxVerb = have : 'has' be : 'is' kd.getSingleton('appManager').tell 'Feeder', 'createContentFeedController', { itemClass : ActivityListItemView listControllerClass : MemberActivityListController listCssClass : 'activity-related' limitPerPage : 8 useHeaderNav : yes delegate : this creator : account filter : statuses : noItemFoundText : "#{owner} #{auxVerb.have} not shared any posts yet." dataSource : (selector, options = {}, callback) -> options.targetId = account.socialApiId kd.singletons.socialapi.channel.fetchProfileFeed options, callback followers : loggedInOnly : yes itemClass : GroupMembersPageListItemView listControllerClass: KDListViewController listCssClass : 'member-related' noItemFoundText : "No one is following #{owner} yet." dataSource : (selector, options, callback) -> options.groupId or= getGroup().getId() account.fetchFollowersWithRelationship selector, options, callback following : loggedInOnly : yes itemClass : GroupMembersPageListItemView listControllerClass: KDListViewController listCssClass : 'member-related' noItemFoundText : "#{owner} #{auxVerb.be} not following anyone." dataSource : (selector, options, callback) -> options.groupId or= getGroup().getId() account.fetchFollowingWithRelationship selector, options, callback likes : loggedInOnly : yes noItemFoundText : "#{owner} #{auxVerb.have} not liked any posts yet." dataSource : (selector, options, callback) -> return callback { message: 'not impplemented feature' } members : noItemFoundText : 'There is no member.' itemClass : GroupMembersPageListItemView listControllerClass: KDListViewController listCssClass : 'member-related' title : '' dataSource : (selector, options, callback) => group = getGroup() group.fetchMembers selector, options, (err, res) => @emit 'MemberListLoaded' unless err callback err, res sort : 'modifiedAt' : title : 'Latest activity' direction : -1 'counts.followers' : title : 'Most followers' direction : -1 'counts.following' : title : 'Most following' direction : -1 'timestamp|new' : title : 'Latest activity' direction : -1 'timestamp|old' : title : 'Most activity' direction : 1 }, (controller) => @feedController = controller callback controller.getView() @emit 'ready' prepareProfileView: (member, callback) -> options = tagName : 'aside' cssClass : 'app-sidebar clearfix' if isMine member options.cssClass = kd.utils.curry 'own-profile', options.cssClass else options.bind = 'mouseenter' unless isMine member callback new ProfileView options, member showContentDisplay: (contentDisplay) -> view = new ContentDisplayScrollableView contentDisplay : contentDisplay @forwardEvent view, 'LazyLoadThresholdReached' kd.singleton('display').emit 'ContentDisplayWantsToBeShown', view return contentDisplay fetchFeedForHomePage: (callback) -> options = limit : 6 skip : 0 sort : { 'meta.modifiedAt' : -1 } selector = {} remote.api.JAccount.someWithRelationship selector, options, callback fetchSomeMembers: (options = {}, callback) -> options.limit or= 6 options.skip or= 0 options.sort or= { 'meta.modifiedAt' : -1 } selector = options.selector or {} console.log { selector } delete options.selector if options.selector remote.api.JAccount.byRelevance selector, options, callback fetchExternalProfiles: (account, callback) -> whitelist = Object.keys(externalProfiles).slice().map (a) -> "ext|profile|#{a}" account.fetchStorages whitelist, callback
[ { "context": "jector](http://neocotic.com/injector)\n#\n# (c) 2014 Alasdair Mercer\n#\n# Freely distributable under the MIT license\n\n#", "end": 71, "score": 0.9998733401298523, "start": 56, "tag": "NAME", "value": "Alasdair Mercer" } ]
src/coffee/utils.coffee
SlinkySalmon633/injector-chrome
33
# [Injector](http://neocotic.com/injector) # # (c) 2014 Alasdair Mercer # # Freely distributable under the MIT license # Utilities # --------- # Extend `_` with our utility functions. _.mixin { # Transform the given string into title case. capitalize: (str) -> return str unless str str.replace /\w+/g, (word) -> word[0].toUpperCase() + word[1..].toLowerCase() } # Enforcing the use of a template variable significantly optmizes the rendering of templates. _.templateSettings.variable = 'ctx'
180075
# [Injector](http://neocotic.com/injector) # # (c) 2014 <NAME> # # Freely distributable under the MIT license # Utilities # --------- # Extend `_` with our utility functions. _.mixin { # Transform the given string into title case. capitalize: (str) -> return str unless str str.replace /\w+/g, (word) -> word[0].toUpperCase() + word[1..].toLowerCase() } # Enforcing the use of a template variable significantly optmizes the rendering of templates. _.templateSettings.variable = 'ctx'
true
# [Injector](http://neocotic.com/injector) # # (c) 2014 PI:NAME:<NAME>END_PI # # Freely distributable under the MIT license # Utilities # --------- # Extend `_` with our utility functions. _.mixin { # Transform the given string into title case. capitalize: (str) -> return str unless str str.replace /\w+/g, (word) -> word[0].toUpperCase() + word[1..].toLowerCase() } # Enforcing the use of a template variable significantly optmizes the rendering of templates. _.templateSettings.variable = 'ctx'
[ { "context": "#\t> File Name: article.coffee\n#\t> Author: LY\n#\t> Mail: ly.franky@gmail.com\n#\t> Created Time: T", "end": 44, "score": 0.9971282482147217, "start": 42, "tag": "USERNAME", "value": "LY" }, { "context": "File Name: article.coffee\n#\t> Author: LY\n#\t> Mail: ly.franky@gmail.com\n#\t> Created Time: Thursday, November 27, 2014 PM0", "end": 74, "score": 0.9999299645423889, "start": 55, "tag": "EMAIL", "value": "ly.franky@gmail.com" } ]
server/routes/article.coffee
Booker-Z/MIAC-website
0
# > File Name: article.coffee # > Author: LY # > Mail: ly.franky@gmail.com # > Created Time: Thursday, November 27, 2014 PM07:09:34 CST express = require 'express' mongoose = require 'mongoose' async = require 'async' router = express.Router() ArticleModel = require '../db/models/article.coffee' { requireLogin } = require './helpers/authorization.coffee' MessageModel = require '../db/models/message.coffee' ### * render 'article' when get '/article' * find all the articles in ArticleModel * render with articles ### router.get '/', (req, res)-> ArticleModel.find {}, (err, articles)-> if err return res.status(500).send 'Server Error.' else res.render 'article', articles: articles ### * render 'childArticle' when get '/article/create' ### router.get '/create', requireLogin, (req, res)-> res.render 'createArticle' ### * render 'childArticle' when get '/article/:id' * find a article with the article's id * find comments in MessageModel with album's id * find reply in comment's id for each comment in comments * render with article as well as comments(containing replys) * @param id: the ObjectId of the specific article ### router.get '/:id', (req, res)-> id = mongoose.Types.ObjectId req.params.id ArticleModel.findOne { _id: id }, (err, article)-> if err return res.status(500).send 'Server Error.' else MessageModel.find { replyTo: id , type: 'comment'}, (err, comments)-> if not comments res.render 'childArticle', article: article else async.each comments, (comment, callback)-> MessageModel.find { replyTo: comment._id, type: 'reply' }, (err, replys)-> if not replys callback() else comment.replys = replys callback() , (err)-> res.render 'childArticle', { article: article, comments: comments } ### * handle when post '/article/create' * require user's login to continue process * return fail when title has already existed * return fail when params is not completed * create article in ArticleModel with title, content, user's id and category * @param category: the category of article * @param title: article's title, which is one and only * @param content: article's content ### router.post '/create', requireLogin, (req, res)-> { category, title, content } = req.body createdBy = req.session.user.username ArticleModel.findOne { title }, (err, article)-> if article return res.json { result: 'fail', msg: 'Article has already existed.' } else if not title or not content or not createdBy return res.json { result: 'fail', msg: 'Info not completed.' } else ArticleModel.createArticle category, title, content, createdBy, -> res.json { result: 'success' } module.exports = router
113324
# > File Name: article.coffee # > Author: LY # > Mail: <EMAIL> # > Created Time: Thursday, November 27, 2014 PM07:09:34 CST express = require 'express' mongoose = require 'mongoose' async = require 'async' router = express.Router() ArticleModel = require '../db/models/article.coffee' { requireLogin } = require './helpers/authorization.coffee' MessageModel = require '../db/models/message.coffee' ### * render 'article' when get '/article' * find all the articles in ArticleModel * render with articles ### router.get '/', (req, res)-> ArticleModel.find {}, (err, articles)-> if err return res.status(500).send 'Server Error.' else res.render 'article', articles: articles ### * render 'childArticle' when get '/article/create' ### router.get '/create', requireLogin, (req, res)-> res.render 'createArticle' ### * render 'childArticle' when get '/article/:id' * find a article with the article's id * find comments in MessageModel with album's id * find reply in comment's id for each comment in comments * render with article as well as comments(containing replys) * @param id: the ObjectId of the specific article ### router.get '/:id', (req, res)-> id = mongoose.Types.ObjectId req.params.id ArticleModel.findOne { _id: id }, (err, article)-> if err return res.status(500).send 'Server Error.' else MessageModel.find { replyTo: id , type: 'comment'}, (err, comments)-> if not comments res.render 'childArticle', article: article else async.each comments, (comment, callback)-> MessageModel.find { replyTo: comment._id, type: 'reply' }, (err, replys)-> if not replys callback() else comment.replys = replys callback() , (err)-> res.render 'childArticle', { article: article, comments: comments } ### * handle when post '/article/create' * require user's login to continue process * return fail when title has already existed * return fail when params is not completed * create article in ArticleModel with title, content, user's id and category * @param category: the category of article * @param title: article's title, which is one and only * @param content: article's content ### router.post '/create', requireLogin, (req, res)-> { category, title, content } = req.body createdBy = req.session.user.username ArticleModel.findOne { title }, (err, article)-> if article return res.json { result: 'fail', msg: 'Article has already existed.' } else if not title or not content or not createdBy return res.json { result: 'fail', msg: 'Info not completed.' } else ArticleModel.createArticle category, title, content, createdBy, -> res.json { result: 'success' } module.exports = router
true
# > File Name: article.coffee # > Author: LY # > Mail: PI:EMAIL:<EMAIL>END_PI # > Created Time: Thursday, November 27, 2014 PM07:09:34 CST express = require 'express' mongoose = require 'mongoose' async = require 'async' router = express.Router() ArticleModel = require '../db/models/article.coffee' { requireLogin } = require './helpers/authorization.coffee' MessageModel = require '../db/models/message.coffee' ### * render 'article' when get '/article' * find all the articles in ArticleModel * render with articles ### router.get '/', (req, res)-> ArticleModel.find {}, (err, articles)-> if err return res.status(500).send 'Server Error.' else res.render 'article', articles: articles ### * render 'childArticle' when get '/article/create' ### router.get '/create', requireLogin, (req, res)-> res.render 'createArticle' ### * render 'childArticle' when get '/article/:id' * find a article with the article's id * find comments in MessageModel with album's id * find reply in comment's id for each comment in comments * render with article as well as comments(containing replys) * @param id: the ObjectId of the specific article ### router.get '/:id', (req, res)-> id = mongoose.Types.ObjectId req.params.id ArticleModel.findOne { _id: id }, (err, article)-> if err return res.status(500).send 'Server Error.' else MessageModel.find { replyTo: id , type: 'comment'}, (err, comments)-> if not comments res.render 'childArticle', article: article else async.each comments, (comment, callback)-> MessageModel.find { replyTo: comment._id, type: 'reply' }, (err, replys)-> if not replys callback() else comment.replys = replys callback() , (err)-> res.render 'childArticle', { article: article, comments: comments } ### * handle when post '/article/create' * require user's login to continue process * return fail when title has already existed * return fail when params is not completed * create article in ArticleModel with title, content, user's id and category * @param category: the category of article * @param title: article's title, which is one and only * @param content: article's content ### router.post '/create', requireLogin, (req, res)-> { category, title, content } = req.body createdBy = req.session.user.username ArticleModel.findOne { title }, (err, article)-> if article return res.json { result: 'fail', msg: 'Article has already existed.' } else if not title or not content or not createdBy return res.json { result: 'fail', msg: 'Info not completed.' } else ArticleModel.createArticle category, title, content, createdBy, -> res.json { result: 'success' } module.exports = router
[ { "context": " (done) ->\n @timeout 10000\n temp.mkdir 'murphy', (err, tempPath) ->\n files = []\n o", "end": 1394, "score": 0.8876899480819702, "start": 1388, "tag": "NAME", "value": "murphy" } ]
spec/ExtractImages.coffee
noflo/noflo-tika
1
noflo = require 'noflo' chai = require 'chai' unless chai path = require 'path' Extract = require '../components/ExtractImages.coffee' temp = require 'temp' fs = require 'fs' describe 'ExtractImages component', -> c = null ins = null dir = null out = null nothing = null beforeEach -> c = Extract.getComponent() ins = noflo.internalSocket.createSocket() dir = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() nothing = noflo.internalSocket.createSocket() c.inPorts.in.attach ins c.inPorts.dir.attach dir c.outPorts.out.attach out c.outPorts.nothing.attach nothing describe 'when instantiated', -> it 'should have an input port', -> chai.expect(c.inPorts.in).to.be.an 'object' it 'should have an output port', -> chai.expect(c.outPorts.out).to.be.an 'object' describe 'extracting images from Word documents', -> it 'shouldn\'t find images for a simple file', (done) -> temp.mkdir 'file', (err, tempPath) -> out.on 'data', (data) -> chai.expect(true).to.equal false nothing.on 'data', () -> chai.expect(true).to.equal true done() dir.send tempPath ins.send path.resolve __dirname, 'fixtures/file.doc' ins.disconnect() it 'should find images from file', (done) -> @timeout 10000 temp.mkdir 'murphy', (err, tempPath) -> files = [] out.on 'data', (data) -> files.push data nothing.on 'data', (data) -> chai.expect(true).to.equal false out.on 'disconnect', -> chai.expect(files.length).to.be.above 5 for f in files chai.expect(fs.existsSync(f)).to.equal true done() dir.send tempPath ins.send path.resolve __dirname, 'fixtures/trm-design-project-murphy.docx' ins.disconnect()
92439
noflo = require 'noflo' chai = require 'chai' unless chai path = require 'path' Extract = require '../components/ExtractImages.coffee' temp = require 'temp' fs = require 'fs' describe 'ExtractImages component', -> c = null ins = null dir = null out = null nothing = null beforeEach -> c = Extract.getComponent() ins = noflo.internalSocket.createSocket() dir = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() nothing = noflo.internalSocket.createSocket() c.inPorts.in.attach ins c.inPorts.dir.attach dir c.outPorts.out.attach out c.outPorts.nothing.attach nothing describe 'when instantiated', -> it 'should have an input port', -> chai.expect(c.inPorts.in).to.be.an 'object' it 'should have an output port', -> chai.expect(c.outPorts.out).to.be.an 'object' describe 'extracting images from Word documents', -> it 'shouldn\'t find images for a simple file', (done) -> temp.mkdir 'file', (err, tempPath) -> out.on 'data', (data) -> chai.expect(true).to.equal false nothing.on 'data', () -> chai.expect(true).to.equal true done() dir.send tempPath ins.send path.resolve __dirname, 'fixtures/file.doc' ins.disconnect() it 'should find images from file', (done) -> @timeout 10000 temp.mkdir '<NAME>', (err, tempPath) -> files = [] out.on 'data', (data) -> files.push data nothing.on 'data', (data) -> chai.expect(true).to.equal false out.on 'disconnect', -> chai.expect(files.length).to.be.above 5 for f in files chai.expect(fs.existsSync(f)).to.equal true done() dir.send tempPath ins.send path.resolve __dirname, 'fixtures/trm-design-project-murphy.docx' ins.disconnect()
true
noflo = require 'noflo' chai = require 'chai' unless chai path = require 'path' Extract = require '../components/ExtractImages.coffee' temp = require 'temp' fs = require 'fs' describe 'ExtractImages component', -> c = null ins = null dir = null out = null nothing = null beforeEach -> c = Extract.getComponent() ins = noflo.internalSocket.createSocket() dir = noflo.internalSocket.createSocket() out = noflo.internalSocket.createSocket() nothing = noflo.internalSocket.createSocket() c.inPorts.in.attach ins c.inPorts.dir.attach dir c.outPorts.out.attach out c.outPorts.nothing.attach nothing describe 'when instantiated', -> it 'should have an input port', -> chai.expect(c.inPorts.in).to.be.an 'object' it 'should have an output port', -> chai.expect(c.outPorts.out).to.be.an 'object' describe 'extracting images from Word documents', -> it 'shouldn\'t find images for a simple file', (done) -> temp.mkdir 'file', (err, tempPath) -> out.on 'data', (data) -> chai.expect(true).to.equal false nothing.on 'data', () -> chai.expect(true).to.equal true done() dir.send tempPath ins.send path.resolve __dirname, 'fixtures/file.doc' ins.disconnect() it 'should find images from file', (done) -> @timeout 10000 temp.mkdir 'PI:NAME:<NAME>END_PI', (err, tempPath) -> files = [] out.on 'data', (data) -> files.push data nothing.on 'data', (data) -> chai.expect(true).to.equal false out.on 'disconnect', -> chai.expect(files.length).to.be.above 5 for f in files chai.expect(fs.existsSync(f)).to.equal true done() dir.send tempPath ins.send path.resolve __dirname, 'fixtures/trm-design-project-murphy.docx' ins.disconnect()
[ { "context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Cof", "end": 23, "score": 0.9998787045478821, "start": 13, "tag": "NAME", "value": "Mat Groves" }, { "context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Coffixi/textures/Tex", "end": 40, "score": 0.8104812502861023, "start": 31, "tag": "USERNAME", "value": "matgroves" }, { "context": "###*\n@author Mat Groves http://matgroves.com/ @Doormat23\n###\n\ndefine 'Coffixi/textures/Texture', [\n 'Coff", "end": 56, "score": 0.9993347525596619, "start": 46, "tag": "USERNAME", "value": "@Doormat23" } ]
src/Coffixi/textures/Texture.coffee
namuol/Coffixi
1
###* @author Mat Groves http://matgroves.com/ @Doormat23 ### define 'Coffixi/textures/Texture', [ 'Coffixi/utils/Module' 'Coffixi/utils/HasSignals' './BaseTexture' 'Coffixi/core/Rectangle' 'Coffixi/core/Point' ], ( Module HasSignals BaseTexture Rectangle Point ) -> ###* A texture stores the information that represents an image or part of an image. It cannot be added to the display list directly. To do this use Sprite. If no frame is provided then the whole image is used @class Texture @extends Module @uses HasSignals @constructor @param baseTexture {BaseTexture} The base texture source to create the texture from @param frmae {Rectangle} The rectangle frame of the texture to show ### class Texture extends Module @mixin HasSignals @cache: {} @frameUpdates: [] constructor: (baseTexture, frame) -> super if not frame @noFrame = true frame = new Rectangle(0, 0, 1, 1) if baseTexture instanceof Texture baseTexture = baseTexture.baseTexture ###* The base texture of this texture @property baseTexture @type BaseTexture ### @baseTexture = baseTexture ###* The frame specifies the region of the base texture that this texture uses @property frame @type Rectangle ### @frame = frame ###* The trim point @property trim @type Point ### @trim = new Point() if baseTexture.hasLoaded frame = new Rectangle(0, 0, baseTexture.width, baseTexture.height) if @noFrame #console.log(frame) @setFrame frame else baseTexture.on 'loaded', => @onBaseTextureLoaded() ###* Called when the base texture is loaded @method onBaseTextureLoaded @param event @private ### onBaseTextureLoaded: (event) -> baseTexture = @baseTexture # baseTexture.off 'loaded', @onLoaded @frame = new Rectangle(0, 0, baseTexture.width, baseTexture.height) if @noFrame @noFrame = false @width = @frame.width @height = @frame.height @emit 'update', @ ###* Destroys this texture @method destroy @param destroyBase {Boolean} Whether to destroy the base texture as well ### destroy: (destroyBase) -> @baseTexture.destroy() if destroyBase ###* Specifies the rectangle region of the baseTexture @method setFrame @param frame {Rectangle} The frame of the texture to set it to ### setFrame: (frame) -> @frame = frame @width = frame.width @height = frame.height if frame.x + frame.width > @baseTexture.width or frame.y + frame.height > @baseTexture.height throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this) @updateFrame = true Texture.frameUpdates.push this getPixel: (x,y) -> @baseTexture.getPixel @frame.x + x, @frame.y + y beginRead: -> @baseTexture.beginRead() endRead: -> @baseTexture.endRead() ###* Helper function that returns a texture based on an image url If the image is not in the texture cache it will be created and loaded @static @method fromImage @param imageUrl {String} The image url of the texture @param crossorigin {Boolean} Whether requests should be treated as crossorigin @return Texture ### @fromImage: (imageUrl, crossorigin) -> texture = Texture.cache[imageUrl] unless texture texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin)) Texture.cache[imageUrl] = texture texture ###* Helper function that returns a texture based on a frame id If the frame id is not in the texture cache an error will be thrown @static @method fromFrame @param frameId {String} The frame id of the texture @return Texture ### @fromFrame: (frameId) -> texture = Texture.cache[frameId] throw new Error("The frameId '" + frameId + "' does not exist in the texture cache " + this) unless texture texture ###* Helper function that returns a texture based on a canvas element If the canvas is not in the texture cache it will be created and loaded @static @method fromCanvas @param canvas {Canvas} The canvas element source of the texture @return Texture ### @fromCanvas: (canvas) -> baseTexture = new BaseTexture(canvas) new Texture(baseTexture) ###* Adds a texture to the textureCache. @static @method addTextureToCache @param texture {Texture} @param id {String} the id that the texture will be stored against. ### @addTextureToCache: (texture, id) -> Texture.cache[id] = texture ###* Remove a texture from the textureCache. @static @method removeTextureFromCache @param id {String} the id of the texture to be removed @return {Texture} the texture that was removed ### @removeTextureFromCache: (id) -> texture = Texture.cache[id] Texture.cache[id] = null texture
117302
###* @author <NAME> http://matgroves.com/ @Doormat23 ### define 'Coffixi/textures/Texture', [ 'Coffixi/utils/Module' 'Coffixi/utils/HasSignals' './BaseTexture' 'Coffixi/core/Rectangle' 'Coffixi/core/Point' ], ( Module HasSignals BaseTexture Rectangle Point ) -> ###* A texture stores the information that represents an image or part of an image. It cannot be added to the display list directly. To do this use Sprite. If no frame is provided then the whole image is used @class Texture @extends Module @uses HasSignals @constructor @param baseTexture {BaseTexture} The base texture source to create the texture from @param frmae {Rectangle} The rectangle frame of the texture to show ### class Texture extends Module @mixin HasSignals @cache: {} @frameUpdates: [] constructor: (baseTexture, frame) -> super if not frame @noFrame = true frame = new Rectangle(0, 0, 1, 1) if baseTexture instanceof Texture baseTexture = baseTexture.baseTexture ###* The base texture of this texture @property baseTexture @type BaseTexture ### @baseTexture = baseTexture ###* The frame specifies the region of the base texture that this texture uses @property frame @type Rectangle ### @frame = frame ###* The trim point @property trim @type Point ### @trim = new Point() if baseTexture.hasLoaded frame = new Rectangle(0, 0, baseTexture.width, baseTexture.height) if @noFrame #console.log(frame) @setFrame frame else baseTexture.on 'loaded', => @onBaseTextureLoaded() ###* Called when the base texture is loaded @method onBaseTextureLoaded @param event @private ### onBaseTextureLoaded: (event) -> baseTexture = @baseTexture # baseTexture.off 'loaded', @onLoaded @frame = new Rectangle(0, 0, baseTexture.width, baseTexture.height) if @noFrame @noFrame = false @width = @frame.width @height = @frame.height @emit 'update', @ ###* Destroys this texture @method destroy @param destroyBase {Boolean} Whether to destroy the base texture as well ### destroy: (destroyBase) -> @baseTexture.destroy() if destroyBase ###* Specifies the rectangle region of the baseTexture @method setFrame @param frame {Rectangle} The frame of the texture to set it to ### setFrame: (frame) -> @frame = frame @width = frame.width @height = frame.height if frame.x + frame.width > @baseTexture.width or frame.y + frame.height > @baseTexture.height throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this) @updateFrame = true Texture.frameUpdates.push this getPixel: (x,y) -> @baseTexture.getPixel @frame.x + x, @frame.y + y beginRead: -> @baseTexture.beginRead() endRead: -> @baseTexture.endRead() ###* Helper function that returns a texture based on an image url If the image is not in the texture cache it will be created and loaded @static @method fromImage @param imageUrl {String} The image url of the texture @param crossorigin {Boolean} Whether requests should be treated as crossorigin @return Texture ### @fromImage: (imageUrl, crossorigin) -> texture = Texture.cache[imageUrl] unless texture texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin)) Texture.cache[imageUrl] = texture texture ###* Helper function that returns a texture based on a frame id If the frame id is not in the texture cache an error will be thrown @static @method fromFrame @param frameId {String} The frame id of the texture @return Texture ### @fromFrame: (frameId) -> texture = Texture.cache[frameId] throw new Error("The frameId '" + frameId + "' does not exist in the texture cache " + this) unless texture texture ###* Helper function that returns a texture based on a canvas element If the canvas is not in the texture cache it will be created and loaded @static @method fromCanvas @param canvas {Canvas} The canvas element source of the texture @return Texture ### @fromCanvas: (canvas) -> baseTexture = new BaseTexture(canvas) new Texture(baseTexture) ###* Adds a texture to the textureCache. @static @method addTextureToCache @param texture {Texture} @param id {String} the id that the texture will be stored against. ### @addTextureToCache: (texture, id) -> Texture.cache[id] = texture ###* Remove a texture from the textureCache. @static @method removeTextureFromCache @param id {String} the id of the texture to be removed @return {Texture} the texture that was removed ### @removeTextureFromCache: (id) -> texture = Texture.cache[id] Texture.cache[id] = null texture
true
###* @author PI:NAME:<NAME>END_PI http://matgroves.com/ @Doormat23 ### define 'Coffixi/textures/Texture', [ 'Coffixi/utils/Module' 'Coffixi/utils/HasSignals' './BaseTexture' 'Coffixi/core/Rectangle' 'Coffixi/core/Point' ], ( Module HasSignals BaseTexture Rectangle Point ) -> ###* A texture stores the information that represents an image or part of an image. It cannot be added to the display list directly. To do this use Sprite. If no frame is provided then the whole image is used @class Texture @extends Module @uses HasSignals @constructor @param baseTexture {BaseTexture} The base texture source to create the texture from @param frmae {Rectangle} The rectangle frame of the texture to show ### class Texture extends Module @mixin HasSignals @cache: {} @frameUpdates: [] constructor: (baseTexture, frame) -> super if not frame @noFrame = true frame = new Rectangle(0, 0, 1, 1) if baseTexture instanceof Texture baseTexture = baseTexture.baseTexture ###* The base texture of this texture @property baseTexture @type BaseTexture ### @baseTexture = baseTexture ###* The frame specifies the region of the base texture that this texture uses @property frame @type Rectangle ### @frame = frame ###* The trim point @property trim @type Point ### @trim = new Point() if baseTexture.hasLoaded frame = new Rectangle(0, 0, baseTexture.width, baseTexture.height) if @noFrame #console.log(frame) @setFrame frame else baseTexture.on 'loaded', => @onBaseTextureLoaded() ###* Called when the base texture is loaded @method onBaseTextureLoaded @param event @private ### onBaseTextureLoaded: (event) -> baseTexture = @baseTexture # baseTexture.off 'loaded', @onLoaded @frame = new Rectangle(0, 0, baseTexture.width, baseTexture.height) if @noFrame @noFrame = false @width = @frame.width @height = @frame.height @emit 'update', @ ###* Destroys this texture @method destroy @param destroyBase {Boolean} Whether to destroy the base texture as well ### destroy: (destroyBase) -> @baseTexture.destroy() if destroyBase ###* Specifies the rectangle region of the baseTexture @method setFrame @param frame {Rectangle} The frame of the texture to set it to ### setFrame: (frame) -> @frame = frame @width = frame.width @height = frame.height if frame.x + frame.width > @baseTexture.width or frame.y + frame.height > @baseTexture.height throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this) @updateFrame = true Texture.frameUpdates.push this getPixel: (x,y) -> @baseTexture.getPixel @frame.x + x, @frame.y + y beginRead: -> @baseTexture.beginRead() endRead: -> @baseTexture.endRead() ###* Helper function that returns a texture based on an image url If the image is not in the texture cache it will be created and loaded @static @method fromImage @param imageUrl {String} The image url of the texture @param crossorigin {Boolean} Whether requests should be treated as crossorigin @return Texture ### @fromImage: (imageUrl, crossorigin) -> texture = Texture.cache[imageUrl] unless texture texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin)) Texture.cache[imageUrl] = texture texture ###* Helper function that returns a texture based on a frame id If the frame id is not in the texture cache an error will be thrown @static @method fromFrame @param frameId {String} The frame id of the texture @return Texture ### @fromFrame: (frameId) -> texture = Texture.cache[frameId] throw new Error("The frameId '" + frameId + "' does not exist in the texture cache " + this) unless texture texture ###* Helper function that returns a texture based on a canvas element If the canvas is not in the texture cache it will be created and loaded @static @method fromCanvas @param canvas {Canvas} The canvas element source of the texture @return Texture ### @fromCanvas: (canvas) -> baseTexture = new BaseTexture(canvas) new Texture(baseTexture) ###* Adds a texture to the textureCache. @static @method addTextureToCache @param texture {Texture} @param id {String} the id that the texture will be stored against. ### @addTextureToCache: (texture, id) -> Texture.cache[id] = texture ###* Remove a texture from the textureCache. @static @method removeTextureFromCache @param id {String} the id of the texture to be removed @return {Texture} the texture that was removed ### @removeTextureFromCache: (id) -> texture = Texture.cache[id] Texture.cache[id] = null texture
[ { "context": "es a `knoxClient`)\n * {@link https://github.com/LearnBoost/knox}\n ###\n constructor: (opts = {}) ->\n {ke", "end": 692, "score": 0.9989902973175049, "start": 682, "tag": "USERNAME", "value": "LearnBoost" }, { "context": "eaders, headers_resource\n aws_content_key = @_imageKey \"#{prefix}#{basename}\", format.suffix, extensi", "end": 8738, "score": 0.7591506838798523, "start": 8731, "tag": "KEY", "value": "@_image" }, { "context": "rce\n aws_content_key = @_imageKey \"#{prefix}#{basename}\", format.suffix, extension\n debug", "end": 8754, "score": 0.8785309791564941, "start": 8752, "tag": "KEY", "value": "#{" } ]
src/coffee/services/s3client.coffee
sphereio/node-s3-utils
4
debug = require('debug')('s3utils-s3client') {EventEmitter} = require('events') _ = require 'underscore' path = require 'path' knox = require 'knox' Lynx = require 'lynx' Promise = require 'bluebird' easyimage = require 'easyimage' Compress = require '../compress' {CustomError} = require '../errors' fs = Promise.promisifyAll require('fs') DEFAULT_IMG_EXTENSION = 'jpg' ###* * An S3Client wrapper that holds some useful methods to talk to S3 ### class S3Client ###* * Creates a new S3Client instance * @constructor * @param {Object} opts A JSON object containing required information * * (internally initializes a `knoxClient`) * {@link https://github.com/LearnBoost/knox} ### constructor: (opts = {}) -> {key, secret, bucket, logger, metrics} = opts throw new CustomError 'Missing AWS \'key\'' unless key throw new CustomError 'Missing AWS \'secret\'' unless secret throw new CustomError 'Missing AWS \'bucket\'' unless bucket @_logger = logger @_ee = new EventEmitter() @_knoxClient = knox.createClient key: key secret: secret bucket: bucket @_knoxClient = Promise.promisifyAll @_knoxClient if metrics?.active @_logger?.info 'StatsD metrics are enabled' @_metricsPrefix = metrics.prefix @_metrics = new Lynx 'localhost', 8125, on_error: -> #noop else @_metrics = undefined on: (eventName, cb) -> @_ee.on eventName, cb emit: (eventName, obj) -> @_ee.emit eventName, obj sendMetrics: (typ, key) -> return unless @_metrics prefix = if @_metricsPrefix then "#{@_metricsPrefix}." else '' switch typ when 'increment' then @_metrics.increment "#{prefix}#{key}" ###* * Lists all files in the given bucket * @param {Object} headers The request headers for AWS (S3) * @return {Promise} A promise, fulfilled with the response or rejected with an error ### list: (headers) -> @sendMetrics 'increment', 'file.list' @_knoxClient.listAsync headers ###* * Lists all files in the given bucket, filtering by an optional regex * @param {Object} headers The request headers for AWS (S3) * @param {String} [regex] A regular expression to filter the returned list * @param {Boolean} [rejectFolders] Whether to reject folders from the returned list (default: true) * @return {Promise} A promise, fulfilled with the filtered list or rejected with an error ### filteredList: (headers, regex, rejectFolders = true) -> @list headers .then (data) -> debug 'listing %s files', data.Contents.length files = _.reject data.Contents, (content) -> if rejectFolders then content.Size is 0 else false if regex # filter files from given regex r = new RegExp regex, 'gi' debug 'using RegExp %s', regex filtered = _.filter files, (content) -> content.Key.match(r) debug 'filtered %s files', filtered.length Promise.resolve(filtered) else debug 'no regex defined, skipping filter' Promise.resolve(files) ###* * Returns a specific file from the given bucket * @param {String} source The path to the remote file (bucket) * @return {Promise} A promise, fulfilled with the response or rejected with an error ### getFile: (source) -> @sendMetrics 'increment', 'file.get' @_knoxClient.getFileAsync source ###* * Uploads a given file to the given bucket, optionally showing the upload progress * @param {String} source The path to the local file to upload * @param {String} target The path to the remote destination file (bucket) * @param {Object} header A JSON object containing some Headers to send * @param {ProgressBar} [progressBar] An optional instance of {ProgressBar} * @return {Promise} A promise, fulfilled with the response or rejected with an error ### putFile: (source, target, header, progressBar) -> new Promise (resolve, reject) => @sendMetrics 'increment', 'file.put' upload = @_knoxClient.putFile source, target, header, (err, resp) -> if err reject err else resolve resp upload.on 'progress', (d) -> progressBar?.update d.written / d.total, total: d.total percent: d.percent ###* * Uploads all files in the given directory to the given bucket, optionally showing the upload progress * @param {String} source The path to the local directory to upload * @param {String} target The path to the remote destination directory (bucket) * @param {Object} header A JSON object containing some Headers to send * @param {ProgressBar} [progressBar] An optional instance of {ProgressBar} * @return {Promise} A promise, fulfilled with the response or rejected with an error ### putDir: (source, target, header, progressBar) -> if fs.statSync(source).isDirectory() debug 'about to upload files in given directory %s', source fs.readdirAsync(source) .then (files) => filesOnly = _.reject files, (file) -> fs.statSync("#{source}/#{file}").isDirectory() totFilesOnly = _.size(filesOnly) if totFilesOnly < _.size(files) debug 'found %s files (only) out of %s total, ignoring directories', totFilesOnly, _.size(files) progressBar?.total = totFilesOnly # override total of ProgressBar with correct value debug 'about to upload %s files', totFilesOnly Promise.map filesOnly, (file) => @putFile "#{source}/#{file}", "#{target}/#{file}", header .then -> progressBar?.tick() Promise.resolve() , {concurrency: 5} else debug 'not a directory, uploading a single file' @putFile source, target, header, progressBar ###* * Copies a file directly in the bucket * @param {String} source The path to the remote source file (bucket) * @param {String} filename The path to the remote destination file (bucket) * @return {Promise} A promise, fulfilled with the response or rejected with an error ### copyFile: (source, destination) -> @sendMetrics 'increment', 'file.copy' @_knoxClient.copyFileAsync source, destination ###* * Moves a given file to the given bucket * @param {String} source The path to the remote source file (bucket) * @param {String} filename The path to the remote destination file (bucket) * @return {Promise} A promise, fulfilled with the response or rejected with an error ### moveFile: (source, destination) -> @copyFile(source, destination).then => @deleteFile source ###* * Deletes a file from the given bucket * @param {String} file The path to the remote file to be deleted (bucket) * @return {Promise} A promise, fulfilled with the response or rejected with an error ### deleteFile: (file) -> @sendMetrics 'increment', 'file.delete' @_knoxClient.deleteFileAsync file ###* * @private * * Builds the correct key as image name * @param {String} prefix A prefix for the image key * @param {String} suffix A suffix for the image key * @param {String} [extension] An optional file extension (default 'jpg') * @return {String} The built image key ### _imageKey: (prefix, suffix, extension) -> "#{prefix}#{suffix}#{extension or DEFAULT_IMG_EXTENSION}" ###* * @private * * Resizes, optionally compress and uploads a given image to the bucket * @param {String} image The path the the image * @param {String} prefix A prefix for the image key * @param {Array} formats A list of formats for image resizing * @param {String} [tmpDir] A path to a tmp folder * @param {Boolean} compress Information if compressing is required * @return {Promise} A promise, fulfilled with the upload response or rejected with an error ### _resizeCompressAndUploadImage: (image, prefix, formats, tmpDir = '/tmp', compress, headers_resource) -> extension = path.extname image basename = path.basename image, extension basename_full = path.basename image tmp_original = "#{tmpDir}/#{basename_full}" Promise.map formats, (format) => tmp_resized = @_imageKey "#{tmpDir}/#{basename}", format.suffix, extension debug 'about to resize image %s to %s', image, tmp_resized easyimage.resize src: tmp_original dst: tmp_resized width: format.width height: format.height .then -> if compress == true Compress.compressImage(tmp_resized, tmpDir, extension) .then => @sendMetrics 'increment', 'image.resized' headers = 'x-amz-acl': 'public-read' headers = _.extend headers, headers_resource aws_content_key = @_imageKey "#{prefix}#{basename}", format.suffix, extension debug 'about to upload resized image to %s', aws_content_key @putFile tmp_resized, aws_content_key, headers .catch (error) => debug 'error while converting / uploading image %s, skipping...', image @_logger?.error 'error while converting / uploading image %s, skipping...', image, error.message Promise.resolve() , {concurrency: 1} # keep it at 1, to avoid concurrency problems related to imagemagick resize jobs ###* * Resizes, optionally compress and uploads a list of images to the bucket * Internally calls {@link _resizeCompressAndUploadImage} * @param {Array} images A list of images to be processed * @param {Object} description A config JSON object describing the images conversion * @param {String} [tmpDir] A path to a tmp folder * @return {Promise} A promise, fulfilled with a successful response or rejected with an error ### resizeCompressAndUploadImages: (images, description, tmpDir = '/tmp') -> Promise.map images, (image) => name = path.basename(image.Key) debug 'about to get image %s', name @sendMetrics 'increment', 'image.count' @getFile(image.Key) .then (response) -> tmp_resized = "#{tmpDir}/#{name}" stream = fs.createWriteStream tmp_resized new Promise (resolve, reject) -> response.pipe stream response.on 'end', resolve response.on 'error', reject .then => @_resizeCompressAndUploadImage image.Key, description.prefix, description.formats, tmpDir, description.compress, description.headers_resource .then (result) => source = "#{description.prefix_unprocessed}/#{name}" target = "#{description.prefix_processed}/#{name}" debug "about to move file %s from '%s' to '%s'", name, source, target @moveFile source, target .then => @emit 'progress' Promise.resolve() , {concurrency: 1} module.exports = S3Client
10462
debug = require('debug')('s3utils-s3client') {EventEmitter} = require('events') _ = require 'underscore' path = require 'path' knox = require 'knox' Lynx = require 'lynx' Promise = require 'bluebird' easyimage = require 'easyimage' Compress = require '../compress' {CustomError} = require '../errors' fs = Promise.promisifyAll require('fs') DEFAULT_IMG_EXTENSION = 'jpg' ###* * An S3Client wrapper that holds some useful methods to talk to S3 ### class S3Client ###* * Creates a new S3Client instance * @constructor * @param {Object} opts A JSON object containing required information * * (internally initializes a `knoxClient`) * {@link https://github.com/LearnBoost/knox} ### constructor: (opts = {}) -> {key, secret, bucket, logger, metrics} = opts throw new CustomError 'Missing AWS \'key\'' unless key throw new CustomError 'Missing AWS \'secret\'' unless secret throw new CustomError 'Missing AWS \'bucket\'' unless bucket @_logger = logger @_ee = new EventEmitter() @_knoxClient = knox.createClient key: key secret: secret bucket: bucket @_knoxClient = Promise.promisifyAll @_knoxClient if metrics?.active @_logger?.info 'StatsD metrics are enabled' @_metricsPrefix = metrics.prefix @_metrics = new Lynx 'localhost', 8125, on_error: -> #noop else @_metrics = undefined on: (eventName, cb) -> @_ee.on eventName, cb emit: (eventName, obj) -> @_ee.emit eventName, obj sendMetrics: (typ, key) -> return unless @_metrics prefix = if @_metricsPrefix then "#{@_metricsPrefix}." else '' switch typ when 'increment' then @_metrics.increment "#{prefix}#{key}" ###* * Lists all files in the given bucket * @param {Object} headers The request headers for AWS (S3) * @return {Promise} A promise, fulfilled with the response or rejected with an error ### list: (headers) -> @sendMetrics 'increment', 'file.list' @_knoxClient.listAsync headers ###* * Lists all files in the given bucket, filtering by an optional regex * @param {Object} headers The request headers for AWS (S3) * @param {String} [regex] A regular expression to filter the returned list * @param {Boolean} [rejectFolders] Whether to reject folders from the returned list (default: true) * @return {Promise} A promise, fulfilled with the filtered list or rejected with an error ### filteredList: (headers, regex, rejectFolders = true) -> @list headers .then (data) -> debug 'listing %s files', data.Contents.length files = _.reject data.Contents, (content) -> if rejectFolders then content.Size is 0 else false if regex # filter files from given regex r = new RegExp regex, 'gi' debug 'using RegExp %s', regex filtered = _.filter files, (content) -> content.Key.match(r) debug 'filtered %s files', filtered.length Promise.resolve(filtered) else debug 'no regex defined, skipping filter' Promise.resolve(files) ###* * Returns a specific file from the given bucket * @param {String} source The path to the remote file (bucket) * @return {Promise} A promise, fulfilled with the response or rejected with an error ### getFile: (source) -> @sendMetrics 'increment', 'file.get' @_knoxClient.getFileAsync source ###* * Uploads a given file to the given bucket, optionally showing the upload progress * @param {String} source The path to the local file to upload * @param {String} target The path to the remote destination file (bucket) * @param {Object} header A JSON object containing some Headers to send * @param {ProgressBar} [progressBar] An optional instance of {ProgressBar} * @return {Promise} A promise, fulfilled with the response or rejected with an error ### putFile: (source, target, header, progressBar) -> new Promise (resolve, reject) => @sendMetrics 'increment', 'file.put' upload = @_knoxClient.putFile source, target, header, (err, resp) -> if err reject err else resolve resp upload.on 'progress', (d) -> progressBar?.update d.written / d.total, total: d.total percent: d.percent ###* * Uploads all files in the given directory to the given bucket, optionally showing the upload progress * @param {String} source The path to the local directory to upload * @param {String} target The path to the remote destination directory (bucket) * @param {Object} header A JSON object containing some Headers to send * @param {ProgressBar} [progressBar] An optional instance of {ProgressBar} * @return {Promise} A promise, fulfilled with the response or rejected with an error ### putDir: (source, target, header, progressBar) -> if fs.statSync(source).isDirectory() debug 'about to upload files in given directory %s', source fs.readdirAsync(source) .then (files) => filesOnly = _.reject files, (file) -> fs.statSync("#{source}/#{file}").isDirectory() totFilesOnly = _.size(filesOnly) if totFilesOnly < _.size(files) debug 'found %s files (only) out of %s total, ignoring directories', totFilesOnly, _.size(files) progressBar?.total = totFilesOnly # override total of ProgressBar with correct value debug 'about to upload %s files', totFilesOnly Promise.map filesOnly, (file) => @putFile "#{source}/#{file}", "#{target}/#{file}", header .then -> progressBar?.tick() Promise.resolve() , {concurrency: 5} else debug 'not a directory, uploading a single file' @putFile source, target, header, progressBar ###* * Copies a file directly in the bucket * @param {String} source The path to the remote source file (bucket) * @param {String} filename The path to the remote destination file (bucket) * @return {Promise} A promise, fulfilled with the response or rejected with an error ### copyFile: (source, destination) -> @sendMetrics 'increment', 'file.copy' @_knoxClient.copyFileAsync source, destination ###* * Moves a given file to the given bucket * @param {String} source The path to the remote source file (bucket) * @param {String} filename The path to the remote destination file (bucket) * @return {Promise} A promise, fulfilled with the response or rejected with an error ### moveFile: (source, destination) -> @copyFile(source, destination).then => @deleteFile source ###* * Deletes a file from the given bucket * @param {String} file The path to the remote file to be deleted (bucket) * @return {Promise} A promise, fulfilled with the response or rejected with an error ### deleteFile: (file) -> @sendMetrics 'increment', 'file.delete' @_knoxClient.deleteFileAsync file ###* * @private * * Builds the correct key as image name * @param {String} prefix A prefix for the image key * @param {String} suffix A suffix for the image key * @param {String} [extension] An optional file extension (default 'jpg') * @return {String} The built image key ### _imageKey: (prefix, suffix, extension) -> "#{prefix}#{suffix}#{extension or DEFAULT_IMG_EXTENSION}" ###* * @private * * Resizes, optionally compress and uploads a given image to the bucket * @param {String} image The path the the image * @param {String} prefix A prefix for the image key * @param {Array} formats A list of formats for image resizing * @param {String} [tmpDir] A path to a tmp folder * @param {Boolean} compress Information if compressing is required * @return {Promise} A promise, fulfilled with the upload response or rejected with an error ### _resizeCompressAndUploadImage: (image, prefix, formats, tmpDir = '/tmp', compress, headers_resource) -> extension = path.extname image basename = path.basename image, extension basename_full = path.basename image tmp_original = "#{tmpDir}/#{basename_full}" Promise.map formats, (format) => tmp_resized = @_imageKey "#{tmpDir}/#{basename}", format.suffix, extension debug 'about to resize image %s to %s', image, tmp_resized easyimage.resize src: tmp_original dst: tmp_resized width: format.width height: format.height .then -> if compress == true Compress.compressImage(tmp_resized, tmpDir, extension) .then => @sendMetrics 'increment', 'image.resized' headers = 'x-amz-acl': 'public-read' headers = _.extend headers, headers_resource aws_content_key = <KEY>Key "#{prefix}<KEY>basename}", format.suffix, extension debug 'about to upload resized image to %s', aws_content_key @putFile tmp_resized, aws_content_key, headers .catch (error) => debug 'error while converting / uploading image %s, skipping...', image @_logger?.error 'error while converting / uploading image %s, skipping...', image, error.message Promise.resolve() , {concurrency: 1} # keep it at 1, to avoid concurrency problems related to imagemagick resize jobs ###* * Resizes, optionally compress and uploads a list of images to the bucket * Internally calls {@link _resizeCompressAndUploadImage} * @param {Array} images A list of images to be processed * @param {Object} description A config JSON object describing the images conversion * @param {String} [tmpDir] A path to a tmp folder * @return {Promise} A promise, fulfilled with a successful response or rejected with an error ### resizeCompressAndUploadImages: (images, description, tmpDir = '/tmp') -> Promise.map images, (image) => name = path.basename(image.Key) debug 'about to get image %s', name @sendMetrics 'increment', 'image.count' @getFile(image.Key) .then (response) -> tmp_resized = "#{tmpDir}/#{name}" stream = fs.createWriteStream tmp_resized new Promise (resolve, reject) -> response.pipe stream response.on 'end', resolve response.on 'error', reject .then => @_resizeCompressAndUploadImage image.Key, description.prefix, description.formats, tmpDir, description.compress, description.headers_resource .then (result) => source = "#{description.prefix_unprocessed}/#{name}" target = "#{description.prefix_processed}/#{name}" debug "about to move file %s from '%s' to '%s'", name, source, target @moveFile source, target .then => @emit 'progress' Promise.resolve() , {concurrency: 1} module.exports = S3Client
true
debug = require('debug')('s3utils-s3client') {EventEmitter} = require('events') _ = require 'underscore' path = require 'path' knox = require 'knox' Lynx = require 'lynx' Promise = require 'bluebird' easyimage = require 'easyimage' Compress = require '../compress' {CustomError} = require '../errors' fs = Promise.promisifyAll require('fs') DEFAULT_IMG_EXTENSION = 'jpg' ###* * An S3Client wrapper that holds some useful methods to talk to S3 ### class S3Client ###* * Creates a new S3Client instance * @constructor * @param {Object} opts A JSON object containing required information * * (internally initializes a `knoxClient`) * {@link https://github.com/LearnBoost/knox} ### constructor: (opts = {}) -> {key, secret, bucket, logger, metrics} = opts throw new CustomError 'Missing AWS \'key\'' unless key throw new CustomError 'Missing AWS \'secret\'' unless secret throw new CustomError 'Missing AWS \'bucket\'' unless bucket @_logger = logger @_ee = new EventEmitter() @_knoxClient = knox.createClient key: key secret: secret bucket: bucket @_knoxClient = Promise.promisifyAll @_knoxClient if metrics?.active @_logger?.info 'StatsD metrics are enabled' @_metricsPrefix = metrics.prefix @_metrics = new Lynx 'localhost', 8125, on_error: -> #noop else @_metrics = undefined on: (eventName, cb) -> @_ee.on eventName, cb emit: (eventName, obj) -> @_ee.emit eventName, obj sendMetrics: (typ, key) -> return unless @_metrics prefix = if @_metricsPrefix then "#{@_metricsPrefix}." else '' switch typ when 'increment' then @_metrics.increment "#{prefix}#{key}" ###* * Lists all files in the given bucket * @param {Object} headers The request headers for AWS (S3) * @return {Promise} A promise, fulfilled with the response or rejected with an error ### list: (headers) -> @sendMetrics 'increment', 'file.list' @_knoxClient.listAsync headers ###* * Lists all files in the given bucket, filtering by an optional regex * @param {Object} headers The request headers for AWS (S3) * @param {String} [regex] A regular expression to filter the returned list * @param {Boolean} [rejectFolders] Whether to reject folders from the returned list (default: true) * @return {Promise} A promise, fulfilled with the filtered list or rejected with an error ### filteredList: (headers, regex, rejectFolders = true) -> @list headers .then (data) -> debug 'listing %s files', data.Contents.length files = _.reject data.Contents, (content) -> if rejectFolders then content.Size is 0 else false if regex # filter files from given regex r = new RegExp regex, 'gi' debug 'using RegExp %s', regex filtered = _.filter files, (content) -> content.Key.match(r) debug 'filtered %s files', filtered.length Promise.resolve(filtered) else debug 'no regex defined, skipping filter' Promise.resolve(files) ###* * Returns a specific file from the given bucket * @param {String} source The path to the remote file (bucket) * @return {Promise} A promise, fulfilled with the response or rejected with an error ### getFile: (source) -> @sendMetrics 'increment', 'file.get' @_knoxClient.getFileAsync source ###* * Uploads a given file to the given bucket, optionally showing the upload progress * @param {String} source The path to the local file to upload * @param {String} target The path to the remote destination file (bucket) * @param {Object} header A JSON object containing some Headers to send * @param {ProgressBar} [progressBar] An optional instance of {ProgressBar} * @return {Promise} A promise, fulfilled with the response or rejected with an error ### putFile: (source, target, header, progressBar) -> new Promise (resolve, reject) => @sendMetrics 'increment', 'file.put' upload = @_knoxClient.putFile source, target, header, (err, resp) -> if err reject err else resolve resp upload.on 'progress', (d) -> progressBar?.update d.written / d.total, total: d.total percent: d.percent ###* * Uploads all files in the given directory to the given bucket, optionally showing the upload progress * @param {String} source The path to the local directory to upload * @param {String} target The path to the remote destination directory (bucket) * @param {Object} header A JSON object containing some Headers to send * @param {ProgressBar} [progressBar] An optional instance of {ProgressBar} * @return {Promise} A promise, fulfilled with the response or rejected with an error ### putDir: (source, target, header, progressBar) -> if fs.statSync(source).isDirectory() debug 'about to upload files in given directory %s', source fs.readdirAsync(source) .then (files) => filesOnly = _.reject files, (file) -> fs.statSync("#{source}/#{file}").isDirectory() totFilesOnly = _.size(filesOnly) if totFilesOnly < _.size(files) debug 'found %s files (only) out of %s total, ignoring directories', totFilesOnly, _.size(files) progressBar?.total = totFilesOnly # override total of ProgressBar with correct value debug 'about to upload %s files', totFilesOnly Promise.map filesOnly, (file) => @putFile "#{source}/#{file}", "#{target}/#{file}", header .then -> progressBar?.tick() Promise.resolve() , {concurrency: 5} else debug 'not a directory, uploading a single file' @putFile source, target, header, progressBar ###* * Copies a file directly in the bucket * @param {String} source The path to the remote source file (bucket) * @param {String} filename The path to the remote destination file (bucket) * @return {Promise} A promise, fulfilled with the response or rejected with an error ### copyFile: (source, destination) -> @sendMetrics 'increment', 'file.copy' @_knoxClient.copyFileAsync source, destination ###* * Moves a given file to the given bucket * @param {String} source The path to the remote source file (bucket) * @param {String} filename The path to the remote destination file (bucket) * @return {Promise} A promise, fulfilled with the response or rejected with an error ### moveFile: (source, destination) -> @copyFile(source, destination).then => @deleteFile source ###* * Deletes a file from the given bucket * @param {String} file The path to the remote file to be deleted (bucket) * @return {Promise} A promise, fulfilled with the response or rejected with an error ### deleteFile: (file) -> @sendMetrics 'increment', 'file.delete' @_knoxClient.deleteFileAsync file ###* * @private * * Builds the correct key as image name * @param {String} prefix A prefix for the image key * @param {String} suffix A suffix for the image key * @param {String} [extension] An optional file extension (default 'jpg') * @return {String} The built image key ### _imageKey: (prefix, suffix, extension) -> "#{prefix}#{suffix}#{extension or DEFAULT_IMG_EXTENSION}" ###* * @private * * Resizes, optionally compress and uploads a given image to the bucket * @param {String} image The path the the image * @param {String} prefix A prefix for the image key * @param {Array} formats A list of formats for image resizing * @param {String} [tmpDir] A path to a tmp folder * @param {Boolean} compress Information if compressing is required * @return {Promise} A promise, fulfilled with the upload response or rejected with an error ### _resizeCompressAndUploadImage: (image, prefix, formats, tmpDir = '/tmp', compress, headers_resource) -> extension = path.extname image basename = path.basename image, extension basename_full = path.basename image tmp_original = "#{tmpDir}/#{basename_full}" Promise.map formats, (format) => tmp_resized = @_imageKey "#{tmpDir}/#{basename}", format.suffix, extension debug 'about to resize image %s to %s', image, tmp_resized easyimage.resize src: tmp_original dst: tmp_resized width: format.width height: format.height .then -> if compress == true Compress.compressImage(tmp_resized, tmpDir, extension) .then => @sendMetrics 'increment', 'image.resized' headers = 'x-amz-acl': 'public-read' headers = _.extend headers, headers_resource aws_content_key = PI:KEY:<KEY>END_PIKey "#{prefix}PI:KEY:<KEY>END_PIbasename}", format.suffix, extension debug 'about to upload resized image to %s', aws_content_key @putFile tmp_resized, aws_content_key, headers .catch (error) => debug 'error while converting / uploading image %s, skipping...', image @_logger?.error 'error while converting / uploading image %s, skipping...', image, error.message Promise.resolve() , {concurrency: 1} # keep it at 1, to avoid concurrency problems related to imagemagick resize jobs ###* * Resizes, optionally compress and uploads a list of images to the bucket * Internally calls {@link _resizeCompressAndUploadImage} * @param {Array} images A list of images to be processed * @param {Object} description A config JSON object describing the images conversion * @param {String} [tmpDir] A path to a tmp folder * @return {Promise} A promise, fulfilled with a successful response or rejected with an error ### resizeCompressAndUploadImages: (images, description, tmpDir = '/tmp') -> Promise.map images, (image) => name = path.basename(image.Key) debug 'about to get image %s', name @sendMetrics 'increment', 'image.count' @getFile(image.Key) .then (response) -> tmp_resized = "#{tmpDir}/#{name}" stream = fs.createWriteStream tmp_resized new Promise (resolve, reject) -> response.pipe stream response.on 'end', resolve response.on 'error', reject .then => @_resizeCompressAndUploadImage image.Key, description.prefix, description.formats, tmpDir, description.compress, description.headers_resource .then (result) => source = "#{description.prefix_unprocessed}/#{name}" target = "#{description.prefix_processed}/#{name}" debug "about to move file %s from '%s' to '%s'", name, source, target @moveFile source, target .then => @emit 'progress' Promise.resolve() , {concurrency: 1} module.exports = S3Client
[ { "context": ",\n\t\trecord: taskRecord\n\t\t#cls: 'story'\n\t\t#title: 'Hello',\n\t\t#html: taskRecord.data.Name,\n\t\t#height: 50,\n\t", "end": 180, "score": 0.9268162250518799, "start": 175, "tag": "NAME", "value": "Hello" }, { "context": "lex: 1,\n\t\titems: [{\n\t\t\txtype: 'panel',\n\t\t\ttitle: 'Hello',\n\t\t\thtml: story.data.Name,\n\t\t\theight: 50\n\t\t}]\n\t}", "end": 620, "score": 0.8985962271690369, "start": 615, "tag": "NAME", "value": "Hello" } ]
src/app.coffee
RallyHackathon/Task-Board-Redux
0
###global Ext, Rally### "use strict" require('./RowCardBoard') createCard = (taskRecord) -> { xtype: 'rallyartifactcard', record: taskRecord #cls: 'story' #title: 'Hello', #html: taskRecord.data.Name, #height: 50, #draggable: true } createRow = (story, taskRecords) -> items = [] cols = [] ret = { xtype: 'panel', layout: { type: 'hbox' align: 'stretch' }, height: 0, items: cols } cols.push { xtype: 'panel', #height: 100, width: 200, cls: 'cardContainer', layout: { type: 'vbox', align: 'stretch' }, flex: 1, items: [{ xtype: 'panel', title: 'Hello', html: story.data.Name, height: 50 }] } states = { "Defined": [], "In-Progress": [], "Completed": [] } states[rec.data.State].push(rec) for rec in taskRecords for i in ["Defined", "In-Progress", "Completed"] items = [] cols.push { xtype: 'panel', #height: 100, width: 200, layout: { type: 'vbox', align: 'stretch' }, listeners: { render: () -> } flex: 1, items: items } items.push(createCard(task)) for task in states[i] ret.height = items.length * 55 if items.length * 55 > ret.height return ret Ext.define 'rally.TaskBoardRedux', extend: 'Rally.app.App' layout: { type: 'fit' }, ### autoScroll: true, scroll: false, viewConfig: { style: { overflow: 'auto', overflowX: 'hidden' } }, ### launch: () -> @taskStore = Ext.create 'Rally.data.WsapiDataStore', { model: 'Task', fetch: true, autoLoad: false, filters: [ { property: 'Iteration.State', operator: '=', value: 'Committed' } ] } @storyStore = Ext.create 'Rally.data.WsapiDataStore', { model: 'Story', fetch: true, autoLoad: false, filters: [ { property: 'Iteration.State', operator: '=', value: 'Committed' } ] } @storyStore.load((storyRecords) => @taskStore.load((taskRecords) => rows = [] storiesTaskMap = {} for rec in storyRecords storiesTaskMap[rec.data._ref] ?= [] for rec in taskRecords storiesTaskMap[rec.data.WorkProduct._ref]?.push(rec) console.log storiesTaskMap for rec in storyRecords rows.push(createRow(rec, storiesTaskMap[rec.data._ref])) @add { xtype: 'panel', scroll: false, cls: 'cardboard', defaults: { viewConfig: { style: { overflow: 'auto', overflowX: 'hidden' } }, frame: true }, layout: { type: 'vbox', align: 'stretch', pack: 'start' }, items: rows } # Take that Ext scrolling Ext.query(".x-box-inner")?[0]?.style.overflow = "auto" ) ) Rally.launchApp 'rally.TaskBoardRedux', { name: 'Task Board Redux' }
140770
###global Ext, Rally### "use strict" require('./RowCardBoard') createCard = (taskRecord) -> { xtype: 'rallyartifactcard', record: taskRecord #cls: 'story' #title: '<NAME>', #html: taskRecord.data.Name, #height: 50, #draggable: true } createRow = (story, taskRecords) -> items = [] cols = [] ret = { xtype: 'panel', layout: { type: 'hbox' align: 'stretch' }, height: 0, items: cols } cols.push { xtype: 'panel', #height: 100, width: 200, cls: 'cardContainer', layout: { type: 'vbox', align: 'stretch' }, flex: 1, items: [{ xtype: 'panel', title: '<NAME>', html: story.data.Name, height: 50 }] } states = { "Defined": [], "In-Progress": [], "Completed": [] } states[rec.data.State].push(rec) for rec in taskRecords for i in ["Defined", "In-Progress", "Completed"] items = [] cols.push { xtype: 'panel', #height: 100, width: 200, layout: { type: 'vbox', align: 'stretch' }, listeners: { render: () -> } flex: 1, items: items } items.push(createCard(task)) for task in states[i] ret.height = items.length * 55 if items.length * 55 > ret.height return ret Ext.define 'rally.TaskBoardRedux', extend: 'Rally.app.App' layout: { type: 'fit' }, ### autoScroll: true, scroll: false, viewConfig: { style: { overflow: 'auto', overflowX: 'hidden' } }, ### launch: () -> @taskStore = Ext.create 'Rally.data.WsapiDataStore', { model: 'Task', fetch: true, autoLoad: false, filters: [ { property: 'Iteration.State', operator: '=', value: 'Committed' } ] } @storyStore = Ext.create 'Rally.data.WsapiDataStore', { model: 'Story', fetch: true, autoLoad: false, filters: [ { property: 'Iteration.State', operator: '=', value: 'Committed' } ] } @storyStore.load((storyRecords) => @taskStore.load((taskRecords) => rows = [] storiesTaskMap = {} for rec in storyRecords storiesTaskMap[rec.data._ref] ?= [] for rec in taskRecords storiesTaskMap[rec.data.WorkProduct._ref]?.push(rec) console.log storiesTaskMap for rec in storyRecords rows.push(createRow(rec, storiesTaskMap[rec.data._ref])) @add { xtype: 'panel', scroll: false, cls: 'cardboard', defaults: { viewConfig: { style: { overflow: 'auto', overflowX: 'hidden' } }, frame: true }, layout: { type: 'vbox', align: 'stretch', pack: 'start' }, items: rows } # Take that Ext scrolling Ext.query(".x-box-inner")?[0]?.style.overflow = "auto" ) ) Rally.launchApp 'rally.TaskBoardRedux', { name: 'Task Board Redux' }
true
###global Ext, Rally### "use strict" require('./RowCardBoard') createCard = (taskRecord) -> { xtype: 'rallyartifactcard', record: taskRecord #cls: 'story' #title: 'PI:NAME:<NAME>END_PI', #html: taskRecord.data.Name, #height: 50, #draggable: true } createRow = (story, taskRecords) -> items = [] cols = [] ret = { xtype: 'panel', layout: { type: 'hbox' align: 'stretch' }, height: 0, items: cols } cols.push { xtype: 'panel', #height: 100, width: 200, cls: 'cardContainer', layout: { type: 'vbox', align: 'stretch' }, flex: 1, items: [{ xtype: 'panel', title: 'PI:NAME:<NAME>END_PI', html: story.data.Name, height: 50 }] } states = { "Defined": [], "In-Progress": [], "Completed": [] } states[rec.data.State].push(rec) for rec in taskRecords for i in ["Defined", "In-Progress", "Completed"] items = [] cols.push { xtype: 'panel', #height: 100, width: 200, layout: { type: 'vbox', align: 'stretch' }, listeners: { render: () -> } flex: 1, items: items } items.push(createCard(task)) for task in states[i] ret.height = items.length * 55 if items.length * 55 > ret.height return ret Ext.define 'rally.TaskBoardRedux', extend: 'Rally.app.App' layout: { type: 'fit' }, ### autoScroll: true, scroll: false, viewConfig: { style: { overflow: 'auto', overflowX: 'hidden' } }, ### launch: () -> @taskStore = Ext.create 'Rally.data.WsapiDataStore', { model: 'Task', fetch: true, autoLoad: false, filters: [ { property: 'Iteration.State', operator: '=', value: 'Committed' } ] } @storyStore = Ext.create 'Rally.data.WsapiDataStore', { model: 'Story', fetch: true, autoLoad: false, filters: [ { property: 'Iteration.State', operator: '=', value: 'Committed' } ] } @storyStore.load((storyRecords) => @taskStore.load((taskRecords) => rows = [] storiesTaskMap = {} for rec in storyRecords storiesTaskMap[rec.data._ref] ?= [] for rec in taskRecords storiesTaskMap[rec.data.WorkProduct._ref]?.push(rec) console.log storiesTaskMap for rec in storyRecords rows.push(createRow(rec, storiesTaskMap[rec.data._ref])) @add { xtype: 'panel', scroll: false, cls: 'cardboard', defaults: { viewConfig: { style: { overflow: 'auto', overflowX: 'hidden' } }, frame: true }, layout: { type: 'vbox', align: 'stretch', pack: 'start' }, items: rows } # Take that Ext scrolling Ext.query(".x-box-inner")?[0]?.style.overflow = "auto" ) ) Rally.launchApp 'rally.TaskBoardRedux', { name: 'Task Board Redux' }
[ { "context": "###\nCopyright (c) 2002-2013 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n", "end": 43, "score": 0.7075113654136658, "start": 33, "tag": "NAME", "value": "Technology" } ]
community/server/src/main/coffeescript/neo4j/webadmin/modules/databrowser/visualization/RelationshipStyler.coffee
rebaze/neo4j
1
### Copyright (c) 2002-2013 "Neo Technology," Network Engine for Objects in Lund AB [http://neotechnology.com] This file is part of Neo4j. Neo4j is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ### define( [], () -> class RelationshipStyler defaultBetweenExploredStyle : edgeStyle : color : "rgba(0, 0, 0, 1)" width : 1 labelStyle : color : "rgba(0, 0, 0, 1)" font : "10px Helvetica" defaultToUnknownStyle : edgeStyle : color : "rgba(0, 0, 0, 0.2)" width : 1 labelStyle : color : "rgba(0, 0, 0, 0.4)" font : "10px Helvetica" defaultToGroupStyle : edgeStyle : color : "rgba(0, 0, 0, 0.8)" width : 1 labelStyle : color : "rgba(0, 0, 0, 0.8)" font : "10px Helvetica" getStyleFor : (visualRelationship) -> srcType = visualRelationship.source.data.type dstType = visualRelationship.target.data.type if visualRelationship.target.data.relType != null types = for url, rel of visualRelationship.data.relationships rel.getType() types = _.uniq(types) labelText = types.join(", ") if srcType is "explored" and dstType is "explored" return { edgeStyle : @defaultBetweenExploredStyle.edgeStyle, labelStyle : @defaultBetweenExploredStyle.labelStyle, labelText : labelText } if srcType is "unexplored" or dstType is "unexplored" return { edgeStyle : @defaultToUnknownStyle.edgeStyle, labelStyle : @defaultToUnknownStyle.labelStyle, labelText : labelText } return { edgeStyle : @defaultToGroupStyle.edgeStyle, labelStyle : @defaultToGroupStyle.labelStyle, labelText : visualRelationship.data.relType } )
214736
### Copyright (c) 2002-2013 "Neo <NAME>," Network Engine for Objects in Lund AB [http://neotechnology.com] This file is part of Neo4j. Neo4j is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ### define( [], () -> class RelationshipStyler defaultBetweenExploredStyle : edgeStyle : color : "rgba(0, 0, 0, 1)" width : 1 labelStyle : color : "rgba(0, 0, 0, 1)" font : "10px Helvetica" defaultToUnknownStyle : edgeStyle : color : "rgba(0, 0, 0, 0.2)" width : 1 labelStyle : color : "rgba(0, 0, 0, 0.4)" font : "10px Helvetica" defaultToGroupStyle : edgeStyle : color : "rgba(0, 0, 0, 0.8)" width : 1 labelStyle : color : "rgba(0, 0, 0, 0.8)" font : "10px Helvetica" getStyleFor : (visualRelationship) -> srcType = visualRelationship.source.data.type dstType = visualRelationship.target.data.type if visualRelationship.target.data.relType != null types = for url, rel of visualRelationship.data.relationships rel.getType() types = _.uniq(types) labelText = types.join(", ") if srcType is "explored" and dstType is "explored" return { edgeStyle : @defaultBetweenExploredStyle.edgeStyle, labelStyle : @defaultBetweenExploredStyle.labelStyle, labelText : labelText } if srcType is "unexplored" or dstType is "unexplored" return { edgeStyle : @defaultToUnknownStyle.edgeStyle, labelStyle : @defaultToUnknownStyle.labelStyle, labelText : labelText } return { edgeStyle : @defaultToGroupStyle.edgeStyle, labelStyle : @defaultToGroupStyle.labelStyle, labelText : visualRelationship.data.relType } )
true
### Copyright (c) 2002-2013 "Neo PI:NAME:<NAME>END_PI," Network Engine for Objects in Lund AB [http://neotechnology.com] This file is part of Neo4j. Neo4j is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ### define( [], () -> class RelationshipStyler defaultBetweenExploredStyle : edgeStyle : color : "rgba(0, 0, 0, 1)" width : 1 labelStyle : color : "rgba(0, 0, 0, 1)" font : "10px Helvetica" defaultToUnknownStyle : edgeStyle : color : "rgba(0, 0, 0, 0.2)" width : 1 labelStyle : color : "rgba(0, 0, 0, 0.4)" font : "10px Helvetica" defaultToGroupStyle : edgeStyle : color : "rgba(0, 0, 0, 0.8)" width : 1 labelStyle : color : "rgba(0, 0, 0, 0.8)" font : "10px Helvetica" getStyleFor : (visualRelationship) -> srcType = visualRelationship.source.data.type dstType = visualRelationship.target.data.type if visualRelationship.target.data.relType != null types = for url, rel of visualRelationship.data.relationships rel.getType() types = _.uniq(types) labelText = types.join(", ") if srcType is "explored" and dstType is "explored" return { edgeStyle : @defaultBetweenExploredStyle.edgeStyle, labelStyle : @defaultBetweenExploredStyle.labelStyle, labelText : labelText } if srcType is "unexplored" or dstType is "unexplored" return { edgeStyle : @defaultToUnknownStyle.edgeStyle, labelStyle : @defaultToUnknownStyle.labelStyle, labelText : labelText } return { edgeStyle : @defaultToGroupStyle.edgeStyle, labelStyle : @defaultToGroupStyle.labelStyle, labelText : visualRelationship.data.relType } )
[ { "context": "result.find_citation = API.service.oab.find url: 'Nusch, C., & Percivale, B. (2016). El Bicentenario argentino", "end": 462, "score": 0.9911146759986877, "start": 454, "tag": "NAME", "value": "Nusch, C" }, { "context": "citation = API.service.oab.find url: 'Nusch, C., & Percivale, B. (2016). El Bicentenario argentino como territori", "end": 479, "score": 0.9993322491645813, "start": 467, "tag": "NAME", "value": "Percivale, B" }, { "context": " () ->\n result.dnr = API.service.oab.dnr 'test@test.com', true\n future = new Future()\n Meteor.s", "end": 5507, "score": 0.9999256134033203, "start": 5494, "tag": "EMAIL", "value": "test@test.com" }, { "context": ".wait()\n result.ondnr = API.service.oab.dnr 'test@test.com'\n oab_dnr.remove {email: 'test@test.com'}\n ", "end": 5671, "score": 0.9999265670776367, "start": 5658, "tag": "EMAIL", "value": "test@test.com" }, { "context": "dnr 'test@test.com'\n oab_dnr.remove {email: 'test@test.com'}\n return result.ondnr is true\n () ->\n ", "end": 5716, "score": 0.9999271631240845, "start": 5703, "tag": "EMAIL", "value": "test@test.com" }, { "context": "tists\",\n \"author\": [\n {\n \"given\": \"Kerry\",\n \"family\": \"Holden\",\n \"affiliatio", "end": 7760, "score": 0.9997395277023315, "start": 7755, "tag": "NAME", "value": "Kerry" }, { "context": " {\n \"given\": \"Kerry\",\n \"family\": \"Holden\",\n \"affiliation\": []\n }\n ],\n \"j", "end": 7788, "score": 0.9996265172958374, "start": 7782, "tag": "NAME", "value": "Holden" }, { "context": " \"scientific labour\"\n ],\n \"email\": [\n \"k.holden@qmul.ac.uk\"\n ]\n },\n request: {\n \"url\": \"https://jche", "end": 8355, "score": 0.999933660030365, "start": 8336, "tag": "EMAIL", "value": "k.holden@qmul.ac.uk" }, { "context": "-3-47\",\n \"author\": [\n {\n \"given\": \"Richard\",\n \"family\": \"Jones\",\n \"affiliation", "end": 8696, "score": 0.9995776414871216, "start": 8689, "tag": "NAME", "value": "Richard" }, { "context": " {\n \"given\": \"Richard\",\n \"family\": \"Jones\",\n \"affiliation\": []\n },\n {\n ", "end": 8723, "score": 0.9995447397232056, "start": 8718, "tag": "NAME", "value": "Jones" }, { "context": "filiation\": []\n },\n {\n \"given\": \"Mark\",\n \"family\": \"MacGillivray\",\n \"affi", "end": 8791, "score": 0.9998469352722168, "start": 8787, "tag": "NAME", "value": "Mark" }, { "context": " {\n \"given\": \"Mark\",\n \"family\": \"MacGillivray\",\n \"affiliation\": []\n },\n {\n ", "end": 8825, "score": 0.8843101263046265, "start": 8813, "tag": "NAME", "value": "MacGillivray" }, { "context": "filiation\": []\n },\n {\n \"given\": \"Peter\",\n \"family\": \"Murray-Rust\",\n \"affil", "end": 8894, "score": 0.9995940923690796, "start": 8889, "tag": "NAME", "value": "Peter" }, { "context": " {\n \"given\": \"Peter\",\n \"family\": \"Murray-Rust\",\n \"affiliation\": []\n },\n {\n ", "end": 8927, "score": 0.9969764947891235, "start": 8916, "tag": "NAME", "value": "Murray-Rust" }, { "context": "filiation\": []\n },\n {\n \"given\": \"Jim\",\n \"family\": \"Pitman\",\n \"affiliatio", "end": 8994, "score": 0.9998308420181274, "start": 8991, "tag": "NAME", "value": "Jim" }, { "context": " {\n \"given\": \"Jim\",\n \"family\": \"Pitman\",\n \"affiliation\": []\n },\n {\n ", "end": 9022, "score": 0.9986355900764465, "start": 9016, "tag": "NAME", "value": "Pitman" }, { "context": "filiation\": []\n },\n {\n \"given\": \"Peter\",\n \"family\": \"Sefton\",\n \"affiliatio", "end": 9091, "score": 0.9994169473648071, "start": 9086, "tag": "NAME", "value": "Peter" }, { "context": " {\n \"given\": \"Peter\",\n \"family\": \"Sefton\",\n \"affiliation\": []\n },\n {\n ", "end": 9119, "score": 0.9690673351287842, "start": 9113, "tag": "NAME", "value": "Sefton" }, { "context": "filiation\": []\n },\n {\n \"given\": \"Ben\",\n \"family\": \"O'Steen\",\n \"affiliati", "end": 9186, "score": 0.9998347759246826, "start": 9183, "tag": "NAME", "value": "Ben" }, { "context": " {\n \"given\": \"Ben\",\n \"family\": \"O'Steen\",\n \"affiliation\": []\n },\n {\n ", "end": 9215, "score": 0.9097056984901428, "start": 9208, "tag": "NAME", "value": "O'Steen" }, { "context": "filiation\": []\n },\n {\n \"given\": \"William\",\n \"family\": \"Waites\",\n \"affiliatio", "end": 9286, "score": 0.9994158744812012, "start": 9279, "tag": "NAME", "value": "William" }, { "context": " {\n \"given\": \"William\",\n \"family\": \"Waites\",\n \"affiliation\": []\n }\n ],\n \"j", "end": 9314, "score": 0.9981272220611572, "start": 9308, "tag": "NAME", "value": "Waites" } ]
noddy/service/oabutton/test.coffee
jibe-b/website
0
import Future from 'fibers/future' API.add 'service/oab/test', get: roleRequired: if API.settings.dev then undefined else 'root' action: () -> return API.service.oab.test(this.queryParams.verbose) API.service.oab.test = (verbose) -> result = {passed:[],failed:[]} oab_request.remove url: 'https://jcheminf.springeropen.com/articles/10.1186/1758-2946-3-47' tests = [ () -> result.find_citation = API.service.oab.find url: 'Nusch, C., & Percivale, B. (2016). El Bicentenario argentino como territorio en disputa. Analecta política, 6(10).', refresh: 0 return result.find_citation.match is "https://doi.org/10.18566/apolit.v6n10.a04" and result.find_citation.availability?[0]?.url is "https://revistas.upb.edu.co/index.php/analecta/article/download/6166/5658" and result.find_citation.meta.article.source is "oadoi" () -> result.find_title = API.service.oab.find url: 'Effect of Saxagliptin on Renal Outcomes in the SAVOR-TIMI 53 Trial', refresh: 0 return result.find_title.match is "https://doi.org/10.2337/dc16-0621" and result.find_title.availability?[0]?.url is "https://spiral.imperial.ac.uk:8443/bitstream/10044/1/42241/4/Effect%20of%20Saxagliptin%20on%20Renal%20Outcomes%20in%20the%20SAVOR%20trial%20clean%20final%201....pdf" and result.find_title.meta.article.source is "oadoi" () -> result.find_url = API.service.oab.find url: 'http://journals.sagepub.com/doi/abs/10.1177/0037549715583150', refresh: 0 return result.find_url.match is "http://journals.sagepub.com/doi/abs/10.1177/0037549715583150" and result.find_url.availability?[0]?.url is "http://journals.sagepub.com/doi/pdf/10.1177/0037549715583150" and result.find_url.meta.article.source is "oadoi" () -> result.find_pmid = API.service.oab.find url: '27353853', refresh: 0 return result.find_pmid.match is "https://www.ncbi.nlm.nih.gov/pubmed/27353853" and result.find_pmid.availability?[0]?.url is "http://circimaging.ahajournals.org/content/circcvim/9/7/e005150.full.pdf" and result.find_pmid.meta.article.source is "oadoi" () -> result.find_pmc = API.service.oab.find url: 'PMC3220411', refresh: 0 return result.find_pmc.match is "http://europepmc.org/articles/PMC3220411" and result.find_pmc.availability?[0]?.url is "http://europepmc.org/articles/PMC3220411?pdf=render" and result.find_pmc.meta.article.source is "eupmc" () -> result.find_doi = API.service.oab.find url: '10.1145/2908080.2908114', refresh: 0 return result.find_doi.match is "https://doi.org/10.1145/2908080.2908114" and result.find_doi.availability?[0]?.url is "http://spiral.imperial.ac.uk/bitstream/10044/1/31580/2/paper.pdf" and result.find_doi.meta.article.source is "oadoi" () -> result.closed = API.service.oab.find url: 'http://www.tandfonline.com/doi/abs/10.1080/09505431.2014.928678', refresh: 0 return result.closed.match is "http://www.tandfonline.com/doi/abs/10.1080/09505431.2014.928678" and result.closed.availability.length is 0 and not result.closed.meta.article.source? and result.closed.meta.article.doi is "10.1080/09505431.2014.928678" () -> result.resolve = API.service.oab.resolve 'http://www.sciencedirect.com/science/article/pii/S0735109712600734', undefined, undefined, true return _.isEqual result.resolve, API.service.oab.test._examples.resolve () -> result.redirect_false = API.service.oab.redirect 'https://www.researchgate.net/anything' return result.redirect_false is false () -> result.redirect_fulltext = API.service.oab.redirect 'https://arxiv.org/abs/1711.07985' return result.redirect_fulltext is 'https://arxiv.org/pdf/1711.07985.pdf' () -> result.redirect_element = API.service.oab.redirect 'http://nora.nerc.ac.uk/518502' return result.redirect_element is 'http://nora.nerc.ac.uk/518502/1/N518502CR.pdf' () -> result.scrape = API.service.oab.scrape 'http://www.tandfonline.com/doi/abs/10.1080/09505431.2014.928678' return _.isEqual result.scrape, API.service.oab.test._examples.scrape () -> result.request = API.service.oab.request url: 'https://jcheminf.springeropen.com/articles/10.1186/1758-2946-3-47', test: true ck = JSON.parse(JSON.stringify(result.request)) delete ck.receiver delete ck._id return _.isEqual ck, API.service.oab.test._examples.request () -> result.support = API.service.oab.support result.request._id, "I am the test story", "0" future = new Future() Meteor.setTimeout (() -> future.return()), 999 future.wait() result.supports = API.service.oab.supports result.request._id, "0" oab_support.remove result.support._id return result.supports?.rid is result.request._id and result.supports?.story is "I am the test story" and result.supports?.uid is "0" () -> result.hold = API.service.oab.hold result.request._id, 7 result.held = oab_request.get result.request._id return result.held.status is 'hold' and result.held.holds? and result.held.hold?.until? () -> result.refuse = API.service.oab.refuse result.request._id, "Test reason" result.refused = oab_request.get result.request._id oab_request.remove result.request._id return result.refused.status is 'refused' and not result.refused.email? and not result.refused.hold? and result.refused.refused? and result.refused.refused[0].reason is "Test reason" () -> result.dnr = API.service.oab.dnr 'test@test.com', true future = new Future() Meteor.setTimeout (() -> future.return()), 999 future.wait() result.ondnr = API.service.oab.dnr 'test@test.com' oab_dnr.remove {email: 'test@test.com'} return result.ondnr is true () -> result.vars = API.service.oab.vars {user: {id:"0"}} return result.vars.userid is "0" and result.vars.profession? and result.vars.fullname? ] # TODO need to add tests for ill once we start developing that again (if (try tests[t]()) then (result.passed.push(t) if result.passed isnt false) else result.failed.push(t)) for t of tests result.passed = result.passed.length if result.passed isnt false and result.failed.length is 0 result = {passed:result.passed} if result.failed.length is 0 and not verbose return result API.service.oab.test._examples = { resolve: { "url": "http://linkinghub.elsevier.com/retrieve/pii/S0735109712600734", "all": true, "sources": [ "oabutton", "eupmc", "oadoi", "base", "dissemin", "share", "core", "openaire", "figshare", "doaj" ], "found": { "oadoi": "http://linkinghub.elsevier.com/retrieve/pii/S0735109712600734" }, "checked": { "identifiers": [ "oabutton", "oadoi", "eupmc", "base", "dissemin", "share", "core", "openaire", "figshare", "doaj" ], "titles": [ "eupmc", "share", "base", "core", "openaire", "doaj" ] }, "original": "http://www.sciencedirect.com/science/article/pii/S0735109712600734", "doi": "10.1016/s0735-1097(12)60073-4", "title": "cost-effectiveness analysis of propensity matched radial and femoral cardiac catheterization and coronary intervention", "email": [], "source": "oadoi", "licence": "elsevier-specific: oa user license", "titles": true }, scrape: { "url": "http://www.tandfonline.com/doi/abs/10.1080/09505431.2014.928678", "doi": "10.1080/09505431.2014.928678", "title": "Lamenting the Golden Age: Love, Labour and Loss in the Collective Memory of Scientists", "author": [ { "given": "Kerry", "family": "Holden", "affiliation": [] } ], "journal": "Science as Culture", "issn": "0950-5431", "subject": [ "Biotechnology", "History and Philosophy of Science", "Cultural Studies", "Sociology and Political Science", "Health(social science)", "Biomedical Engineering" ], "publisher": "Informa UK Limited", "keywords": [ "academic science", "commercialisation", "golden age", "moral economy", "myth", "scientific labour" ], "email": [ "k.holden@qmul.ac.uk" ] }, request: { "url": "https://jcheminf.springeropen.com/articles/10.1186/1758-2946-3-47", "test": true, "type": "article", "count": 0, "keywords": [], "title": "Open Bibliography for Science, Technology, and Medicine", "doi": "10.1186/1758-2946-3-47", "author": [ { "given": "Richard", "family": "Jones", "affiliation": [] }, { "given": "Mark", "family": "MacGillivray", "affiliation": [] }, { "given": "Peter", "family": "Murray-Rust", "affiliation": [] }, { "given": "Jim", "family": "Pitman", "affiliation": [] }, { "given": "Peter", "family": "Sefton", "affiliation": [] }, { "given": "Ben", "family": "O'Steen", "affiliation": [] }, { "given": "William", "family": "Waites", "affiliation": [] } ], "journal": "Journal of Cheminformatics", "issn": "1758-2946", "publisher": "Springer Nature", "status": "help", } }
120159
import Future from 'fibers/future' API.add 'service/oab/test', get: roleRequired: if API.settings.dev then undefined else 'root' action: () -> return API.service.oab.test(this.queryParams.verbose) API.service.oab.test = (verbose) -> result = {passed:[],failed:[]} oab_request.remove url: 'https://jcheminf.springeropen.com/articles/10.1186/1758-2946-3-47' tests = [ () -> result.find_citation = API.service.oab.find url: '<NAME>., & <NAME>. (2016). El Bicentenario argentino como territorio en disputa. Analecta política, 6(10).', refresh: 0 return result.find_citation.match is "https://doi.org/10.18566/apolit.v6n10.a04" and result.find_citation.availability?[0]?.url is "https://revistas.upb.edu.co/index.php/analecta/article/download/6166/5658" and result.find_citation.meta.article.source is "oadoi" () -> result.find_title = API.service.oab.find url: 'Effect of Saxagliptin on Renal Outcomes in the SAVOR-TIMI 53 Trial', refresh: 0 return result.find_title.match is "https://doi.org/10.2337/dc16-0621" and result.find_title.availability?[0]?.url is "https://spiral.imperial.ac.uk:8443/bitstream/10044/1/42241/4/Effect%20of%20Saxagliptin%20on%20Renal%20Outcomes%20in%20the%20SAVOR%20trial%20clean%20final%201....pdf" and result.find_title.meta.article.source is "oadoi" () -> result.find_url = API.service.oab.find url: 'http://journals.sagepub.com/doi/abs/10.1177/0037549715583150', refresh: 0 return result.find_url.match is "http://journals.sagepub.com/doi/abs/10.1177/0037549715583150" and result.find_url.availability?[0]?.url is "http://journals.sagepub.com/doi/pdf/10.1177/0037549715583150" and result.find_url.meta.article.source is "oadoi" () -> result.find_pmid = API.service.oab.find url: '27353853', refresh: 0 return result.find_pmid.match is "https://www.ncbi.nlm.nih.gov/pubmed/27353853" and result.find_pmid.availability?[0]?.url is "http://circimaging.ahajournals.org/content/circcvim/9/7/e005150.full.pdf" and result.find_pmid.meta.article.source is "oadoi" () -> result.find_pmc = API.service.oab.find url: 'PMC3220411', refresh: 0 return result.find_pmc.match is "http://europepmc.org/articles/PMC3220411" and result.find_pmc.availability?[0]?.url is "http://europepmc.org/articles/PMC3220411?pdf=render" and result.find_pmc.meta.article.source is "eupmc" () -> result.find_doi = API.service.oab.find url: '10.1145/2908080.2908114', refresh: 0 return result.find_doi.match is "https://doi.org/10.1145/2908080.2908114" and result.find_doi.availability?[0]?.url is "http://spiral.imperial.ac.uk/bitstream/10044/1/31580/2/paper.pdf" and result.find_doi.meta.article.source is "oadoi" () -> result.closed = API.service.oab.find url: 'http://www.tandfonline.com/doi/abs/10.1080/09505431.2014.928678', refresh: 0 return result.closed.match is "http://www.tandfonline.com/doi/abs/10.1080/09505431.2014.928678" and result.closed.availability.length is 0 and not result.closed.meta.article.source? and result.closed.meta.article.doi is "10.1080/09505431.2014.928678" () -> result.resolve = API.service.oab.resolve 'http://www.sciencedirect.com/science/article/pii/S0735109712600734', undefined, undefined, true return _.isEqual result.resolve, API.service.oab.test._examples.resolve () -> result.redirect_false = API.service.oab.redirect 'https://www.researchgate.net/anything' return result.redirect_false is false () -> result.redirect_fulltext = API.service.oab.redirect 'https://arxiv.org/abs/1711.07985' return result.redirect_fulltext is 'https://arxiv.org/pdf/1711.07985.pdf' () -> result.redirect_element = API.service.oab.redirect 'http://nora.nerc.ac.uk/518502' return result.redirect_element is 'http://nora.nerc.ac.uk/518502/1/N518502CR.pdf' () -> result.scrape = API.service.oab.scrape 'http://www.tandfonline.com/doi/abs/10.1080/09505431.2014.928678' return _.isEqual result.scrape, API.service.oab.test._examples.scrape () -> result.request = API.service.oab.request url: 'https://jcheminf.springeropen.com/articles/10.1186/1758-2946-3-47', test: true ck = JSON.parse(JSON.stringify(result.request)) delete ck.receiver delete ck._id return _.isEqual ck, API.service.oab.test._examples.request () -> result.support = API.service.oab.support result.request._id, "I am the test story", "0" future = new Future() Meteor.setTimeout (() -> future.return()), 999 future.wait() result.supports = API.service.oab.supports result.request._id, "0" oab_support.remove result.support._id return result.supports?.rid is result.request._id and result.supports?.story is "I am the test story" and result.supports?.uid is "0" () -> result.hold = API.service.oab.hold result.request._id, 7 result.held = oab_request.get result.request._id return result.held.status is 'hold' and result.held.holds? and result.held.hold?.until? () -> result.refuse = API.service.oab.refuse result.request._id, "Test reason" result.refused = oab_request.get result.request._id oab_request.remove result.request._id return result.refused.status is 'refused' and not result.refused.email? and not result.refused.hold? and result.refused.refused? and result.refused.refused[0].reason is "Test reason" () -> result.dnr = API.service.oab.dnr '<EMAIL>', true future = new Future() Meteor.setTimeout (() -> future.return()), 999 future.wait() result.ondnr = API.service.oab.dnr '<EMAIL>' oab_dnr.remove {email: '<EMAIL>'} return result.ondnr is true () -> result.vars = API.service.oab.vars {user: {id:"0"}} return result.vars.userid is "0" and result.vars.profession? and result.vars.fullname? ] # TODO need to add tests for ill once we start developing that again (if (try tests[t]()) then (result.passed.push(t) if result.passed isnt false) else result.failed.push(t)) for t of tests result.passed = result.passed.length if result.passed isnt false and result.failed.length is 0 result = {passed:result.passed} if result.failed.length is 0 and not verbose return result API.service.oab.test._examples = { resolve: { "url": "http://linkinghub.elsevier.com/retrieve/pii/S0735109712600734", "all": true, "sources": [ "oabutton", "eupmc", "oadoi", "base", "dissemin", "share", "core", "openaire", "figshare", "doaj" ], "found": { "oadoi": "http://linkinghub.elsevier.com/retrieve/pii/S0735109712600734" }, "checked": { "identifiers": [ "oabutton", "oadoi", "eupmc", "base", "dissemin", "share", "core", "openaire", "figshare", "doaj" ], "titles": [ "eupmc", "share", "base", "core", "openaire", "doaj" ] }, "original": "http://www.sciencedirect.com/science/article/pii/S0735109712600734", "doi": "10.1016/s0735-1097(12)60073-4", "title": "cost-effectiveness analysis of propensity matched radial and femoral cardiac catheterization and coronary intervention", "email": [], "source": "oadoi", "licence": "elsevier-specific: oa user license", "titles": true }, scrape: { "url": "http://www.tandfonline.com/doi/abs/10.1080/09505431.2014.928678", "doi": "10.1080/09505431.2014.928678", "title": "Lamenting the Golden Age: Love, Labour and Loss in the Collective Memory of Scientists", "author": [ { "given": "<NAME>", "family": "<NAME>", "affiliation": [] } ], "journal": "Science as Culture", "issn": "0950-5431", "subject": [ "Biotechnology", "History and Philosophy of Science", "Cultural Studies", "Sociology and Political Science", "Health(social science)", "Biomedical Engineering" ], "publisher": "Informa UK Limited", "keywords": [ "academic science", "commercialisation", "golden age", "moral economy", "myth", "scientific labour" ], "email": [ "<EMAIL>" ] }, request: { "url": "https://jcheminf.springeropen.com/articles/10.1186/1758-2946-3-47", "test": true, "type": "article", "count": 0, "keywords": [], "title": "Open Bibliography for Science, Technology, and Medicine", "doi": "10.1186/1758-2946-3-47", "author": [ { "given": "<NAME>", "family": "<NAME>", "affiliation": [] }, { "given": "<NAME>", "family": "<NAME>", "affiliation": [] }, { "given": "<NAME>", "family": "<NAME>", "affiliation": [] }, { "given": "<NAME>", "family": "<NAME>", "affiliation": [] }, { "given": "<NAME>", "family": "<NAME>", "affiliation": [] }, { "given": "<NAME>", "family": "<NAME>", "affiliation": [] }, { "given": "<NAME>", "family": "<NAME>", "affiliation": [] } ], "journal": "Journal of Cheminformatics", "issn": "1758-2946", "publisher": "Springer Nature", "status": "help", } }
true
import Future from 'fibers/future' API.add 'service/oab/test', get: roleRequired: if API.settings.dev then undefined else 'root' action: () -> return API.service.oab.test(this.queryParams.verbose) API.service.oab.test = (verbose) -> result = {passed:[],failed:[]} oab_request.remove url: 'https://jcheminf.springeropen.com/articles/10.1186/1758-2946-3-47' tests = [ () -> result.find_citation = API.service.oab.find url: 'PI:NAME:<NAME>END_PI., & PI:NAME:<NAME>END_PI. (2016). El Bicentenario argentino como territorio en disputa. Analecta política, 6(10).', refresh: 0 return result.find_citation.match is "https://doi.org/10.18566/apolit.v6n10.a04" and result.find_citation.availability?[0]?.url is "https://revistas.upb.edu.co/index.php/analecta/article/download/6166/5658" and result.find_citation.meta.article.source is "oadoi" () -> result.find_title = API.service.oab.find url: 'Effect of Saxagliptin on Renal Outcomes in the SAVOR-TIMI 53 Trial', refresh: 0 return result.find_title.match is "https://doi.org/10.2337/dc16-0621" and result.find_title.availability?[0]?.url is "https://spiral.imperial.ac.uk:8443/bitstream/10044/1/42241/4/Effect%20of%20Saxagliptin%20on%20Renal%20Outcomes%20in%20the%20SAVOR%20trial%20clean%20final%201....pdf" and result.find_title.meta.article.source is "oadoi" () -> result.find_url = API.service.oab.find url: 'http://journals.sagepub.com/doi/abs/10.1177/0037549715583150', refresh: 0 return result.find_url.match is "http://journals.sagepub.com/doi/abs/10.1177/0037549715583150" and result.find_url.availability?[0]?.url is "http://journals.sagepub.com/doi/pdf/10.1177/0037549715583150" and result.find_url.meta.article.source is "oadoi" () -> result.find_pmid = API.service.oab.find url: '27353853', refresh: 0 return result.find_pmid.match is "https://www.ncbi.nlm.nih.gov/pubmed/27353853" and result.find_pmid.availability?[0]?.url is "http://circimaging.ahajournals.org/content/circcvim/9/7/e005150.full.pdf" and result.find_pmid.meta.article.source is "oadoi" () -> result.find_pmc = API.service.oab.find url: 'PMC3220411', refresh: 0 return result.find_pmc.match is "http://europepmc.org/articles/PMC3220411" and result.find_pmc.availability?[0]?.url is "http://europepmc.org/articles/PMC3220411?pdf=render" and result.find_pmc.meta.article.source is "eupmc" () -> result.find_doi = API.service.oab.find url: '10.1145/2908080.2908114', refresh: 0 return result.find_doi.match is "https://doi.org/10.1145/2908080.2908114" and result.find_doi.availability?[0]?.url is "http://spiral.imperial.ac.uk/bitstream/10044/1/31580/2/paper.pdf" and result.find_doi.meta.article.source is "oadoi" () -> result.closed = API.service.oab.find url: 'http://www.tandfonline.com/doi/abs/10.1080/09505431.2014.928678', refresh: 0 return result.closed.match is "http://www.tandfonline.com/doi/abs/10.1080/09505431.2014.928678" and result.closed.availability.length is 0 and not result.closed.meta.article.source? and result.closed.meta.article.doi is "10.1080/09505431.2014.928678" () -> result.resolve = API.service.oab.resolve 'http://www.sciencedirect.com/science/article/pii/S0735109712600734', undefined, undefined, true return _.isEqual result.resolve, API.service.oab.test._examples.resolve () -> result.redirect_false = API.service.oab.redirect 'https://www.researchgate.net/anything' return result.redirect_false is false () -> result.redirect_fulltext = API.service.oab.redirect 'https://arxiv.org/abs/1711.07985' return result.redirect_fulltext is 'https://arxiv.org/pdf/1711.07985.pdf' () -> result.redirect_element = API.service.oab.redirect 'http://nora.nerc.ac.uk/518502' return result.redirect_element is 'http://nora.nerc.ac.uk/518502/1/N518502CR.pdf' () -> result.scrape = API.service.oab.scrape 'http://www.tandfonline.com/doi/abs/10.1080/09505431.2014.928678' return _.isEqual result.scrape, API.service.oab.test._examples.scrape () -> result.request = API.service.oab.request url: 'https://jcheminf.springeropen.com/articles/10.1186/1758-2946-3-47', test: true ck = JSON.parse(JSON.stringify(result.request)) delete ck.receiver delete ck._id return _.isEqual ck, API.service.oab.test._examples.request () -> result.support = API.service.oab.support result.request._id, "I am the test story", "0" future = new Future() Meteor.setTimeout (() -> future.return()), 999 future.wait() result.supports = API.service.oab.supports result.request._id, "0" oab_support.remove result.support._id return result.supports?.rid is result.request._id and result.supports?.story is "I am the test story" and result.supports?.uid is "0" () -> result.hold = API.service.oab.hold result.request._id, 7 result.held = oab_request.get result.request._id return result.held.status is 'hold' and result.held.holds? and result.held.hold?.until? () -> result.refuse = API.service.oab.refuse result.request._id, "Test reason" result.refused = oab_request.get result.request._id oab_request.remove result.request._id return result.refused.status is 'refused' and not result.refused.email? and not result.refused.hold? and result.refused.refused? and result.refused.refused[0].reason is "Test reason" () -> result.dnr = API.service.oab.dnr 'PI:EMAIL:<EMAIL>END_PI', true future = new Future() Meteor.setTimeout (() -> future.return()), 999 future.wait() result.ondnr = API.service.oab.dnr 'PI:EMAIL:<EMAIL>END_PI' oab_dnr.remove {email: 'PI:EMAIL:<EMAIL>END_PI'} return result.ondnr is true () -> result.vars = API.service.oab.vars {user: {id:"0"}} return result.vars.userid is "0" and result.vars.profession? and result.vars.fullname? ] # TODO need to add tests for ill once we start developing that again (if (try tests[t]()) then (result.passed.push(t) if result.passed isnt false) else result.failed.push(t)) for t of tests result.passed = result.passed.length if result.passed isnt false and result.failed.length is 0 result = {passed:result.passed} if result.failed.length is 0 and not verbose return result API.service.oab.test._examples = { resolve: { "url": "http://linkinghub.elsevier.com/retrieve/pii/S0735109712600734", "all": true, "sources": [ "oabutton", "eupmc", "oadoi", "base", "dissemin", "share", "core", "openaire", "figshare", "doaj" ], "found": { "oadoi": "http://linkinghub.elsevier.com/retrieve/pii/S0735109712600734" }, "checked": { "identifiers": [ "oabutton", "oadoi", "eupmc", "base", "dissemin", "share", "core", "openaire", "figshare", "doaj" ], "titles": [ "eupmc", "share", "base", "core", "openaire", "doaj" ] }, "original": "http://www.sciencedirect.com/science/article/pii/S0735109712600734", "doi": "10.1016/s0735-1097(12)60073-4", "title": "cost-effectiveness analysis of propensity matched radial and femoral cardiac catheterization and coronary intervention", "email": [], "source": "oadoi", "licence": "elsevier-specific: oa user license", "titles": true }, scrape: { "url": "http://www.tandfonline.com/doi/abs/10.1080/09505431.2014.928678", "doi": "10.1080/09505431.2014.928678", "title": "Lamenting the Golden Age: Love, Labour and Loss in the Collective Memory of Scientists", "author": [ { "given": "PI:NAME:<NAME>END_PI", "family": "PI:NAME:<NAME>END_PI", "affiliation": [] } ], "journal": "Science as Culture", "issn": "0950-5431", "subject": [ "Biotechnology", "History and Philosophy of Science", "Cultural Studies", "Sociology and Political Science", "Health(social science)", "Biomedical Engineering" ], "publisher": "Informa UK Limited", "keywords": [ "academic science", "commercialisation", "golden age", "moral economy", "myth", "scientific labour" ], "email": [ "PI:EMAIL:<EMAIL>END_PI" ] }, request: { "url": "https://jcheminf.springeropen.com/articles/10.1186/1758-2946-3-47", "test": true, "type": "article", "count": 0, "keywords": [], "title": "Open Bibliography for Science, Technology, and Medicine", "doi": "10.1186/1758-2946-3-47", "author": [ { "given": "PI:NAME:<NAME>END_PI", "family": "PI:NAME:<NAME>END_PI", "affiliation": [] }, { "given": "PI:NAME:<NAME>END_PI", "family": "PI:NAME:<NAME>END_PI", "affiliation": [] }, { "given": "PI:NAME:<NAME>END_PI", "family": "PI:NAME:<NAME>END_PI", "affiliation": [] }, { "given": "PI:NAME:<NAME>END_PI", "family": "PI:NAME:<NAME>END_PI", "affiliation": [] }, { "given": "PI:NAME:<NAME>END_PI", "family": "PI:NAME:<NAME>END_PI", "affiliation": [] }, { "given": "PI:NAME:<NAME>END_PI", "family": "PI:NAME:<NAME>END_PI", "affiliation": [] }, { "given": "PI:NAME:<NAME>END_PI", "family": "PI:NAME:<NAME>END_PI", "affiliation": [] } ], "journal": "Journal of Cheminformatics", "issn": "1758-2946", "publisher": "Springer Nature", "status": "help", } }
[ { "context": "> x.toFixed precision\n\n### see https://github.com/nwjs/nw.js/wiki/Window ###\nsplash_info = [ './splash.h", "end": 2126, "score": 0.9993883967399597, "start": 2122, "tag": "USERNAME", "value": "nwjs" }, { "context": "nsertion_y_px}px\n\ne.g.\n\n mkts://(file:///Users/dave/Documents/cv.mkts)/page:3/column:4/y:120.45px\n###", "end": 3092, "score": 0.9990884065628052, "start": 3088, "tag": "USERNAME", "value": "dave" }, { "context": "re was nothing so VERY remarkable in that; nor did Alice think it so\n # VERY much out of the way to hea", "end": 12087, "score": 0.9694283604621887, "start": 12082, "tag": "NAME", "value": "Alice" }, { "context": "CKET, and looked at it, and then hurried on,\n # Alice started to her feet, for it flashed across her mi", "end": 12491, "score": 0.947131335735321, "start": 12486, "tag": "NAME", "value": "Alice" }, { "context": "# 'Come, there's no use in crying like that!' said Alice to herself,\n # rather sharply; 'I advise you t", "end": 12884, "score": 0.950078010559082, "start": 12879, "tag": "NAME", "value": "Alice" }, { "context": " people.\n # 'But it's no use now,' thought poor Alice, 'to pretend to be two people!\n # Why, there's", "end": 13400, "score": 0.9785415530204773, "start": 13395, "tag": "NAME", "value": "Alice" }, { "context": "--\nMKTS.push_tool_mode = ( mode ) ->\n debug '©2ryq9', app[ 'tool-modes' ]\n app[ 'tool-modes' ].push ", "end": 18143, "score": 0.684785008430481, "start": 18141, "tag": "USERNAME", "value": "q9" }, { "context": "................\n return null\n\n###\n\n{\n \"name\": \"mingkwai\"\n\n \"main\": \"lib/index.html\",\n \"version\": \"0.1.0", "end": 21286, "score": 0.9989204406738281, "start": 21278, "tag": "USERNAME", "value": "mingkwai" } ]
mingkwai.app/Contents/Resources/app.nw/src/browser.coffee
loveencounterflow/mingkwai-app
0
############################################################################################################ njs_path = require 'path' njs_fs = require 'fs' #........................................................................................................... CND = require 'cnd' rpr = CND.rpr.bind CND badge = '眀快排字机/browser' log = CND.get_logger 'plain', badge info = CND.get_logger 'info', badge alert = CND.get_logger 'alert', badge debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge urge = CND.get_logger 'urge', badge whisper = CND.get_logger 'whisper', badge help = CND.get_logger 'help', badge echo = CND.echo.bind CND #........................................................................................................... NW = require 'nw.gui' win = NW.Window.get() #........................................................................................................... suspend = require 'coffeenode-suspend' step = suspend.step immediately = suspend.immediately after = suspend.after sleep = suspend.sleep #........................................................................................................... D = require 'pipedreams' D$ = D.remit.bind D CHR = require 'coffeenode-chr' #........................................................................................................... LINESETTER = require './LINESETTER' #........................................................................................................... ƒ = ( x, precision = 2 ) -> x.toFixed precision ### see https://github.com/nwjs/nw.js/wiki/Window ### splash_info = [ './splash.html', "position": "center", "title": "眀快排字机", "width": 800, "height": 500, "frame": false, "toolbar": false, "transparent": true, "focus": false, "resizable": false, "show": true, "show_in_taskbar": true, ] #----------------------------------------------------------------------------------------------------------- splash_win = NW.Window.open splash_info... #----------------------------------------------------------------------------------------------------------- ### Description of what is being typeset; the document. ### ### At some point in the future, maybe we'll be able to refer to the matter (document) and to locations inside the matter by using a URL like: mkts://#{file_locator}#page:#{page_nr}/column:#{column_nr}/y:#{insertion_y_px}px e.g. mkts://(file:///Users/dave/Documents/cv.mkts)/page:3/column:4/y:120.45px ### matter = '~isa': 'MKTS/matter' 'batch-idx': -1 'pages': [] 'caret': 'page-nr': 1 'column-nr': 1 'y.px': 0 #----------------------------------------------------------------------------------------------------------- ### Description of the app, its settings and its current user interface state. ### app = '~isa': 'MKTS/app' '%memo': {} ### TAINT populate with `MKTS.new_windows()` ### '%windows': 'main': win 'devtools': null 'splash': splash_win # 'mm-per-px': 100 / 377.94791 # 'mm-per-px': 55 / 203.704 # 'mm-per-px': 160 / 593 'gauge': null 'jQuery': $ 'NW': NW 'MKTS': null 'artboard': null 'window': window 'view-mode': 'dev' 'zoom-delta-factor': 1.25 'zoom': 1 'tool-modes': [] 'tool-modes-default': 'default' 'view': 'pages' 'matter': matter #----------------------------------------------------------------------------------------------------------- ### Publish app so we have access to it in both the browser and the NodeJS contexts: ### window[ 'app' ] = app #----------------------------------------------------------------------------------------------------------- MKTS = ( require './MKTS' ) app ### TAINT temporary fix: ### app[ 'MKTS' ] = MKTS app[ 'gauge' ] = MKTS.GAUGE.new app # win.zoomLevel = 0 # 100% # win.setResizable yes # win.resizeTo 1500, 1500 # win.setTransparent yes # ??? # win.showDevTools() # win.setProgressBar 0.5 # visible on dock icon # win.setBadgeLabel = 'helo from 眀快排字机' # ??? # help '©5t3', document.visibilityState # CND.dir win # help ( name for name of window).join ' ' # win.on 'blur', -> info 'blur' # win.on 'capturepagedone', -> info 'capturepagedone' win.on 'close', -> info 'close'; @close true # win.on 'closed', -> info 'closed' # win.on 'devtools-closed', -> info 'devtools-closed' # win.on 'devtools-opened', -> info 'devtools-opened' # win.on 'document-end', -> info 'document-end' # win.on 'document-start', -> info 'document-start' # win.on 'enter-fullscreen', -> info 'enter-fullscreen' # win.on 'focus', -> info 'focus' # win.on 'leave-fullscreen', -> info 'leave-fullscreen' # win.on 'loaded', -> info 'loaded' # win.on 'loading', -> info 'loading' # win.on 'maximize', -> info 'maximize' # win.on 'minimize', -> info 'minimize' # win.on 'move', -> info 'move' # win.on 'new-win-policy', -> info 'new-win-policy' # win.on 'resize', -> info 'resize' # win.on 'restore', -> info 'restore' # win.on 'unmaximize', -> info 'unmaximize' # win.on 'zoom', -> info 'zoom' # debug '©AfAsc', 'window.devicePixelRatio ', window.devicePixelRatio # debug '©AfAsc', 'window.devicePixelRatio ', window.devicePixelRatio # debug '©igYFq', 'window.screen.availTop ', window.screen.availTop # debug '©VUTiB', 'window.screen.availLeft ', window.screen.availLeft # debug '©o8v8T', 'window.screen.availHeight', window.screen.availHeight # debug '©Ubkrt', 'window.screen.availWidth ', window.screen.availWidth # debug '©zvq8U', 'window.screen.colorDepth ', window.screen.colorDepth # debug '©nH9a6', 'window.screen.height ', window.screen.height # debug '©YDbG3', 'window.screen.left ', window.screen.left # debug '©j0QXK', 'window.screen.orientation', window.screen.orientation # debug '©wEUqB', 'window.screen.pixelDepth ', window.screen.pixelDepth # debug '©G5QV3', 'window.screen.top ', window.screen.top # debug '©7Kqfv', 'window.screen.width ', window.screen.width # #----------------------------------------------------------------------------------------------------------- # win.on 'resize', -> # info "resized to #{win.width} x #{win.height}" # #----------------------------------------------------------------------------------------------------------- # win.on 'move', -> # info "moved to #{win.x}, #{win.y}" #----------------------------------------------------------------------------------------------------------- MKTS.get_document_size = ( me ) -> [ ( $ 'html' ).outerWidth(), ( $ 'html' ).outerHeight(), ] #----------------------------------------------------------------------------------------------------------- MKTS.maximize = ( app ) -> win.moveTo window.screen.availLeft, window.screen.availTop win.resizeTo window.screen.availWidth, window.screen.availHeight #----------------------------------------------------------------------------------------------------------- MKTS.wait = ( handler ) -> window.requestAnimationFrame -> handler() #----------------------------------------------------------------------------------------------------------- MKTS.take_screenshot = -> step ( resume ) => ### trying to wait for DOM reflow: ### # yield step.wrap window.requestAnimationFrame, resume yield MKTS.wait resume # help 'animation frame' img = yield MKTS._capture win, resume img_route = '/tmp/nw.png' yield njs_fs.writeFile img_route, img, resume help "image written to #{img_route}" #----------------------------------------------------------------------------------------------------------- MKTS.scroll_to = ( label ) -> # log '©Rafbc', ( $ '#bottom' ).offset ( $ 'html, body' ).stop().animate { scrollTop: ( $ label ).offset().top }, 500 #----------------------------------------------------------------------------------------------------------- MKTS.scroll_to_top = -> @scroll_to '#mkts-top' MKTS.scroll_to_bottom = -> @scroll_to '#mkts-bottom' #----------------------------------------------------------------------------------------------------------- MKTS._capture = ( win, handler ) -> win.capturePage ( ( img ) => handler null, img ), format: 'png', datatype: 'buffer' demo_count = 0 #----------------------------------------------------------------------------------------------------------- MKTS.demo = ( me ) -> debug '©iNl2F', 'demo' # source = """<em>Ab<xsmall>c</xsmall>d<xbig>e</xbig>ffiVA</em>""" # source = """Xxxxxxxxxxxxxxxx, she noticed xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx""" # source = """ # # Behind the Looking-Glass # 'But everything's curious today. I think I may as well go in at once.' And in # she went. # # Behind the Looking-Glass # Just as she said this, she noticed that one of the trees had a door # leading right into it. 'That's very curious!' she thought. 'But # everything's <xbig>curious</xbig> today. I think I may as well go in at once.' And in # she went. # 上古時期的越南語很可能具有南亞語系其他語言現在具有的一些共同特徵,例如在屈折方面較發達,具有豐富的複輔音等。這些特徵已不再存於現代的越南語中,據認為是由於越南語地處東南亞的“語言聯盟”中,受到周邊有聲調的孤立語的影響,也變成了一種有聲調的孤立語。形態上的孤立和聲調的存在可能並非來源自原始南亞語,周邊的無親屬關係的語言,例如壯侗語系的泰語和南島語系的回輝話,也都具有聲調。 # Just as shé said this, she fluffi *noticed* that # one of the trees had a door # leading right into it. 'That's very curious!' she thought. # Just as shé said this, she fluffi *noticed* that # one of the trees had a door # leading right into it. 'That's very curious!' she thought. # Just as shé said this, she fluffi *noticed* that # one of the trees had a door # leading right into it. 'That's very curious!' she thought. # Just as shé said this, she fluffi *noticed* that # one of the trees had a door # leading right into it. 'That's very curious!' she thought. # """ # source = "one <xbig>line</xbig>\n\n" + source[ .. 500 ] + ( 'ddd' for i in [ 0 .. 150 ] ).join ' ' # demo_count += +1 # if demo_count is 1 # source = """ # # Test # just a **test**. *ffi*. abcdefghijklm Q Qu Queen the most unbelievable story.""" # debug '©uvL5t', source.length # source = "Just as shé said this, she fluffi *noticed* that abc def ghi jkl mno pqr stu vwx xy" source = """ 'But everything's curious today. I think I may as well go in at once.' And in she went.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx and so on. bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb Short paragraph. """ # supercalifragilisticexpialigoricalsupercalifragilisticexpialigorical # Sedutperspiciatisundeomnisistenatuserrorsitvoluptatemaccusantiumdoloremquelaudantium,totamremaperiam,eaqueipsaquaeabilloinventoreveritatisetquasiarchitectobeataevitaedicta sunt explicabo. # # Behind the Looking-Glass # The King and Queen of Hearts were <xbig>seated</xbig> on their throne when they # arrived, with a great crowd assembled about them--all sorts of little # birds and beasts. # There was nothing so VERY remarkable in that; nor did Alice think it so # VERY much out of the way to hear the Rabbit say to itself, 'Oh dear! # Oh dear! I shall be late!' (when she thought it over afterwards, it # occurred to her that she ought to have wondered at this, but at the time # it all seemed quite natural); but when the Rabbit actually TOOK A WATCH # OUT OF ITS WAISTCOAT-POCKET, and looked at it, and then hurried on, # Alice started to her feet, for it flashed across her mind that she had # never before seen a rabbit with either a waistcoat-pocket, or a watch # to take out of it, and burning with curiosity, she ran across the field # after it, and fortunately was just in time to see it pop down a large # rabbit-hole under the hedge. # 'Come, there's no use in crying like that!' said Alice to herself, # rather sharply; 'I advise you to leave off this minute!' She generally # gave herself very good advice, (though she very seldom followed it), # and sometimes she scolded herself so severely as to bring tears into # her eyes; and once she remembered trying to box her own ears for having # cheated herself in a game of croquet she was playing against herself, # for this curious child was very fond of pretending to be two people. # 'But it's no use now,' thought poor Alice, 'to pretend to be two people! # Why, there's hardly enough of me left to make ONE respectable person!' # source = """ # <kwic-lineup>1 中國皇帝</kwic-lineup> # <kwic-lineup>2 中國皇帝</kwic-lineup> # <kwic-lineup>3 中國皇帝</kwic-lineup> # <kwic-lineup>4 中國皇帝</kwic-lineup> # <kwic-lineup>5 中國皇帝</kwic-lineup> # <kwic-lineup>6 中國皇帝</kwic-lineup> # <kwic-lineup>7 中國皇帝</kwic-lineup> # <kwic-lineup>8 中國皇帝</kwic-lineup> # <kwic-lineup>9 中國皇帝</kwic-lineup> # <kwic-lineup>10 中國皇帝</kwic-lineup> # <kwic-lineup>11 中國皇帝</kwic-lineup> # <kwic-lineup>12 中國皇帝</kwic-lineup> # <kwic-lineup>13 中國皇帝</kwic-lineup> # <kwic-lineup>14 中國皇帝</kwic-lineup> # <kwic-lineup>15 中國皇帝</kwic-lineup> # <kwic-lineup>16 中國皇帝</kwic-lineup> # <kwic-lineup>17 中國皇帝</kwic-lineup> # <kwic-lineup>18 中國皇帝</kwic-lineup> # <kwic-lineup>19 中國皇帝</kwic-lineup> # <kwic-lineup>20 中國皇帝</kwic-lineup> # <kwic-lineup>21 中國皇帝</kwic-lineup> # <kwic-lineup>22 中國皇帝</kwic-lineup> # <kwic-lineup>23 中國皇帝</kwic-lineup> # <kwic-lineup>24 中國皇帝</kwic-lineup> # <kwic-lineup>25 中國皇帝</kwic-lineup> # <kwic-lineup>26 中國皇帝</kwic-lineup> # <kwic-lineup>27 中國皇帝</kwic-lineup> # <kwic-lineup>28 中國皇帝</kwic-lineup> # <kwic-lineup>29 中國皇帝</kwic-lineup> # <kwic-lineup>30 中國皇帝</kwic-lineup> # <kwic-lineup>31 中國皇帝</kwic-lineup> # <kwic-lineup>32 中國皇帝</kwic-lineup> # <kwic-lineup>33 中國皇帝</kwic-lineup> # <kwic-lineup>34 中國皇帝</kwic-lineup> # <kwic-lineup>35 中國皇帝</kwic-lineup> # <kwic-lineup>36 中國皇帝</kwic-lineup> # <kwic-lineup>37 中國皇帝</kwic-lineup> # <kwic-lineup>38 中國皇帝</kwic-lineup> # <kwic-lineup>39 中國皇帝</kwic-lineup> # <kwic-lineup>40 中國皇帝</kwic-lineup> # <kwic-lineup>41 中國皇帝</kwic-lineup> # <kwic-lineup>42 中國皇帝</kwic-lineup> # <kwic-lineup>43 中國皇帝</kwic-lineup> # <kwic-lineup>44 中國皇帝</kwic-lineup> # <kwic-lineup>45 中國皇帝</kwic-lineup> # <kwic-lineup>46 中國皇帝</kwic-lineup> # <kwic-lineup>47 中國皇帝</kwic-lineup> # <kwic-lineup>48 中國皇帝</kwic-lineup> # <kwic-lineup>49 中國皇帝</kwic-lineup> # <kwic-lineup>50 中國皇帝</kwic-lineup> # <kwic-lineup>51 中國皇帝</kwic-lineup> # <kwic-lineup>52 中國皇帝</kwic-lineup> # <kwic-lineup>53 中國皇帝</kwic-lineup> # <kwic-lineup>54 中國皇帝</kwic-lineup> # <kwic-lineup>55 中國皇帝</kwic-lineup> # <kwic-lineup>56 中國皇帝</kwic-lineup> # <kwic-lineup>57 中國皇帝</kwic-lineup> # <kwic-lineup>58 中國皇帝</kwic-lineup> # <kwic-lineup>59 中國皇帝</kwic-lineup> # <kwic-lineup>60 中國皇帝</kwic-lineup> # <kwic-lineup>61 中國皇帝</kwic-lineup> # <kwic-lineup>62 中國皇帝</kwic-lineup> # <kwic-lineup>63 中國皇帝</kwic-lineup> # <kwic-lineup>64 中國皇帝</kwic-lineup> # <kwic-lineup>65 中國皇帝</kwic-lineup> # <kwic-lineup>66 中國皇帝</kwic-lineup> # <kwic-lineup>67 中國皇帝</kwic-lineup> # <kwic-lineup>68 中國皇帝</kwic-lineup> # """ # source = require './demo-text' # source = njs_fs.readFileSync '/tmp/kwic.html', encoding: 'utf-8' # source = ( ( if line.length is 0 or line is '```' then line else "#{line}<!--##{idx}-->" ) for line, idx in source.split '\n' ).join '\n' help "source: approx. #{source.length} characters" settings = # 'format': 'html' 'format': 'md' step ( resume ) => # yield MKTS.VIEW.show_galley resume yield LINESETTER.demo me, source, settings, resume # MKTS.revert_zoom me help "MKTS.demo ok" return null ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### #----------------------------------------------------------------------------------------------------------- MKTS.toggle_tool_mode = ( mode ) -> return @pop_tool_mode() if ( CND.last_of app[ 'tool-modes' ] ) is mode return @push_tool_mode mode #----------------------------------------------------------------------------------------------------------- MKTS.push_tool_mode = ( mode ) -> debug '©2ryq9', app[ 'tool-modes' ] app[ 'tool-modes' ].push mode unless ( CND.last_of app[ 'tool-modes' ] ) is mode app[ 'tool-modes' ].shift() if app[ 'tool-modes' ].length > 10 # ( $ 'body' ).css 'cursor', 'url(./icons/mkts-tool-hand.png)' # ( $ 'body' ).attr 'style', 'cursor:url(./icons/mkts-tool-hand-cursor.png), auto;' ### TAINT must swap classes ### ### TAINT how to make cursor visible after change? ### ( $ 'body' ).addClass 'cursor-hand' # ( $ app[ 'document' ] ).trigger 'mousemove' return mode #----------------------------------------------------------------------------------------------------------- MKTS.pop_tool_mode = -> debug '©2ryq9', app[ 'tool-modes' ] if app[ 'tool-modes' ].length < 1 R = app[ 'tool-modes-default' ] else R = app[ 'tool-modes' ].pop() ### TAINT must swap classes ### ( $ 'body' ).removeClass 'cursor-hand' return R #----------------------------------------------------------------------------------------------------------- MKTS.enable_console = ( selector = '#console' ) -> console = $ '#console' return unless console.length > 0 _write = process.stderr.write.bind process.stderr process.stderr.write = ( P... ) -> # process.stdout.write '***' + P[ 0 ] [ text, ... ] = P lines = ( text.replace /\n$/, '' ).split '\n' for line in lines console.append $ "<div>#{CND.ANSI.as_html text}</div>" console.stop().animate { scrollTop: ( $ '#console-bottom' ).offset()[ 'top' ] }, 500 # console.scrollTop ( $ '#console-bottom' ).offset()[ 'top' ] _write P... return null #----------------------------------------------------------------------------------------------------------- win.on 'zoom', -> MKTS.GAUGE.set_ratios app #----------------------------------------------------------------------------------------------------------- win.on 'document-end', -> # dev_win = win.showDevTools() # dev_win.moveTo 1200, 848 # dev_win.maximize() # dev_win.blur() #......................................................................................................... show_splash = no if show_splash after 2, -> win.show() splash_win.focus() after 3, -> win.focus() after 4, -> splash_win.hide() else splash_win.hide() win.show() win.focus() #......................................................................................................... app[ 'artboard' ] = $ 'artboard' app[ 'zoomer' ] = $ 'zoomer' MKTS.enable_console() step ( resume ) -> # MKTS.maximize app # MKTS.ZOOM.to app, 1.85 win.zoomLevel = 1 # MKTS.ZOOM.to app[ 'zoom' ] yield step.wrap ( $ document ).ready, resume help "document ready" #....................................................................................................... ### TAINT should be implicitly performed by MKTS.KEYS ### ( $ document ).keydown MKTS.KEYS.on_key.bind MKTS MKTS.INTERFACE.build() #......................................................................................................... return null ### { "name": "mingkwai" "main": "lib/index.html", "version": "0.1.0", "keywords": [ "node-webkit", "typesetting", "Chinese", "Japanese", "CJK", "typography" ], "chromium-args": "--enable-remote-fonts --enable-region-based-columns --enable-webkit-text-subpixel-positioning --enable-devtools-experiments --enable-experimental-web-platform-features --enable-smooth-scrolling --disable-accelerated-video --enable-webgl --enable-webaudio --ignore-gpu-blacklist --force-compositing-mode --remote-debugging-port=10138 --harmony", "single-instance": true, "no-edit-menu": false, "window": { "x": 0, "y": 20, "width": 1200, "height": 800, "show": false, "show_in_taskbar": true, "focus": false, "toolbar": true, "frame": true, "icon": "./favicon.ico", "position": "center", "title": "眀快排字机", "resizable": true }, "js-flags": "--harmony", "dependencies": { "applescript": "^1.0.0", "cnd": "^0.1.5", "coffeenode-chr": "^0.1.4", "coffeenode-suspend": "^0.1.4", "coffeenode-teacup": "^0.1.2", "linear-interpolator": "^1.0.2", "pipedreams": "^0.2.8", "stylus": "^0.49.3" } } ###
160905
############################################################################################################ njs_path = require 'path' njs_fs = require 'fs' #........................................................................................................... CND = require 'cnd' rpr = CND.rpr.bind CND badge = '眀快排字机/browser' log = CND.get_logger 'plain', badge info = CND.get_logger 'info', badge alert = CND.get_logger 'alert', badge debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge urge = CND.get_logger 'urge', badge whisper = CND.get_logger 'whisper', badge help = CND.get_logger 'help', badge echo = CND.echo.bind CND #........................................................................................................... NW = require 'nw.gui' win = NW.Window.get() #........................................................................................................... suspend = require 'coffeenode-suspend' step = suspend.step immediately = suspend.immediately after = suspend.after sleep = suspend.sleep #........................................................................................................... D = require 'pipedreams' D$ = D.remit.bind D CHR = require 'coffeenode-chr' #........................................................................................................... LINESETTER = require './LINESETTER' #........................................................................................................... ƒ = ( x, precision = 2 ) -> x.toFixed precision ### see https://github.com/nwjs/nw.js/wiki/Window ### splash_info = [ './splash.html', "position": "center", "title": "眀快排字机", "width": 800, "height": 500, "frame": false, "toolbar": false, "transparent": true, "focus": false, "resizable": false, "show": true, "show_in_taskbar": true, ] #----------------------------------------------------------------------------------------------------------- splash_win = NW.Window.open splash_info... #----------------------------------------------------------------------------------------------------------- ### Description of what is being typeset; the document. ### ### At some point in the future, maybe we'll be able to refer to the matter (document) and to locations inside the matter by using a URL like: mkts://#{file_locator}#page:#{page_nr}/column:#{column_nr}/y:#{insertion_y_px}px e.g. mkts://(file:///Users/dave/Documents/cv.mkts)/page:3/column:4/y:120.45px ### matter = '~isa': 'MKTS/matter' 'batch-idx': -1 'pages': [] 'caret': 'page-nr': 1 'column-nr': 1 'y.px': 0 #----------------------------------------------------------------------------------------------------------- ### Description of the app, its settings and its current user interface state. ### app = '~isa': 'MKTS/app' '%memo': {} ### TAINT populate with `MKTS.new_windows()` ### '%windows': 'main': win 'devtools': null 'splash': splash_win # 'mm-per-px': 100 / 377.94791 # 'mm-per-px': 55 / 203.704 # 'mm-per-px': 160 / 593 'gauge': null 'jQuery': $ 'NW': NW 'MKTS': null 'artboard': null 'window': window 'view-mode': 'dev' 'zoom-delta-factor': 1.25 'zoom': 1 'tool-modes': [] 'tool-modes-default': 'default' 'view': 'pages' 'matter': matter #----------------------------------------------------------------------------------------------------------- ### Publish app so we have access to it in both the browser and the NodeJS contexts: ### window[ 'app' ] = app #----------------------------------------------------------------------------------------------------------- MKTS = ( require './MKTS' ) app ### TAINT temporary fix: ### app[ 'MKTS' ] = MKTS app[ 'gauge' ] = MKTS.GAUGE.new app # win.zoomLevel = 0 # 100% # win.setResizable yes # win.resizeTo 1500, 1500 # win.setTransparent yes # ??? # win.showDevTools() # win.setProgressBar 0.5 # visible on dock icon # win.setBadgeLabel = 'helo from 眀快排字机' # ??? # help '©5t3', document.visibilityState # CND.dir win # help ( name for name of window).join ' ' # win.on 'blur', -> info 'blur' # win.on 'capturepagedone', -> info 'capturepagedone' win.on 'close', -> info 'close'; @close true # win.on 'closed', -> info 'closed' # win.on 'devtools-closed', -> info 'devtools-closed' # win.on 'devtools-opened', -> info 'devtools-opened' # win.on 'document-end', -> info 'document-end' # win.on 'document-start', -> info 'document-start' # win.on 'enter-fullscreen', -> info 'enter-fullscreen' # win.on 'focus', -> info 'focus' # win.on 'leave-fullscreen', -> info 'leave-fullscreen' # win.on 'loaded', -> info 'loaded' # win.on 'loading', -> info 'loading' # win.on 'maximize', -> info 'maximize' # win.on 'minimize', -> info 'minimize' # win.on 'move', -> info 'move' # win.on 'new-win-policy', -> info 'new-win-policy' # win.on 'resize', -> info 'resize' # win.on 'restore', -> info 'restore' # win.on 'unmaximize', -> info 'unmaximize' # win.on 'zoom', -> info 'zoom' # debug '©AfAsc', 'window.devicePixelRatio ', window.devicePixelRatio # debug '©AfAsc', 'window.devicePixelRatio ', window.devicePixelRatio # debug '©igYFq', 'window.screen.availTop ', window.screen.availTop # debug '©VUTiB', 'window.screen.availLeft ', window.screen.availLeft # debug '©o8v8T', 'window.screen.availHeight', window.screen.availHeight # debug '©Ubkrt', 'window.screen.availWidth ', window.screen.availWidth # debug '©zvq8U', 'window.screen.colorDepth ', window.screen.colorDepth # debug '©nH9a6', 'window.screen.height ', window.screen.height # debug '©YDbG3', 'window.screen.left ', window.screen.left # debug '©j0QXK', 'window.screen.orientation', window.screen.orientation # debug '©wEUqB', 'window.screen.pixelDepth ', window.screen.pixelDepth # debug '©G5QV3', 'window.screen.top ', window.screen.top # debug '©7Kqfv', 'window.screen.width ', window.screen.width # #----------------------------------------------------------------------------------------------------------- # win.on 'resize', -> # info "resized to #{win.width} x #{win.height}" # #----------------------------------------------------------------------------------------------------------- # win.on 'move', -> # info "moved to #{win.x}, #{win.y}" #----------------------------------------------------------------------------------------------------------- MKTS.get_document_size = ( me ) -> [ ( $ 'html' ).outerWidth(), ( $ 'html' ).outerHeight(), ] #----------------------------------------------------------------------------------------------------------- MKTS.maximize = ( app ) -> win.moveTo window.screen.availLeft, window.screen.availTop win.resizeTo window.screen.availWidth, window.screen.availHeight #----------------------------------------------------------------------------------------------------------- MKTS.wait = ( handler ) -> window.requestAnimationFrame -> handler() #----------------------------------------------------------------------------------------------------------- MKTS.take_screenshot = -> step ( resume ) => ### trying to wait for DOM reflow: ### # yield step.wrap window.requestAnimationFrame, resume yield MKTS.wait resume # help 'animation frame' img = yield MKTS._capture win, resume img_route = '/tmp/nw.png' yield njs_fs.writeFile img_route, img, resume help "image written to #{img_route}" #----------------------------------------------------------------------------------------------------------- MKTS.scroll_to = ( label ) -> # log '©Rafbc', ( $ '#bottom' ).offset ( $ 'html, body' ).stop().animate { scrollTop: ( $ label ).offset().top }, 500 #----------------------------------------------------------------------------------------------------------- MKTS.scroll_to_top = -> @scroll_to '#mkts-top' MKTS.scroll_to_bottom = -> @scroll_to '#mkts-bottom' #----------------------------------------------------------------------------------------------------------- MKTS._capture = ( win, handler ) -> win.capturePage ( ( img ) => handler null, img ), format: 'png', datatype: 'buffer' demo_count = 0 #----------------------------------------------------------------------------------------------------------- MKTS.demo = ( me ) -> debug '©iNl2F', 'demo' # source = """<em>Ab<xsmall>c</xsmall>d<xbig>e</xbig>ffiVA</em>""" # source = """Xxxxxxxxxxxxxxxx, she noticed xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx""" # source = """ # # Behind the Looking-Glass # 'But everything's curious today. I think I may as well go in at once.' And in # she went. # # Behind the Looking-Glass # Just as she said this, she noticed that one of the trees had a door # leading right into it. 'That's very curious!' she thought. 'But # everything's <xbig>curious</xbig> today. I think I may as well go in at once.' And in # she went. # 上古時期的越南語很可能具有南亞語系其他語言現在具有的一些共同特徵,例如在屈折方面較發達,具有豐富的複輔音等。這些特徵已不再存於現代的越南語中,據認為是由於越南語地處東南亞的“語言聯盟”中,受到周邊有聲調的孤立語的影響,也變成了一種有聲調的孤立語。形態上的孤立和聲調的存在可能並非來源自原始南亞語,周邊的無親屬關係的語言,例如壯侗語系的泰語和南島語系的回輝話,也都具有聲調。 # Just as shé said this, she fluffi *noticed* that # one of the trees had a door # leading right into it. 'That's very curious!' she thought. # Just as shé said this, she fluffi *noticed* that # one of the trees had a door # leading right into it. 'That's very curious!' she thought. # Just as shé said this, she fluffi *noticed* that # one of the trees had a door # leading right into it. 'That's very curious!' she thought. # Just as shé said this, she fluffi *noticed* that # one of the trees had a door # leading right into it. 'That's very curious!' she thought. # """ # source = "one <xbig>line</xbig>\n\n" + source[ .. 500 ] + ( 'ddd' for i in [ 0 .. 150 ] ).join ' ' # demo_count += +1 # if demo_count is 1 # source = """ # # Test # just a **test**. *ffi*. abcdefghijklm Q Qu Queen the most unbelievable story.""" # debug '©uvL5t', source.length # source = "Just as shé said this, she fluffi *noticed* that abc def ghi jkl mno pqr stu vwx xy" source = """ 'But everything's curious today. I think I may as well go in at once.' And in she went.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx and so on. bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb Short paragraph. """ # supercalifragilisticexpialigoricalsupercalifragilisticexpialigorical # Sedutperspiciatisundeomnisistenatuserrorsitvoluptatemaccusantiumdoloremquelaudantium,totamremaperiam,eaqueipsaquaeabilloinventoreveritatisetquasiarchitectobeataevitaedicta sunt explicabo. # # Behind the Looking-Glass # The King and Queen of Hearts were <xbig>seated</xbig> on their throne when they # arrived, with a great crowd assembled about them--all sorts of little # birds and beasts. # There was nothing so VERY remarkable in that; nor did <NAME> think it so # VERY much out of the way to hear the Rabbit say to itself, 'Oh dear! # Oh dear! I shall be late!' (when she thought it over afterwards, it # occurred to her that she ought to have wondered at this, but at the time # it all seemed quite natural); but when the Rabbit actually TOOK A WATCH # OUT OF ITS WAISTCOAT-POCKET, and looked at it, and then hurried on, # <NAME> started to her feet, for it flashed across her mind that she had # never before seen a rabbit with either a waistcoat-pocket, or a watch # to take out of it, and burning with curiosity, she ran across the field # after it, and fortunately was just in time to see it pop down a large # rabbit-hole under the hedge. # 'Come, there's no use in crying like that!' said <NAME> to herself, # rather sharply; 'I advise you to leave off this minute!' She generally # gave herself very good advice, (though she very seldom followed it), # and sometimes she scolded herself so severely as to bring tears into # her eyes; and once she remembered trying to box her own ears for having # cheated herself in a game of croquet she was playing against herself, # for this curious child was very fond of pretending to be two people. # 'But it's no use now,' thought poor <NAME>, 'to pretend to be two people! # Why, there's hardly enough of me left to make ONE respectable person!' # source = """ # <kwic-lineup>1 中國皇帝</kwic-lineup> # <kwic-lineup>2 中國皇帝</kwic-lineup> # <kwic-lineup>3 中國皇帝</kwic-lineup> # <kwic-lineup>4 中國皇帝</kwic-lineup> # <kwic-lineup>5 中國皇帝</kwic-lineup> # <kwic-lineup>6 中國皇帝</kwic-lineup> # <kwic-lineup>7 中國皇帝</kwic-lineup> # <kwic-lineup>8 中國皇帝</kwic-lineup> # <kwic-lineup>9 中國皇帝</kwic-lineup> # <kwic-lineup>10 中國皇帝</kwic-lineup> # <kwic-lineup>11 中國皇帝</kwic-lineup> # <kwic-lineup>12 中國皇帝</kwic-lineup> # <kwic-lineup>13 中國皇帝</kwic-lineup> # <kwic-lineup>14 中國皇帝</kwic-lineup> # <kwic-lineup>15 中國皇帝</kwic-lineup> # <kwic-lineup>16 中國皇帝</kwic-lineup> # <kwic-lineup>17 中國皇帝</kwic-lineup> # <kwic-lineup>18 中國皇帝</kwic-lineup> # <kwic-lineup>19 中國皇帝</kwic-lineup> # <kwic-lineup>20 中國皇帝</kwic-lineup> # <kwic-lineup>21 中國皇帝</kwic-lineup> # <kwic-lineup>22 中國皇帝</kwic-lineup> # <kwic-lineup>23 中國皇帝</kwic-lineup> # <kwic-lineup>24 中國皇帝</kwic-lineup> # <kwic-lineup>25 中國皇帝</kwic-lineup> # <kwic-lineup>26 中國皇帝</kwic-lineup> # <kwic-lineup>27 中國皇帝</kwic-lineup> # <kwic-lineup>28 中國皇帝</kwic-lineup> # <kwic-lineup>29 中國皇帝</kwic-lineup> # <kwic-lineup>30 中國皇帝</kwic-lineup> # <kwic-lineup>31 中國皇帝</kwic-lineup> # <kwic-lineup>32 中國皇帝</kwic-lineup> # <kwic-lineup>33 中國皇帝</kwic-lineup> # <kwic-lineup>34 中國皇帝</kwic-lineup> # <kwic-lineup>35 中國皇帝</kwic-lineup> # <kwic-lineup>36 中國皇帝</kwic-lineup> # <kwic-lineup>37 中國皇帝</kwic-lineup> # <kwic-lineup>38 中國皇帝</kwic-lineup> # <kwic-lineup>39 中國皇帝</kwic-lineup> # <kwic-lineup>40 中國皇帝</kwic-lineup> # <kwic-lineup>41 中國皇帝</kwic-lineup> # <kwic-lineup>42 中國皇帝</kwic-lineup> # <kwic-lineup>43 中國皇帝</kwic-lineup> # <kwic-lineup>44 中國皇帝</kwic-lineup> # <kwic-lineup>45 中國皇帝</kwic-lineup> # <kwic-lineup>46 中國皇帝</kwic-lineup> # <kwic-lineup>47 中國皇帝</kwic-lineup> # <kwic-lineup>48 中國皇帝</kwic-lineup> # <kwic-lineup>49 中國皇帝</kwic-lineup> # <kwic-lineup>50 中國皇帝</kwic-lineup> # <kwic-lineup>51 中國皇帝</kwic-lineup> # <kwic-lineup>52 中國皇帝</kwic-lineup> # <kwic-lineup>53 中國皇帝</kwic-lineup> # <kwic-lineup>54 中國皇帝</kwic-lineup> # <kwic-lineup>55 中國皇帝</kwic-lineup> # <kwic-lineup>56 中國皇帝</kwic-lineup> # <kwic-lineup>57 中國皇帝</kwic-lineup> # <kwic-lineup>58 中國皇帝</kwic-lineup> # <kwic-lineup>59 中國皇帝</kwic-lineup> # <kwic-lineup>60 中國皇帝</kwic-lineup> # <kwic-lineup>61 中國皇帝</kwic-lineup> # <kwic-lineup>62 中國皇帝</kwic-lineup> # <kwic-lineup>63 中國皇帝</kwic-lineup> # <kwic-lineup>64 中國皇帝</kwic-lineup> # <kwic-lineup>65 中國皇帝</kwic-lineup> # <kwic-lineup>66 中國皇帝</kwic-lineup> # <kwic-lineup>67 中國皇帝</kwic-lineup> # <kwic-lineup>68 中國皇帝</kwic-lineup> # """ # source = require './demo-text' # source = njs_fs.readFileSync '/tmp/kwic.html', encoding: 'utf-8' # source = ( ( if line.length is 0 or line is '```' then line else "#{line}<!--##{idx}-->" ) for line, idx in source.split '\n' ).join '\n' help "source: approx. #{source.length} characters" settings = # 'format': 'html' 'format': 'md' step ( resume ) => # yield MKTS.VIEW.show_galley resume yield LINESETTER.demo me, source, settings, resume # MKTS.revert_zoom me help "MKTS.demo ok" return null ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### #----------------------------------------------------------------------------------------------------------- MKTS.toggle_tool_mode = ( mode ) -> return @pop_tool_mode() if ( CND.last_of app[ 'tool-modes' ] ) is mode return @push_tool_mode mode #----------------------------------------------------------------------------------------------------------- MKTS.push_tool_mode = ( mode ) -> debug '©2ryq9', app[ 'tool-modes' ] app[ 'tool-modes' ].push mode unless ( CND.last_of app[ 'tool-modes' ] ) is mode app[ 'tool-modes' ].shift() if app[ 'tool-modes' ].length > 10 # ( $ 'body' ).css 'cursor', 'url(./icons/mkts-tool-hand.png)' # ( $ 'body' ).attr 'style', 'cursor:url(./icons/mkts-tool-hand-cursor.png), auto;' ### TAINT must swap classes ### ### TAINT how to make cursor visible after change? ### ( $ 'body' ).addClass 'cursor-hand' # ( $ app[ 'document' ] ).trigger 'mousemove' return mode #----------------------------------------------------------------------------------------------------------- MKTS.pop_tool_mode = -> debug '©2ryq9', app[ 'tool-modes' ] if app[ 'tool-modes' ].length < 1 R = app[ 'tool-modes-default' ] else R = app[ 'tool-modes' ].pop() ### TAINT must swap classes ### ( $ 'body' ).removeClass 'cursor-hand' return R #----------------------------------------------------------------------------------------------------------- MKTS.enable_console = ( selector = '#console' ) -> console = $ '#console' return unless console.length > 0 _write = process.stderr.write.bind process.stderr process.stderr.write = ( P... ) -> # process.stdout.write '***' + P[ 0 ] [ text, ... ] = P lines = ( text.replace /\n$/, '' ).split '\n' for line in lines console.append $ "<div>#{CND.ANSI.as_html text}</div>" console.stop().animate { scrollTop: ( $ '#console-bottom' ).offset()[ 'top' ] }, 500 # console.scrollTop ( $ '#console-bottom' ).offset()[ 'top' ] _write P... return null #----------------------------------------------------------------------------------------------------------- win.on 'zoom', -> MKTS.GAUGE.set_ratios app #----------------------------------------------------------------------------------------------------------- win.on 'document-end', -> # dev_win = win.showDevTools() # dev_win.moveTo 1200, 848 # dev_win.maximize() # dev_win.blur() #......................................................................................................... show_splash = no if show_splash after 2, -> win.show() splash_win.focus() after 3, -> win.focus() after 4, -> splash_win.hide() else splash_win.hide() win.show() win.focus() #......................................................................................................... app[ 'artboard' ] = $ 'artboard' app[ 'zoomer' ] = $ 'zoomer' MKTS.enable_console() step ( resume ) -> # MKTS.maximize app # MKTS.ZOOM.to app, 1.85 win.zoomLevel = 1 # MKTS.ZOOM.to app[ 'zoom' ] yield step.wrap ( $ document ).ready, resume help "document ready" #....................................................................................................... ### TAINT should be implicitly performed by MKTS.KEYS ### ( $ document ).keydown MKTS.KEYS.on_key.bind MKTS MKTS.INTERFACE.build() #......................................................................................................... return null ### { "name": "mingkwai" "main": "lib/index.html", "version": "0.1.0", "keywords": [ "node-webkit", "typesetting", "Chinese", "Japanese", "CJK", "typography" ], "chromium-args": "--enable-remote-fonts --enable-region-based-columns --enable-webkit-text-subpixel-positioning --enable-devtools-experiments --enable-experimental-web-platform-features --enable-smooth-scrolling --disable-accelerated-video --enable-webgl --enable-webaudio --ignore-gpu-blacklist --force-compositing-mode --remote-debugging-port=10138 --harmony", "single-instance": true, "no-edit-menu": false, "window": { "x": 0, "y": 20, "width": 1200, "height": 800, "show": false, "show_in_taskbar": true, "focus": false, "toolbar": true, "frame": true, "icon": "./favicon.ico", "position": "center", "title": "眀快排字机", "resizable": true }, "js-flags": "--harmony", "dependencies": { "applescript": "^1.0.0", "cnd": "^0.1.5", "coffeenode-chr": "^0.1.4", "coffeenode-suspend": "^0.1.4", "coffeenode-teacup": "^0.1.2", "linear-interpolator": "^1.0.2", "pipedreams": "^0.2.8", "stylus": "^0.49.3" } } ###
true
############################################################################################################ njs_path = require 'path' njs_fs = require 'fs' #........................................................................................................... CND = require 'cnd' rpr = CND.rpr.bind CND badge = '眀快排字机/browser' log = CND.get_logger 'plain', badge info = CND.get_logger 'info', badge alert = CND.get_logger 'alert', badge debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge urge = CND.get_logger 'urge', badge whisper = CND.get_logger 'whisper', badge help = CND.get_logger 'help', badge echo = CND.echo.bind CND #........................................................................................................... NW = require 'nw.gui' win = NW.Window.get() #........................................................................................................... suspend = require 'coffeenode-suspend' step = suspend.step immediately = suspend.immediately after = suspend.after sleep = suspend.sleep #........................................................................................................... D = require 'pipedreams' D$ = D.remit.bind D CHR = require 'coffeenode-chr' #........................................................................................................... LINESETTER = require './LINESETTER' #........................................................................................................... ƒ = ( x, precision = 2 ) -> x.toFixed precision ### see https://github.com/nwjs/nw.js/wiki/Window ### splash_info = [ './splash.html', "position": "center", "title": "眀快排字机", "width": 800, "height": 500, "frame": false, "toolbar": false, "transparent": true, "focus": false, "resizable": false, "show": true, "show_in_taskbar": true, ] #----------------------------------------------------------------------------------------------------------- splash_win = NW.Window.open splash_info... #----------------------------------------------------------------------------------------------------------- ### Description of what is being typeset; the document. ### ### At some point in the future, maybe we'll be able to refer to the matter (document) and to locations inside the matter by using a URL like: mkts://#{file_locator}#page:#{page_nr}/column:#{column_nr}/y:#{insertion_y_px}px e.g. mkts://(file:///Users/dave/Documents/cv.mkts)/page:3/column:4/y:120.45px ### matter = '~isa': 'MKTS/matter' 'batch-idx': -1 'pages': [] 'caret': 'page-nr': 1 'column-nr': 1 'y.px': 0 #----------------------------------------------------------------------------------------------------------- ### Description of the app, its settings and its current user interface state. ### app = '~isa': 'MKTS/app' '%memo': {} ### TAINT populate with `MKTS.new_windows()` ### '%windows': 'main': win 'devtools': null 'splash': splash_win # 'mm-per-px': 100 / 377.94791 # 'mm-per-px': 55 / 203.704 # 'mm-per-px': 160 / 593 'gauge': null 'jQuery': $ 'NW': NW 'MKTS': null 'artboard': null 'window': window 'view-mode': 'dev' 'zoom-delta-factor': 1.25 'zoom': 1 'tool-modes': [] 'tool-modes-default': 'default' 'view': 'pages' 'matter': matter #----------------------------------------------------------------------------------------------------------- ### Publish app so we have access to it in both the browser and the NodeJS contexts: ### window[ 'app' ] = app #----------------------------------------------------------------------------------------------------------- MKTS = ( require './MKTS' ) app ### TAINT temporary fix: ### app[ 'MKTS' ] = MKTS app[ 'gauge' ] = MKTS.GAUGE.new app # win.zoomLevel = 0 # 100% # win.setResizable yes # win.resizeTo 1500, 1500 # win.setTransparent yes # ??? # win.showDevTools() # win.setProgressBar 0.5 # visible on dock icon # win.setBadgeLabel = 'helo from 眀快排字机' # ??? # help '©5t3', document.visibilityState # CND.dir win # help ( name for name of window).join ' ' # win.on 'blur', -> info 'blur' # win.on 'capturepagedone', -> info 'capturepagedone' win.on 'close', -> info 'close'; @close true # win.on 'closed', -> info 'closed' # win.on 'devtools-closed', -> info 'devtools-closed' # win.on 'devtools-opened', -> info 'devtools-opened' # win.on 'document-end', -> info 'document-end' # win.on 'document-start', -> info 'document-start' # win.on 'enter-fullscreen', -> info 'enter-fullscreen' # win.on 'focus', -> info 'focus' # win.on 'leave-fullscreen', -> info 'leave-fullscreen' # win.on 'loaded', -> info 'loaded' # win.on 'loading', -> info 'loading' # win.on 'maximize', -> info 'maximize' # win.on 'minimize', -> info 'minimize' # win.on 'move', -> info 'move' # win.on 'new-win-policy', -> info 'new-win-policy' # win.on 'resize', -> info 'resize' # win.on 'restore', -> info 'restore' # win.on 'unmaximize', -> info 'unmaximize' # win.on 'zoom', -> info 'zoom' # debug '©AfAsc', 'window.devicePixelRatio ', window.devicePixelRatio # debug '©AfAsc', 'window.devicePixelRatio ', window.devicePixelRatio # debug '©igYFq', 'window.screen.availTop ', window.screen.availTop # debug '©VUTiB', 'window.screen.availLeft ', window.screen.availLeft # debug '©o8v8T', 'window.screen.availHeight', window.screen.availHeight # debug '©Ubkrt', 'window.screen.availWidth ', window.screen.availWidth # debug '©zvq8U', 'window.screen.colorDepth ', window.screen.colorDepth # debug '©nH9a6', 'window.screen.height ', window.screen.height # debug '©YDbG3', 'window.screen.left ', window.screen.left # debug '©j0QXK', 'window.screen.orientation', window.screen.orientation # debug '©wEUqB', 'window.screen.pixelDepth ', window.screen.pixelDepth # debug '©G5QV3', 'window.screen.top ', window.screen.top # debug '©7Kqfv', 'window.screen.width ', window.screen.width # #----------------------------------------------------------------------------------------------------------- # win.on 'resize', -> # info "resized to #{win.width} x #{win.height}" # #----------------------------------------------------------------------------------------------------------- # win.on 'move', -> # info "moved to #{win.x}, #{win.y}" #----------------------------------------------------------------------------------------------------------- MKTS.get_document_size = ( me ) -> [ ( $ 'html' ).outerWidth(), ( $ 'html' ).outerHeight(), ] #----------------------------------------------------------------------------------------------------------- MKTS.maximize = ( app ) -> win.moveTo window.screen.availLeft, window.screen.availTop win.resizeTo window.screen.availWidth, window.screen.availHeight #----------------------------------------------------------------------------------------------------------- MKTS.wait = ( handler ) -> window.requestAnimationFrame -> handler() #----------------------------------------------------------------------------------------------------------- MKTS.take_screenshot = -> step ( resume ) => ### trying to wait for DOM reflow: ### # yield step.wrap window.requestAnimationFrame, resume yield MKTS.wait resume # help 'animation frame' img = yield MKTS._capture win, resume img_route = '/tmp/nw.png' yield njs_fs.writeFile img_route, img, resume help "image written to #{img_route}" #----------------------------------------------------------------------------------------------------------- MKTS.scroll_to = ( label ) -> # log '©Rafbc', ( $ '#bottom' ).offset ( $ 'html, body' ).stop().animate { scrollTop: ( $ label ).offset().top }, 500 #----------------------------------------------------------------------------------------------------------- MKTS.scroll_to_top = -> @scroll_to '#mkts-top' MKTS.scroll_to_bottom = -> @scroll_to '#mkts-bottom' #----------------------------------------------------------------------------------------------------------- MKTS._capture = ( win, handler ) -> win.capturePage ( ( img ) => handler null, img ), format: 'png', datatype: 'buffer' demo_count = 0 #----------------------------------------------------------------------------------------------------------- MKTS.demo = ( me ) -> debug '©iNl2F', 'demo' # source = """<em>Ab<xsmall>c</xsmall>d<xbig>e</xbig>ffiVA</em>""" # source = """Xxxxxxxxxxxxxxxx, she noticed xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx""" # source = """ # # Behind the Looking-Glass # 'But everything's curious today. I think I may as well go in at once.' And in # she went. # # Behind the Looking-Glass # Just as she said this, she noticed that one of the trees had a door # leading right into it. 'That's very curious!' she thought. 'But # everything's <xbig>curious</xbig> today. I think I may as well go in at once.' And in # she went. # 上古時期的越南語很可能具有南亞語系其他語言現在具有的一些共同特徵,例如在屈折方面較發達,具有豐富的複輔音等。這些特徵已不再存於現代的越南語中,據認為是由於越南語地處東南亞的“語言聯盟”中,受到周邊有聲調的孤立語的影響,也變成了一種有聲調的孤立語。形態上的孤立和聲調的存在可能並非來源自原始南亞語,周邊的無親屬關係的語言,例如壯侗語系的泰語和南島語系的回輝話,也都具有聲調。 # Just as shé said this, she fluffi *noticed* that # one of the trees had a door # leading right into it. 'That's very curious!' she thought. # Just as shé said this, she fluffi *noticed* that # one of the trees had a door # leading right into it. 'That's very curious!' she thought. # Just as shé said this, she fluffi *noticed* that # one of the trees had a door # leading right into it. 'That's very curious!' she thought. # Just as shé said this, she fluffi *noticed* that # one of the trees had a door # leading right into it. 'That's very curious!' she thought. # """ # source = "one <xbig>line</xbig>\n\n" + source[ .. 500 ] + ( 'ddd' for i in [ 0 .. 150 ] ).join ' ' # demo_count += +1 # if demo_count is 1 # source = """ # # Test # just a **test**. *ffi*. abcdefghijklm Q Qu Queen the most unbelievable story.""" # debug '©uvL5t', source.length # source = "Just as shé said this, she fluffi *noticed* that abc def ghi jkl mno pqr stu vwx xy" source = """ 'But everything's curious today. I think I may as well go in at once.' And in she went.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx and so on. bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb Short paragraph. """ # supercalifragilisticexpialigoricalsupercalifragilisticexpialigorical # Sedutperspiciatisundeomnisistenatuserrorsitvoluptatemaccusantiumdoloremquelaudantium,totamremaperiam,eaqueipsaquaeabilloinventoreveritatisetquasiarchitectobeataevitaedicta sunt explicabo. # # Behind the Looking-Glass # The King and Queen of Hearts were <xbig>seated</xbig> on their throne when they # arrived, with a great crowd assembled about them--all sorts of little # birds and beasts. # There was nothing so VERY remarkable in that; nor did PI:NAME:<NAME>END_PI think it so # VERY much out of the way to hear the Rabbit say to itself, 'Oh dear! # Oh dear! I shall be late!' (when she thought it over afterwards, it # occurred to her that she ought to have wondered at this, but at the time # it all seemed quite natural); but when the Rabbit actually TOOK A WATCH # OUT OF ITS WAISTCOAT-POCKET, and looked at it, and then hurried on, # PI:NAME:<NAME>END_PI started to her feet, for it flashed across her mind that she had # never before seen a rabbit with either a waistcoat-pocket, or a watch # to take out of it, and burning with curiosity, she ran across the field # after it, and fortunately was just in time to see it pop down a large # rabbit-hole under the hedge. # 'Come, there's no use in crying like that!' said PI:NAME:<NAME>END_PI to herself, # rather sharply; 'I advise you to leave off this minute!' She generally # gave herself very good advice, (though she very seldom followed it), # and sometimes she scolded herself so severely as to bring tears into # her eyes; and once she remembered trying to box her own ears for having # cheated herself in a game of croquet she was playing against herself, # for this curious child was very fond of pretending to be two people. # 'But it's no use now,' thought poor PI:NAME:<NAME>END_PI, 'to pretend to be two people! # Why, there's hardly enough of me left to make ONE respectable person!' # source = """ # <kwic-lineup>1 中國皇帝</kwic-lineup> # <kwic-lineup>2 中國皇帝</kwic-lineup> # <kwic-lineup>3 中國皇帝</kwic-lineup> # <kwic-lineup>4 中國皇帝</kwic-lineup> # <kwic-lineup>5 中國皇帝</kwic-lineup> # <kwic-lineup>6 中國皇帝</kwic-lineup> # <kwic-lineup>7 中國皇帝</kwic-lineup> # <kwic-lineup>8 中國皇帝</kwic-lineup> # <kwic-lineup>9 中國皇帝</kwic-lineup> # <kwic-lineup>10 中國皇帝</kwic-lineup> # <kwic-lineup>11 中國皇帝</kwic-lineup> # <kwic-lineup>12 中國皇帝</kwic-lineup> # <kwic-lineup>13 中國皇帝</kwic-lineup> # <kwic-lineup>14 中國皇帝</kwic-lineup> # <kwic-lineup>15 中國皇帝</kwic-lineup> # <kwic-lineup>16 中國皇帝</kwic-lineup> # <kwic-lineup>17 中國皇帝</kwic-lineup> # <kwic-lineup>18 中國皇帝</kwic-lineup> # <kwic-lineup>19 中國皇帝</kwic-lineup> # <kwic-lineup>20 中國皇帝</kwic-lineup> # <kwic-lineup>21 中國皇帝</kwic-lineup> # <kwic-lineup>22 中國皇帝</kwic-lineup> # <kwic-lineup>23 中國皇帝</kwic-lineup> # <kwic-lineup>24 中國皇帝</kwic-lineup> # <kwic-lineup>25 中國皇帝</kwic-lineup> # <kwic-lineup>26 中國皇帝</kwic-lineup> # <kwic-lineup>27 中國皇帝</kwic-lineup> # <kwic-lineup>28 中國皇帝</kwic-lineup> # <kwic-lineup>29 中國皇帝</kwic-lineup> # <kwic-lineup>30 中國皇帝</kwic-lineup> # <kwic-lineup>31 中國皇帝</kwic-lineup> # <kwic-lineup>32 中國皇帝</kwic-lineup> # <kwic-lineup>33 中國皇帝</kwic-lineup> # <kwic-lineup>34 中國皇帝</kwic-lineup> # <kwic-lineup>35 中國皇帝</kwic-lineup> # <kwic-lineup>36 中國皇帝</kwic-lineup> # <kwic-lineup>37 中國皇帝</kwic-lineup> # <kwic-lineup>38 中國皇帝</kwic-lineup> # <kwic-lineup>39 中國皇帝</kwic-lineup> # <kwic-lineup>40 中國皇帝</kwic-lineup> # <kwic-lineup>41 中國皇帝</kwic-lineup> # <kwic-lineup>42 中國皇帝</kwic-lineup> # <kwic-lineup>43 中國皇帝</kwic-lineup> # <kwic-lineup>44 中國皇帝</kwic-lineup> # <kwic-lineup>45 中國皇帝</kwic-lineup> # <kwic-lineup>46 中國皇帝</kwic-lineup> # <kwic-lineup>47 中國皇帝</kwic-lineup> # <kwic-lineup>48 中國皇帝</kwic-lineup> # <kwic-lineup>49 中國皇帝</kwic-lineup> # <kwic-lineup>50 中國皇帝</kwic-lineup> # <kwic-lineup>51 中國皇帝</kwic-lineup> # <kwic-lineup>52 中國皇帝</kwic-lineup> # <kwic-lineup>53 中國皇帝</kwic-lineup> # <kwic-lineup>54 中國皇帝</kwic-lineup> # <kwic-lineup>55 中國皇帝</kwic-lineup> # <kwic-lineup>56 中國皇帝</kwic-lineup> # <kwic-lineup>57 中國皇帝</kwic-lineup> # <kwic-lineup>58 中國皇帝</kwic-lineup> # <kwic-lineup>59 中國皇帝</kwic-lineup> # <kwic-lineup>60 中國皇帝</kwic-lineup> # <kwic-lineup>61 中國皇帝</kwic-lineup> # <kwic-lineup>62 中國皇帝</kwic-lineup> # <kwic-lineup>63 中國皇帝</kwic-lineup> # <kwic-lineup>64 中國皇帝</kwic-lineup> # <kwic-lineup>65 中國皇帝</kwic-lineup> # <kwic-lineup>66 中國皇帝</kwic-lineup> # <kwic-lineup>67 中國皇帝</kwic-lineup> # <kwic-lineup>68 中國皇帝</kwic-lineup> # """ # source = require './demo-text' # source = njs_fs.readFileSync '/tmp/kwic.html', encoding: 'utf-8' # source = ( ( if line.length is 0 or line is '```' then line else "#{line}<!--##{idx}-->" ) for line, idx in source.split '\n' ).join '\n' help "source: approx. #{source.length} characters" settings = # 'format': 'html' 'format': 'md' step ( resume ) => # yield MKTS.VIEW.show_galley resume yield LINESETTER.demo me, source, settings, resume # MKTS.revert_zoom me help "MKTS.demo ok" return null ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### ### # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ### #----------------------------------------------------------------------------------------------------------- MKTS.toggle_tool_mode = ( mode ) -> return @pop_tool_mode() if ( CND.last_of app[ 'tool-modes' ] ) is mode return @push_tool_mode mode #----------------------------------------------------------------------------------------------------------- MKTS.push_tool_mode = ( mode ) -> debug '©2ryq9', app[ 'tool-modes' ] app[ 'tool-modes' ].push mode unless ( CND.last_of app[ 'tool-modes' ] ) is mode app[ 'tool-modes' ].shift() if app[ 'tool-modes' ].length > 10 # ( $ 'body' ).css 'cursor', 'url(./icons/mkts-tool-hand.png)' # ( $ 'body' ).attr 'style', 'cursor:url(./icons/mkts-tool-hand-cursor.png), auto;' ### TAINT must swap classes ### ### TAINT how to make cursor visible after change? ### ( $ 'body' ).addClass 'cursor-hand' # ( $ app[ 'document' ] ).trigger 'mousemove' return mode #----------------------------------------------------------------------------------------------------------- MKTS.pop_tool_mode = -> debug '©2ryq9', app[ 'tool-modes' ] if app[ 'tool-modes' ].length < 1 R = app[ 'tool-modes-default' ] else R = app[ 'tool-modes' ].pop() ### TAINT must swap classes ### ( $ 'body' ).removeClass 'cursor-hand' return R #----------------------------------------------------------------------------------------------------------- MKTS.enable_console = ( selector = '#console' ) -> console = $ '#console' return unless console.length > 0 _write = process.stderr.write.bind process.stderr process.stderr.write = ( P... ) -> # process.stdout.write '***' + P[ 0 ] [ text, ... ] = P lines = ( text.replace /\n$/, '' ).split '\n' for line in lines console.append $ "<div>#{CND.ANSI.as_html text}</div>" console.stop().animate { scrollTop: ( $ '#console-bottom' ).offset()[ 'top' ] }, 500 # console.scrollTop ( $ '#console-bottom' ).offset()[ 'top' ] _write P... return null #----------------------------------------------------------------------------------------------------------- win.on 'zoom', -> MKTS.GAUGE.set_ratios app #----------------------------------------------------------------------------------------------------------- win.on 'document-end', -> # dev_win = win.showDevTools() # dev_win.moveTo 1200, 848 # dev_win.maximize() # dev_win.blur() #......................................................................................................... show_splash = no if show_splash after 2, -> win.show() splash_win.focus() after 3, -> win.focus() after 4, -> splash_win.hide() else splash_win.hide() win.show() win.focus() #......................................................................................................... app[ 'artboard' ] = $ 'artboard' app[ 'zoomer' ] = $ 'zoomer' MKTS.enable_console() step ( resume ) -> # MKTS.maximize app # MKTS.ZOOM.to app, 1.85 win.zoomLevel = 1 # MKTS.ZOOM.to app[ 'zoom' ] yield step.wrap ( $ document ).ready, resume help "document ready" #....................................................................................................... ### TAINT should be implicitly performed by MKTS.KEYS ### ( $ document ).keydown MKTS.KEYS.on_key.bind MKTS MKTS.INTERFACE.build() #......................................................................................................... return null ### { "name": "mingkwai" "main": "lib/index.html", "version": "0.1.0", "keywords": [ "node-webkit", "typesetting", "Chinese", "Japanese", "CJK", "typography" ], "chromium-args": "--enable-remote-fonts --enable-region-based-columns --enable-webkit-text-subpixel-positioning --enable-devtools-experiments --enable-experimental-web-platform-features --enable-smooth-scrolling --disable-accelerated-video --enable-webgl --enable-webaudio --ignore-gpu-blacklist --force-compositing-mode --remote-debugging-port=10138 --harmony", "single-instance": true, "no-edit-menu": false, "window": { "x": 0, "y": 20, "width": 1200, "height": 800, "show": false, "show_in_taskbar": true, "focus": false, "toolbar": true, "frame": true, "icon": "./favicon.ico", "position": "center", "title": "眀快排字机", "resizable": true }, "js-flags": "--harmony", "dependencies": { "applescript": "^1.0.0", "cnd": "^0.1.5", "coffeenode-chr": "^0.1.4", "coffeenode-suspend": "^0.1.4", "coffeenode-teacup": "^0.1.2", "linear-interpolator": "^1.0.2", "pipedreams": "^0.2.8", "stylus": "^0.49.3" } } ###
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999150037765503, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" }, { "context": " an explicit data type.\n# ref: https://github.com/jquery/jquery/blob/b078a62013782c7424a4a61a240c23c4c0b42", "end": 397, "score": 0.9592266082763672, "start": 391, "tag": "USERNAME", "value": "jquery" } ]
resources/assets/coffee/jquery-prefilter.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. # Prefilter to disable parsing of cross-domain scripts loaded via jQuery. # jQuery's autodection means responses with text/javascript get eval'ed if # fetched without an explicit data type. # ref: https://github.com/jquery/jquery/blob/b078a62013782c7424a4a61a240c23c4c0b42614/src/ajax/script.js#L8-L12 $.ajaxPrefilter (options) -> options.contents.script = false if options.crossDomain
107942
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. # Prefilter to disable parsing of cross-domain scripts loaded via jQuery. # jQuery's autodection means responses with text/javascript get eval'ed if # fetched without an explicit data type. # ref: https://github.com/jquery/jquery/blob/b078a62013782c7424a4a61a240c23c4c0b42614/src/ajax/script.js#L8-L12 $.ajaxPrefilter (options) -> options.contents.script = false if options.crossDomain
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. # Prefilter to disable parsing of cross-domain scripts loaded via jQuery. # jQuery's autodection means responses with text/javascript get eval'ed if # fetched without an explicit data type. # ref: https://github.com/jquery/jquery/blob/b078a62013782c7424a4a61a240c23c4c0b42614/src/ajax/script.js#L8-L12 $.ajaxPrefilter (options) -> options.contents.script = false if options.crossDomain
[ { "context": "# @example \n# ```coffeescript\n# key = new Buffer \"pitying web andiron impacts bought\"\n# data = new Buffer \"this is my secret data\"\n# e", "end": 10880, "score": 0.8500510454177856, "start": 10846, "tag": "KEY", "value": "pitying web andiron impacts bought" } ]
node_modules/triplesec/src/enc.iced
gallizoltan/warpwallet
157
{WordArray} = require './wordarray' salsa20 = require './salsa20' {AES} = require './aes' {TwoFish} = require './twofish' ctr = require './ctr' {XOR,Concat} = require './combine' {SHA512} = require './sha512' {PBKDF2} = require './pbkdf2' {Scrypt} = require './scrypt' util = require './util' prng = require './prng' {make_esc} = require 'iced-error' {HMAC_SHA256} = require './hmac' #======================================================================== # @property {Object} V A lookup table of all supported versions. V = "1" : header : [ 0x1c94d7de, 1 ] # The magic #, and also the version # salt_size : 8 # 8 bytes of salt is good enough! xsalsa20_rev : true # XSalsa20 Endian Reverse kdf : # The key derivation... klass : PBKDF2 # algorithm klass opts : # ..and options c : 1024 # The number of iterations klass : XOR # The HMAC to use as a subroutine hmac_key_size : 768/8 # The size of the key to split over the two HMACs. "2" : header : [ 0x1c94d7de, 2 ] # The magic #, and also the version # salt_size : 16 # 16 bytes of salt for various uses xsalsa20_rev : true # XSalsa20 Endian Reverse kdf : # The key derivation... klass : Scrypt # algorithm klass opts : # ..and options c : 64 # The number of iterations klass : XOR # The HMAC to use as a subroutine N : 12 # log_2 of the work factor r : 8 # The memory use factor p : 1 # the parallelization factor hmac_key_size : 768/8 # The size of the key to split over the two HMACs. "3" : header : [ 0x1c94d7de, 3 ] # The magic #, and also the version # salt_size : 16 # 16 bytes of salt for various uses xsalsa20_rev : false # XSalsa20 Endian Reverse kdf : # The key derivation... klass : Scrypt # algorithm klass opts : # ..and options c : 1 # The number of iterations klass : HMAC_SHA256 # The HMAC to use as a subroutine N : 16 # log_2 of the work factor r : 8 # The memory use factor p : 1 # the parallelization factor hmac_key_size : 768/8 # The size of the key to split over the two HMACs. #======================================================================== # A base class for the {Encryptor} and {Decryptor} classes. # Handles a lot of the particulars of signing, key generation, # and encryption/decryption. class Base #--------------- # @param {WordArray} key The private encryption key constructor : ( { key, version } ) -> @version = V[if version? then version else 1] throw new Error "unknown version: #{version}" unless @version? @set_key key # A map from Salt -> KeySets @derived_keys = {} #--------------- # @method kdf # # Run the KDF function specified by our current version, # to yield the encryption and signing keys, given the # input `key` and the randomly-generated salt. # # @param {WordArray} salt The salt to use for key generation. # @param {Function} progress_hook A standard progress hook (optional). # @param {callback} cb Callback with an {Object} after completion. # The object will map cipher-name to a {WordArray} that is the generated key. # kdf : ({salt, extra_keymaterial, progress_hook}, cb) -> await @_check_scrubbed @key, "in KDF", cb, defer() # Check the cache first salt_hex = salt.to_hex() # The key gets scrubbed by pbkdf2, so we need to clone our copy of it. key = @key.clone() await @_check_scrubbed key, "KDF", cb, defer() if not (keys = @derived_keys[salt_hex])? @_kdf = new @version.kdf.klass @version.kdf.opts lens = hmac : @version.hmac_key_size aes : AES.keySize twofish : TwoFish.keySize salsa20 : salsa20.Salsa20.keySize # The order to read the keys out of the Scrypt output, and don't # depend on the properties of the hash to guarantee the order. order = [ 'hmac', 'aes', 'twofish', 'salsa20' ] dkLen = extra_keymaterial or 0 (dkLen += v for k,v of lens) args = {dkLen, key, progress_hook, salt } await @_kdf.run args, defer raw keys = {} i = 0 for k in order v = lens[k] len = v/4 end = i + len keys[k] = new WordArray raw.words[i...end] i = end keys.extra = (new WordArray raw.words[end...]).to_buffer() @derived_keys[salt_hex] = keys cb null, keys #--------------- # Set or change the key on this encryptor, causing a scrubbing of the # old state if it was previously set. # # @param {Buffer} key the Passphrase/key as a standard buffer object. # set_key : (key) -> if key? wakey = WordArray.from_buffer(key) if not @key or not @key.equal wakey @scrub() @key = wakey else @scrub() #--------------- # @private # # Check that a key isn't scrubbed. If it is, it's a huge problem, and we should short-circuit # encryption. # # @param {WordArray} key The key to check for having been scrubbed. # @param {String} where Where the check is happening. # @param {callback} ecb The callback to fire with an Error, in the case of a scrubbed key. # @param {callback} okcb The callback to fire if we're OK to proceed. # _check_scrubbed : (key, where, ecb, okcb) -> if key? and not key.is_scrubbed() then okcb() else ecb (new Error "#{where}: Failed due to scrubbed key!"), null #--------------- # Sign with HMAC-SHA512-SHA-3 # # @param {WordArray} input The text to sign. # @param {WordArray} key The signing key # @param {WordArray} salt The salt used to generate the derived keys. # @param {Function} progress_hook A standard progress hook (optional). # @param {callback} cb Call back with `(err,res)` upon completion, # with `res` of type {WordArray} and containing the signature. # sign : ({input, key, salt, progress_hook}, cb) -> await @_check_scrubbed key, "HMAC", cb, defer() input = (new WordArray @version.header ).concat(salt).concat(input) await Concat.bulk_sign { key, input, progress_hook}, defer(out) input.scrub() cb null, out #--------------- # Run SALSA20, output (IV || ciphertext) # # @param {WordArray} input The input plaintext # @param {WordArray} key The Salsa20-specific encryption key (32 bytes) # @param {WordArray} iv The Salsa20-specific IV (24 bytes as per XSalsa20) # @param {bool} output_iv Whether or not to output the IV with the ciphertext # @param {callback} cb Callback on completion with `(err, res)`. `res` will # be a {WordArray} of the ciphertext or a concatenation of the IV and # the ciphertext, depending on the `output_iv` option. run_salsa20 : ({ input, key, iv, output_iv, progress_hook }, cb) -> await @_check_scrubbed key, "Salsa20", cb, defer() args = { input, progress_hook, key, iv } # In the newer versions of TripleSec, we fix the fact that our # inputs to Xsalsa20 were reversed endianwise. It wasn't a security # bug, it was just wrong. This fixes it going forward. We might # want a slightly cleaner fix by the way... if @version.xsalsa20_rev args.key = key.clone().endian_reverse() args.iv = iv.clone().endian_reverse() await salsa20.bulk_encrypt args, defer ct # Despite the reversals, always output the original IV. ct = iv.clone().concat(ct) if output_iv # Scrub the reversed IV & key since we'll never use it again. if @version.xsalsa20_rev args.key.scrub() args.iv.scrub() cb null, ct #--------------- # Run Twofish, output (IV || ciphertext). # # @param {WordArray} input The input plaintext # @param {WordArray} key The Twofish-specific encryption key (32 bytes) # @param {WordArray} iv The Twofish-specific IV (16 bytes) # @param {callback} cb Callback on completion with `(err, res)`. `res` will # be a {WordArray} of the concatenation of the IV and # the ciphertext. run_twofish : ({input, key, iv, progress_hook}, cb) -> await @_check_scrubbed key, "TwoFish", cb, defer() block_cipher = new TwoFish key await ctr.bulk_encrypt { block_cipher, iv, input, progress_hook, what : "twofish" }, defer ct block_cipher.scrub() cb null, iv.clone().concat(ct) #--------------- # Run AES, output (IV || ciphertext). # # @param {WordArray} input The input plaintext # @param {WordArray} key The AES-specific encryption key (32 bytes) # @param {WordArray} iv The AES-specific IV (16 bytes) # @param {callback} cb Callback on completion with `(err, res)`. `res` will # be a {WordArray} of the concatenation of the IV and # the ciphertext. run_aes : ({input, key, iv, progress_hook}, cb) -> await @_check_scrubbed key, "AES", cb, defer() block_cipher = new AES key await ctr.bulk_encrypt { block_cipher, iv, input, progress_hook, what : "aes" }, defer ct block_cipher.scrub() cb null, iv.clone().concat(ct) #--------------- # Scrub all internal state that may be sensitive. Use it after you're done # with the Encryptor. scrub : () -> @key.scrub() if @key? if @derived_keys? for salt,key_ring of @derived_keys for key in key_ring key.scrub() @derived_keys = {} @salt.scrub() if @salt? @salt = null @key = null #======================================================================== # ### Encryptor # # The high-level Encryption engine for TripleSec. You should allocate one # instance of this object for each secret key you are dealing with. Reusing # the same Encryptor object will allow you to avoid rerunning PBKDF2 with # each encryption. If you want to use new salt with every encryption, # you can call `resalt` as needed. The `run` method is called to # run the encryption engine. # # Here is an example of multiple encryptions with salt reuse, in CoffeeScript: # @example # ```coffeescript # key = new Buffer "pitying web andiron impacts bought" # data = new Buffer "this is my secret data" # eng = new Encryptor { key } # eng.run { data }, (err, res) -> # console.log "Ciphertext 1: " + res.toString('hex') # data = Buffer.concat data, new Buffer " which just got bigger" # eng.run { data }, (err, res) -> # console.log "Ciphertext 2: " + res.toString('hex') #``` # # Or equivalently in JavaScript: # @example # ```javascript # var key = new Buffer("pitying web andiron impacts bought"); # var data = new Buffer("this is my secret data"); # var eng = new Encryptor({ key : key }); # eng.run({ data : data }, function (err, res) { # console.log("Ciphertext 1: " + res.toString('hex')); # data = Buffer.concat(data, new Buffer(" which just got bigger")); # eng.run({ data : data }), function (err, res) { # console.log("Ciphertext 2: " + res.toString('hex')); # }); # }); # ``` # # In the previous two examples, the same salt was used for both ciphertexts. # To resalt (and regenerate encryption keys): # @example # ```coffeescript # key = new Buffer "pitying web andiron impacts bought" # data = new Buffer "this is my secret data" # eng = new Encryptor { key } # eng.run { data }, (err, res) -> # console.log "Ciphertext 1: " + res.toString('hex') # data = Buffer.concat data, new Buffer " which just got bigger" # eng.resalt {}, () -> # eng.run { data }, (err, res) -> # console.log "Ciphertext 2: " + res.toString('hex') #``` # # class Encryptor extends Base #--------------- # @param {Buffer} key The secret key # @param {Function} rng Call it with the number of Rando bytes you need. It should callback with a WordArray of random bytes # @param {Object} version The version object to follow constructor : ( { key, rng, version } ) -> super { key, version } @rng = rng or prng.generate #--------------- # @private # # Pick random IVS, one for each crypto algoritm. Call back # with an Object, mapping cipher engine name to a {WordArray} # containing the IV. # # @param {Function} progress_hook A standard progress hook. # @param {callback} cb Called back when the resalting completes. pick_random_ivs : ({progress_hook}, cb) -> iv_lens = aes : AES.ivSize twofish : TwoFish.ivSize salsa20 : salsa20.Salsa20.ivSize ivs = {} for k,v of iv_lens await @rng v, defer ivs[k] cb ivs #--------------- # Regenerate the salt. Reinitialize the keys. You have to do this # once, but if you don't do it again, you'll just wind up using the # same salt. # # @param {Function} progress_hook A standard progress hook. # @param {Buffer} salt The optional salt to provide, if it's deterministic # and can be passed in. If not provided, then we # @param {callback} cb Called back when the resalting completes. resalt : ({salt, extra_keymaterial, progress_hook}, cb) -> err = null if not salt? await @rng @version.salt_size, defer @salt else if salt.length isnt @version.salt_size err = new Error "Need a salt of exactly #{@version.salt_size} bytes (got #{salt.length})" else @salt = WordArray.alloc salt unless err? await @kdf {extra_keymaterial, progress_hook, @salt}, defer err, @keys cb err, @keys #--------------- # @method run # # The main point of entry into the TripleSec Encryption system. The # steps of the algorithm are: # # 1. Encrypt PT with Salsa20 # 1. Encrypt the result of 1 with 2Fish-256-CTR # 1. Encrypt the result of 2 with AES-256-CTR # 1. MAC with (HMAC-SHA512 || HMAC-SHA3) # # @param {Buffer} data the data to encrypt # @param {Buffer} salt The optional salt to provide, if it's deterministic # and can be passed in. If not provided, then we # @param {Function} progress_hook Call this to update the U/I about progress # @param {number} extra_keymaterial The number of extra bytes to generate # along with the crypto keys (default : 0) # @param {callback} cb With an (err,res) pair, res is the buffer with the encrypted data # run : ( { data, salt, extra_keymaterial, progress_hook }, cb ) -> # esc = "Error Short-Circuiter". In the case of an error, # we'll forget about the rest of the function and just call back # the outer-level cb with the error. If no error, then proceed as normal. esc = make_esc cb, "Encryptor::run" if salt? or not @salt? await @resalt { salt, extra_keymaterial, progress_hook }, esc defer() await @pick_random_ivs { progress_hook }, defer ivs pt = WordArray.from_buffer data await @run_salsa20 { input : pt, key : @keys.salsa20, progress_hook, iv : ivs.salsa20, output_iv : true }, esc defer ct1 await @run_twofish { input : ct1, key : @keys.twofish, progress_hook, iv : ivs.twofish }, esc defer ct2 await @run_aes { input : ct2, key : @keys.aes, progress_hook, iv : ivs.aes }, esc defer ct3 await @sign { input : ct3, key : @keys.hmac, progress_hook, @salt }, esc defer sig ret = (new WordArray(@version.header)).concat(@salt).concat(sig).concat(ct3).to_buffer() util.scrub_buffer data cb null, ret #======================================================================== # # @method encrypt # # A convenience wrapper for: # # 1. Creating a new Encryptor instance with the given key # 1. Calling `run` just once. # 1. Scrubbing and deleting all state. # # @param {Buffer} key The secret key. This data is scrubbed after use, so copy it # if you want to keep track of it. # @param {Buffer} data The data to encrypt. Again, this data is scrubber after # use, so copy it if you need it later. # @param {Function} rng A function that takes as input n and outputs n truly # random bytes. You must give a real RNG here and not something fake. # You can try require('./prng').generate_words for starters. # @param {callback} cb Callback with an (err,res) pair. The err is an Error object # (if encountered), and res is a Buffer object (on success). # encrypt = ({ key, data, rng, progress_hook, version}, cb) -> enc = new Encryptor { key, rng, version } await enc.run { data, progress_hook }, defer err, ret enc.scrub() cb err, ret #======================================================================== exports.V = V exports.encrypt = encrypt exports.Base = Base exports.Encryptor = Encryptor #========================================================================
77022
{WordArray} = require './wordarray' salsa20 = require './salsa20' {AES} = require './aes' {TwoFish} = require './twofish' ctr = require './ctr' {XOR,Concat} = require './combine' {SHA512} = require './sha512' {PBKDF2} = require './pbkdf2' {Scrypt} = require './scrypt' util = require './util' prng = require './prng' {make_esc} = require 'iced-error' {HMAC_SHA256} = require './hmac' #======================================================================== # @property {Object} V A lookup table of all supported versions. V = "1" : header : [ 0x1c94d7de, 1 ] # The magic #, and also the version # salt_size : 8 # 8 bytes of salt is good enough! xsalsa20_rev : true # XSalsa20 Endian Reverse kdf : # The key derivation... klass : PBKDF2 # algorithm klass opts : # ..and options c : 1024 # The number of iterations klass : XOR # The HMAC to use as a subroutine hmac_key_size : 768/8 # The size of the key to split over the two HMACs. "2" : header : [ 0x1c94d7de, 2 ] # The magic #, and also the version # salt_size : 16 # 16 bytes of salt for various uses xsalsa20_rev : true # XSalsa20 Endian Reverse kdf : # The key derivation... klass : Scrypt # algorithm klass opts : # ..and options c : 64 # The number of iterations klass : XOR # The HMAC to use as a subroutine N : 12 # log_2 of the work factor r : 8 # The memory use factor p : 1 # the parallelization factor hmac_key_size : 768/8 # The size of the key to split over the two HMACs. "3" : header : [ 0x1c94d7de, 3 ] # The magic #, and also the version # salt_size : 16 # 16 bytes of salt for various uses xsalsa20_rev : false # XSalsa20 Endian Reverse kdf : # The key derivation... klass : Scrypt # algorithm klass opts : # ..and options c : 1 # The number of iterations klass : HMAC_SHA256 # The HMAC to use as a subroutine N : 16 # log_2 of the work factor r : 8 # The memory use factor p : 1 # the parallelization factor hmac_key_size : 768/8 # The size of the key to split over the two HMACs. #======================================================================== # A base class for the {Encryptor} and {Decryptor} classes. # Handles a lot of the particulars of signing, key generation, # and encryption/decryption. class Base #--------------- # @param {WordArray} key The private encryption key constructor : ( { key, version } ) -> @version = V[if version? then version else 1] throw new Error "unknown version: #{version}" unless @version? @set_key key # A map from Salt -> KeySets @derived_keys = {} #--------------- # @method kdf # # Run the KDF function specified by our current version, # to yield the encryption and signing keys, given the # input `key` and the randomly-generated salt. # # @param {WordArray} salt The salt to use for key generation. # @param {Function} progress_hook A standard progress hook (optional). # @param {callback} cb Callback with an {Object} after completion. # The object will map cipher-name to a {WordArray} that is the generated key. # kdf : ({salt, extra_keymaterial, progress_hook}, cb) -> await @_check_scrubbed @key, "in KDF", cb, defer() # Check the cache first salt_hex = salt.to_hex() # The key gets scrubbed by pbkdf2, so we need to clone our copy of it. key = @key.clone() await @_check_scrubbed key, "KDF", cb, defer() if not (keys = @derived_keys[salt_hex])? @_kdf = new @version.kdf.klass @version.kdf.opts lens = hmac : @version.hmac_key_size aes : AES.keySize twofish : TwoFish.keySize salsa20 : salsa20.Salsa20.keySize # The order to read the keys out of the Scrypt output, and don't # depend on the properties of the hash to guarantee the order. order = [ 'hmac', 'aes', 'twofish', 'salsa20' ] dkLen = extra_keymaterial or 0 (dkLen += v for k,v of lens) args = {dkLen, key, progress_hook, salt } await @_kdf.run args, defer raw keys = {} i = 0 for k in order v = lens[k] len = v/4 end = i + len keys[k] = new WordArray raw.words[i...end] i = end keys.extra = (new WordArray raw.words[end...]).to_buffer() @derived_keys[salt_hex] = keys cb null, keys #--------------- # Set or change the key on this encryptor, causing a scrubbing of the # old state if it was previously set. # # @param {Buffer} key the Passphrase/key as a standard buffer object. # set_key : (key) -> if key? wakey = WordArray.from_buffer(key) if not @key or not @key.equal wakey @scrub() @key = wakey else @scrub() #--------------- # @private # # Check that a key isn't scrubbed. If it is, it's a huge problem, and we should short-circuit # encryption. # # @param {WordArray} key The key to check for having been scrubbed. # @param {String} where Where the check is happening. # @param {callback} ecb The callback to fire with an Error, in the case of a scrubbed key. # @param {callback} okcb The callback to fire if we're OK to proceed. # _check_scrubbed : (key, where, ecb, okcb) -> if key? and not key.is_scrubbed() then okcb() else ecb (new Error "#{where}: Failed due to scrubbed key!"), null #--------------- # Sign with HMAC-SHA512-SHA-3 # # @param {WordArray} input The text to sign. # @param {WordArray} key The signing key # @param {WordArray} salt The salt used to generate the derived keys. # @param {Function} progress_hook A standard progress hook (optional). # @param {callback} cb Call back with `(err,res)` upon completion, # with `res` of type {WordArray} and containing the signature. # sign : ({input, key, salt, progress_hook}, cb) -> await @_check_scrubbed key, "HMAC", cb, defer() input = (new WordArray @version.header ).concat(salt).concat(input) await Concat.bulk_sign { key, input, progress_hook}, defer(out) input.scrub() cb null, out #--------------- # Run SALSA20, output (IV || ciphertext) # # @param {WordArray} input The input plaintext # @param {WordArray} key The Salsa20-specific encryption key (32 bytes) # @param {WordArray} iv The Salsa20-specific IV (24 bytes as per XSalsa20) # @param {bool} output_iv Whether or not to output the IV with the ciphertext # @param {callback} cb Callback on completion with `(err, res)`. `res` will # be a {WordArray} of the ciphertext or a concatenation of the IV and # the ciphertext, depending on the `output_iv` option. run_salsa20 : ({ input, key, iv, output_iv, progress_hook }, cb) -> await @_check_scrubbed key, "Salsa20", cb, defer() args = { input, progress_hook, key, iv } # In the newer versions of TripleSec, we fix the fact that our # inputs to Xsalsa20 were reversed endianwise. It wasn't a security # bug, it was just wrong. This fixes it going forward. We might # want a slightly cleaner fix by the way... if @version.xsalsa20_rev args.key = key.clone().endian_reverse() args.iv = iv.clone().endian_reverse() await salsa20.bulk_encrypt args, defer ct # Despite the reversals, always output the original IV. ct = iv.clone().concat(ct) if output_iv # Scrub the reversed IV & key since we'll never use it again. if @version.xsalsa20_rev args.key.scrub() args.iv.scrub() cb null, ct #--------------- # Run Twofish, output (IV || ciphertext). # # @param {WordArray} input The input plaintext # @param {WordArray} key The Twofish-specific encryption key (32 bytes) # @param {WordArray} iv The Twofish-specific IV (16 bytes) # @param {callback} cb Callback on completion with `(err, res)`. `res` will # be a {WordArray} of the concatenation of the IV and # the ciphertext. run_twofish : ({input, key, iv, progress_hook}, cb) -> await @_check_scrubbed key, "TwoFish", cb, defer() block_cipher = new TwoFish key await ctr.bulk_encrypt { block_cipher, iv, input, progress_hook, what : "twofish" }, defer ct block_cipher.scrub() cb null, iv.clone().concat(ct) #--------------- # Run AES, output (IV || ciphertext). # # @param {WordArray} input The input plaintext # @param {WordArray} key The AES-specific encryption key (32 bytes) # @param {WordArray} iv The AES-specific IV (16 bytes) # @param {callback} cb Callback on completion with `(err, res)`. `res` will # be a {WordArray} of the concatenation of the IV and # the ciphertext. run_aes : ({input, key, iv, progress_hook}, cb) -> await @_check_scrubbed key, "AES", cb, defer() block_cipher = new AES key await ctr.bulk_encrypt { block_cipher, iv, input, progress_hook, what : "aes" }, defer ct block_cipher.scrub() cb null, iv.clone().concat(ct) #--------------- # Scrub all internal state that may be sensitive. Use it after you're done # with the Encryptor. scrub : () -> @key.scrub() if @key? if @derived_keys? for salt,key_ring of @derived_keys for key in key_ring key.scrub() @derived_keys = {} @salt.scrub() if @salt? @salt = null @key = null #======================================================================== # ### Encryptor # # The high-level Encryption engine for TripleSec. You should allocate one # instance of this object for each secret key you are dealing with. Reusing # the same Encryptor object will allow you to avoid rerunning PBKDF2 with # each encryption. If you want to use new salt with every encryption, # you can call `resalt` as needed. The `run` method is called to # run the encryption engine. # # Here is an example of multiple encryptions with salt reuse, in CoffeeScript: # @example # ```coffeescript # key = new Buffer "<KEY>" # data = new Buffer "this is my secret data" # eng = new Encryptor { key } # eng.run { data }, (err, res) -> # console.log "Ciphertext 1: " + res.toString('hex') # data = Buffer.concat data, new Buffer " which just got bigger" # eng.run { data }, (err, res) -> # console.log "Ciphertext 2: " + res.toString('hex') #``` # # Or equivalently in JavaScript: # @example # ```javascript # var key = new Buffer("pitying web andiron impacts bought"); # var data = new Buffer("this is my secret data"); # var eng = new Encryptor({ key : key }); # eng.run({ data : data }, function (err, res) { # console.log("Ciphertext 1: " + res.toString('hex')); # data = Buffer.concat(data, new Buffer(" which just got bigger")); # eng.run({ data : data }), function (err, res) { # console.log("Ciphertext 2: " + res.toString('hex')); # }); # }); # ``` # # In the previous two examples, the same salt was used for both ciphertexts. # To resalt (and regenerate encryption keys): # @example # ```coffeescript # key = new Buffer "pitying web andiron impacts bought" # data = new Buffer "this is my secret data" # eng = new Encryptor { key } # eng.run { data }, (err, res) -> # console.log "Ciphertext 1: " + res.toString('hex') # data = Buffer.concat data, new Buffer " which just got bigger" # eng.resalt {}, () -> # eng.run { data }, (err, res) -> # console.log "Ciphertext 2: " + res.toString('hex') #``` # # class Encryptor extends Base #--------------- # @param {Buffer} key The secret key # @param {Function} rng Call it with the number of Rando bytes you need. It should callback with a WordArray of random bytes # @param {Object} version The version object to follow constructor : ( { key, rng, version } ) -> super { key, version } @rng = rng or prng.generate #--------------- # @private # # Pick random IVS, one for each crypto algoritm. Call back # with an Object, mapping cipher engine name to a {WordArray} # containing the IV. # # @param {Function} progress_hook A standard progress hook. # @param {callback} cb Called back when the resalting completes. pick_random_ivs : ({progress_hook}, cb) -> iv_lens = aes : AES.ivSize twofish : TwoFish.ivSize salsa20 : salsa20.Salsa20.ivSize ivs = {} for k,v of iv_lens await @rng v, defer ivs[k] cb ivs #--------------- # Regenerate the salt. Reinitialize the keys. You have to do this # once, but if you don't do it again, you'll just wind up using the # same salt. # # @param {Function} progress_hook A standard progress hook. # @param {Buffer} salt The optional salt to provide, if it's deterministic # and can be passed in. If not provided, then we # @param {callback} cb Called back when the resalting completes. resalt : ({salt, extra_keymaterial, progress_hook}, cb) -> err = null if not salt? await @rng @version.salt_size, defer @salt else if salt.length isnt @version.salt_size err = new Error "Need a salt of exactly #{@version.salt_size} bytes (got #{salt.length})" else @salt = WordArray.alloc salt unless err? await @kdf {extra_keymaterial, progress_hook, @salt}, defer err, @keys cb err, @keys #--------------- # @method run # # The main point of entry into the TripleSec Encryption system. The # steps of the algorithm are: # # 1. Encrypt PT with Salsa20 # 1. Encrypt the result of 1 with 2Fish-256-CTR # 1. Encrypt the result of 2 with AES-256-CTR # 1. MAC with (HMAC-SHA512 || HMAC-SHA3) # # @param {Buffer} data the data to encrypt # @param {Buffer} salt The optional salt to provide, if it's deterministic # and can be passed in. If not provided, then we # @param {Function} progress_hook Call this to update the U/I about progress # @param {number} extra_keymaterial The number of extra bytes to generate # along with the crypto keys (default : 0) # @param {callback} cb With an (err,res) pair, res is the buffer with the encrypted data # run : ( { data, salt, extra_keymaterial, progress_hook }, cb ) -> # esc = "Error Short-Circuiter". In the case of an error, # we'll forget about the rest of the function and just call back # the outer-level cb with the error. If no error, then proceed as normal. esc = make_esc cb, "Encryptor::run" if salt? or not @salt? await @resalt { salt, extra_keymaterial, progress_hook }, esc defer() await @pick_random_ivs { progress_hook }, defer ivs pt = WordArray.from_buffer data await @run_salsa20 { input : pt, key : @keys.salsa20, progress_hook, iv : ivs.salsa20, output_iv : true }, esc defer ct1 await @run_twofish { input : ct1, key : @keys.twofish, progress_hook, iv : ivs.twofish }, esc defer ct2 await @run_aes { input : ct2, key : @keys.aes, progress_hook, iv : ivs.aes }, esc defer ct3 await @sign { input : ct3, key : @keys.hmac, progress_hook, @salt }, esc defer sig ret = (new WordArray(@version.header)).concat(@salt).concat(sig).concat(ct3).to_buffer() util.scrub_buffer data cb null, ret #======================================================================== # # @method encrypt # # A convenience wrapper for: # # 1. Creating a new Encryptor instance with the given key # 1. Calling `run` just once. # 1. Scrubbing and deleting all state. # # @param {Buffer} key The secret key. This data is scrubbed after use, so copy it # if you want to keep track of it. # @param {Buffer} data The data to encrypt. Again, this data is scrubber after # use, so copy it if you need it later. # @param {Function} rng A function that takes as input n and outputs n truly # random bytes. You must give a real RNG here and not something fake. # You can try require('./prng').generate_words for starters. # @param {callback} cb Callback with an (err,res) pair. The err is an Error object # (if encountered), and res is a Buffer object (on success). # encrypt = ({ key, data, rng, progress_hook, version}, cb) -> enc = new Encryptor { key, rng, version } await enc.run { data, progress_hook }, defer err, ret enc.scrub() cb err, ret #======================================================================== exports.V = V exports.encrypt = encrypt exports.Base = Base exports.Encryptor = Encryptor #========================================================================
true
{WordArray} = require './wordarray' salsa20 = require './salsa20' {AES} = require './aes' {TwoFish} = require './twofish' ctr = require './ctr' {XOR,Concat} = require './combine' {SHA512} = require './sha512' {PBKDF2} = require './pbkdf2' {Scrypt} = require './scrypt' util = require './util' prng = require './prng' {make_esc} = require 'iced-error' {HMAC_SHA256} = require './hmac' #======================================================================== # @property {Object} V A lookup table of all supported versions. V = "1" : header : [ 0x1c94d7de, 1 ] # The magic #, and also the version # salt_size : 8 # 8 bytes of salt is good enough! xsalsa20_rev : true # XSalsa20 Endian Reverse kdf : # The key derivation... klass : PBKDF2 # algorithm klass opts : # ..and options c : 1024 # The number of iterations klass : XOR # The HMAC to use as a subroutine hmac_key_size : 768/8 # The size of the key to split over the two HMACs. "2" : header : [ 0x1c94d7de, 2 ] # The magic #, and also the version # salt_size : 16 # 16 bytes of salt for various uses xsalsa20_rev : true # XSalsa20 Endian Reverse kdf : # The key derivation... klass : Scrypt # algorithm klass opts : # ..and options c : 64 # The number of iterations klass : XOR # The HMAC to use as a subroutine N : 12 # log_2 of the work factor r : 8 # The memory use factor p : 1 # the parallelization factor hmac_key_size : 768/8 # The size of the key to split over the two HMACs. "3" : header : [ 0x1c94d7de, 3 ] # The magic #, and also the version # salt_size : 16 # 16 bytes of salt for various uses xsalsa20_rev : false # XSalsa20 Endian Reverse kdf : # The key derivation... klass : Scrypt # algorithm klass opts : # ..and options c : 1 # The number of iterations klass : HMAC_SHA256 # The HMAC to use as a subroutine N : 16 # log_2 of the work factor r : 8 # The memory use factor p : 1 # the parallelization factor hmac_key_size : 768/8 # The size of the key to split over the two HMACs. #======================================================================== # A base class for the {Encryptor} and {Decryptor} classes. # Handles a lot of the particulars of signing, key generation, # and encryption/decryption. class Base #--------------- # @param {WordArray} key The private encryption key constructor : ( { key, version } ) -> @version = V[if version? then version else 1] throw new Error "unknown version: #{version}" unless @version? @set_key key # A map from Salt -> KeySets @derived_keys = {} #--------------- # @method kdf # # Run the KDF function specified by our current version, # to yield the encryption and signing keys, given the # input `key` and the randomly-generated salt. # # @param {WordArray} salt The salt to use for key generation. # @param {Function} progress_hook A standard progress hook (optional). # @param {callback} cb Callback with an {Object} after completion. # The object will map cipher-name to a {WordArray} that is the generated key. # kdf : ({salt, extra_keymaterial, progress_hook}, cb) -> await @_check_scrubbed @key, "in KDF", cb, defer() # Check the cache first salt_hex = salt.to_hex() # The key gets scrubbed by pbkdf2, so we need to clone our copy of it. key = @key.clone() await @_check_scrubbed key, "KDF", cb, defer() if not (keys = @derived_keys[salt_hex])? @_kdf = new @version.kdf.klass @version.kdf.opts lens = hmac : @version.hmac_key_size aes : AES.keySize twofish : TwoFish.keySize salsa20 : salsa20.Salsa20.keySize # The order to read the keys out of the Scrypt output, and don't # depend on the properties of the hash to guarantee the order. order = [ 'hmac', 'aes', 'twofish', 'salsa20' ] dkLen = extra_keymaterial or 0 (dkLen += v for k,v of lens) args = {dkLen, key, progress_hook, salt } await @_kdf.run args, defer raw keys = {} i = 0 for k in order v = lens[k] len = v/4 end = i + len keys[k] = new WordArray raw.words[i...end] i = end keys.extra = (new WordArray raw.words[end...]).to_buffer() @derived_keys[salt_hex] = keys cb null, keys #--------------- # Set or change the key on this encryptor, causing a scrubbing of the # old state if it was previously set. # # @param {Buffer} key the Passphrase/key as a standard buffer object. # set_key : (key) -> if key? wakey = WordArray.from_buffer(key) if not @key or not @key.equal wakey @scrub() @key = wakey else @scrub() #--------------- # @private # # Check that a key isn't scrubbed. If it is, it's a huge problem, and we should short-circuit # encryption. # # @param {WordArray} key The key to check for having been scrubbed. # @param {String} where Where the check is happening. # @param {callback} ecb The callback to fire with an Error, in the case of a scrubbed key. # @param {callback} okcb The callback to fire if we're OK to proceed. # _check_scrubbed : (key, where, ecb, okcb) -> if key? and not key.is_scrubbed() then okcb() else ecb (new Error "#{where}: Failed due to scrubbed key!"), null #--------------- # Sign with HMAC-SHA512-SHA-3 # # @param {WordArray} input The text to sign. # @param {WordArray} key The signing key # @param {WordArray} salt The salt used to generate the derived keys. # @param {Function} progress_hook A standard progress hook (optional). # @param {callback} cb Call back with `(err,res)` upon completion, # with `res` of type {WordArray} and containing the signature. # sign : ({input, key, salt, progress_hook}, cb) -> await @_check_scrubbed key, "HMAC", cb, defer() input = (new WordArray @version.header ).concat(salt).concat(input) await Concat.bulk_sign { key, input, progress_hook}, defer(out) input.scrub() cb null, out #--------------- # Run SALSA20, output (IV || ciphertext) # # @param {WordArray} input The input plaintext # @param {WordArray} key The Salsa20-specific encryption key (32 bytes) # @param {WordArray} iv The Salsa20-specific IV (24 bytes as per XSalsa20) # @param {bool} output_iv Whether or not to output the IV with the ciphertext # @param {callback} cb Callback on completion with `(err, res)`. `res` will # be a {WordArray} of the ciphertext or a concatenation of the IV and # the ciphertext, depending on the `output_iv` option. run_salsa20 : ({ input, key, iv, output_iv, progress_hook }, cb) -> await @_check_scrubbed key, "Salsa20", cb, defer() args = { input, progress_hook, key, iv } # In the newer versions of TripleSec, we fix the fact that our # inputs to Xsalsa20 were reversed endianwise. It wasn't a security # bug, it was just wrong. This fixes it going forward. We might # want a slightly cleaner fix by the way... if @version.xsalsa20_rev args.key = key.clone().endian_reverse() args.iv = iv.clone().endian_reverse() await salsa20.bulk_encrypt args, defer ct # Despite the reversals, always output the original IV. ct = iv.clone().concat(ct) if output_iv # Scrub the reversed IV & key since we'll never use it again. if @version.xsalsa20_rev args.key.scrub() args.iv.scrub() cb null, ct #--------------- # Run Twofish, output (IV || ciphertext). # # @param {WordArray} input The input plaintext # @param {WordArray} key The Twofish-specific encryption key (32 bytes) # @param {WordArray} iv The Twofish-specific IV (16 bytes) # @param {callback} cb Callback on completion with `(err, res)`. `res` will # be a {WordArray} of the concatenation of the IV and # the ciphertext. run_twofish : ({input, key, iv, progress_hook}, cb) -> await @_check_scrubbed key, "TwoFish", cb, defer() block_cipher = new TwoFish key await ctr.bulk_encrypt { block_cipher, iv, input, progress_hook, what : "twofish" }, defer ct block_cipher.scrub() cb null, iv.clone().concat(ct) #--------------- # Run AES, output (IV || ciphertext). # # @param {WordArray} input The input plaintext # @param {WordArray} key The AES-specific encryption key (32 bytes) # @param {WordArray} iv The AES-specific IV (16 bytes) # @param {callback} cb Callback on completion with `(err, res)`. `res` will # be a {WordArray} of the concatenation of the IV and # the ciphertext. run_aes : ({input, key, iv, progress_hook}, cb) -> await @_check_scrubbed key, "AES", cb, defer() block_cipher = new AES key await ctr.bulk_encrypt { block_cipher, iv, input, progress_hook, what : "aes" }, defer ct block_cipher.scrub() cb null, iv.clone().concat(ct) #--------------- # Scrub all internal state that may be sensitive. Use it after you're done # with the Encryptor. scrub : () -> @key.scrub() if @key? if @derived_keys? for salt,key_ring of @derived_keys for key in key_ring key.scrub() @derived_keys = {} @salt.scrub() if @salt? @salt = null @key = null #======================================================================== # ### Encryptor # # The high-level Encryption engine for TripleSec. You should allocate one # instance of this object for each secret key you are dealing with. Reusing # the same Encryptor object will allow you to avoid rerunning PBKDF2 with # each encryption. If you want to use new salt with every encryption, # you can call `resalt` as needed. The `run` method is called to # run the encryption engine. # # Here is an example of multiple encryptions with salt reuse, in CoffeeScript: # @example # ```coffeescript # key = new Buffer "PI:KEY:<KEY>END_PI" # data = new Buffer "this is my secret data" # eng = new Encryptor { key } # eng.run { data }, (err, res) -> # console.log "Ciphertext 1: " + res.toString('hex') # data = Buffer.concat data, new Buffer " which just got bigger" # eng.run { data }, (err, res) -> # console.log "Ciphertext 2: " + res.toString('hex') #``` # # Or equivalently in JavaScript: # @example # ```javascript # var key = new Buffer("pitying web andiron impacts bought"); # var data = new Buffer("this is my secret data"); # var eng = new Encryptor({ key : key }); # eng.run({ data : data }, function (err, res) { # console.log("Ciphertext 1: " + res.toString('hex')); # data = Buffer.concat(data, new Buffer(" which just got bigger")); # eng.run({ data : data }), function (err, res) { # console.log("Ciphertext 2: " + res.toString('hex')); # }); # }); # ``` # # In the previous two examples, the same salt was used for both ciphertexts. # To resalt (and regenerate encryption keys): # @example # ```coffeescript # key = new Buffer "pitying web andiron impacts bought" # data = new Buffer "this is my secret data" # eng = new Encryptor { key } # eng.run { data }, (err, res) -> # console.log "Ciphertext 1: " + res.toString('hex') # data = Buffer.concat data, new Buffer " which just got bigger" # eng.resalt {}, () -> # eng.run { data }, (err, res) -> # console.log "Ciphertext 2: " + res.toString('hex') #``` # # class Encryptor extends Base #--------------- # @param {Buffer} key The secret key # @param {Function} rng Call it with the number of Rando bytes you need. It should callback with a WordArray of random bytes # @param {Object} version The version object to follow constructor : ( { key, rng, version } ) -> super { key, version } @rng = rng or prng.generate #--------------- # @private # # Pick random IVS, one for each crypto algoritm. Call back # with an Object, mapping cipher engine name to a {WordArray} # containing the IV. # # @param {Function} progress_hook A standard progress hook. # @param {callback} cb Called back when the resalting completes. pick_random_ivs : ({progress_hook}, cb) -> iv_lens = aes : AES.ivSize twofish : TwoFish.ivSize salsa20 : salsa20.Salsa20.ivSize ivs = {} for k,v of iv_lens await @rng v, defer ivs[k] cb ivs #--------------- # Regenerate the salt. Reinitialize the keys. You have to do this # once, but if you don't do it again, you'll just wind up using the # same salt. # # @param {Function} progress_hook A standard progress hook. # @param {Buffer} salt The optional salt to provide, if it's deterministic # and can be passed in. If not provided, then we # @param {callback} cb Called back when the resalting completes. resalt : ({salt, extra_keymaterial, progress_hook}, cb) -> err = null if not salt? await @rng @version.salt_size, defer @salt else if salt.length isnt @version.salt_size err = new Error "Need a salt of exactly #{@version.salt_size} bytes (got #{salt.length})" else @salt = WordArray.alloc salt unless err? await @kdf {extra_keymaterial, progress_hook, @salt}, defer err, @keys cb err, @keys #--------------- # @method run # # The main point of entry into the TripleSec Encryption system. The # steps of the algorithm are: # # 1. Encrypt PT with Salsa20 # 1. Encrypt the result of 1 with 2Fish-256-CTR # 1. Encrypt the result of 2 with AES-256-CTR # 1. MAC with (HMAC-SHA512 || HMAC-SHA3) # # @param {Buffer} data the data to encrypt # @param {Buffer} salt The optional salt to provide, if it's deterministic # and can be passed in. If not provided, then we # @param {Function} progress_hook Call this to update the U/I about progress # @param {number} extra_keymaterial The number of extra bytes to generate # along with the crypto keys (default : 0) # @param {callback} cb With an (err,res) pair, res is the buffer with the encrypted data # run : ( { data, salt, extra_keymaterial, progress_hook }, cb ) -> # esc = "Error Short-Circuiter". In the case of an error, # we'll forget about the rest of the function and just call back # the outer-level cb with the error. If no error, then proceed as normal. esc = make_esc cb, "Encryptor::run" if salt? or not @salt? await @resalt { salt, extra_keymaterial, progress_hook }, esc defer() await @pick_random_ivs { progress_hook }, defer ivs pt = WordArray.from_buffer data await @run_salsa20 { input : pt, key : @keys.salsa20, progress_hook, iv : ivs.salsa20, output_iv : true }, esc defer ct1 await @run_twofish { input : ct1, key : @keys.twofish, progress_hook, iv : ivs.twofish }, esc defer ct2 await @run_aes { input : ct2, key : @keys.aes, progress_hook, iv : ivs.aes }, esc defer ct3 await @sign { input : ct3, key : @keys.hmac, progress_hook, @salt }, esc defer sig ret = (new WordArray(@version.header)).concat(@salt).concat(sig).concat(ct3).to_buffer() util.scrub_buffer data cb null, ret #======================================================================== # # @method encrypt # # A convenience wrapper for: # # 1. Creating a new Encryptor instance with the given key # 1. Calling `run` just once. # 1. Scrubbing and deleting all state. # # @param {Buffer} key The secret key. This data is scrubbed after use, so copy it # if you want to keep track of it. # @param {Buffer} data The data to encrypt. Again, this data is scrubber after # use, so copy it if you need it later. # @param {Function} rng A function that takes as input n and outputs n truly # random bytes. You must give a real RNG here and not something fake. # You can try require('./prng').generate_words for starters. # @param {callback} cb Callback with an (err,res) pair. The err is an Error object # (if encountered), and res is a Buffer object (on success). # encrypt = ({ key, data, rng, progress_hook, version}, cb) -> enc = new Encryptor { key, rng, version } await enc.run { data, progress_hook }, defer err, ret enc.scrub() cb err, ret #======================================================================== exports.V = V exports.encrypt = encrypt exports.Base = Base exports.Encryptor = Encryptor #========================================================================
[ { "context": "lement, 'buyerName')\n name.value = 'Mr. Foo'\n ReactTestUtils.Simulate.change(name)", "end": 1711, "score": 0.7099100351333618, "start": 1708, "tag": "NAME", "value": "Foo" }, { "context": "element, 'buyerEmail')\n email.value = 'foo@bar.baz'\n ReactTestUtils.Simulate.change(email", "end": 2113, "score": 0.9995958209037781, "start": 2102, "tag": "EMAIL", "value": "foo@bar.baz" }, { "context": " element.state =\n name: 'mr foo'\n address: 'address'\n ", "end": 2685, "score": 0.9962946772575378, "start": 2679, "tag": "NAME", "value": "mr foo" }, { "context": " address: 'address'\n email: 'foo@example'\n phone: '12345'\n a", "end": 2757, "score": 0.9997389912605286, "start": 2746, "tag": "EMAIL", "value": "foo@example" }, { "context": " items: {items: true}\n name: 'mr foo'\n address: 'address'\n ", "end": 3020, "score": 0.9974092245101929, "start": 3014, "tag": "NAME", "value": "mr foo" }, { "context": " address: 'address'\n email: 'foo@example'\n phone: '12345'\n a", "end": 3092, "score": 0.9997022747993469, "start": 3081, "tag": "EMAIL", "value": "foo@example" } ]
clients/widgets/product/test/jstest_order_any.coffee
jacob22/accounting
0
/* Copyright 2019 Open End AB Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ Tests = new Deferred() require(['react', 'react-dom', 'signals', 'widgets/product/order'], -> [React, ReactDOM, signals, Order] = arguments ReactTestUtils = React.addons.TestUtils findRenderedDOMComponentWithName = (tree, name) -> [dom] = ReactTestUtils.findAllInRenderedTree(tree, (elem) -> return elem.name == name ) return dom render_form = (props={cart: {contents: []}}) -> root = insertTestNode() component = React.createElement(Order.Form, props) element = ReactDOM.render(component, root) return [root, component, element] Tests.callback( test_create: -> [root, component, element] = render_form() node = ReactDOM.findDOMNode(element) aok(node) test_valid: -> cart = {contents: []} [root, component, element] = render_form({cart: cart}) button = ReactTestUtils.findRenderedDOMComponentWithTag(element, 'button') aok(button.disabled) name = findRenderedDOMComponentWithName(element, 'buyerName') name.value = 'Mr. Foo' ReactTestUtils.Simulate.change(name) aok(button.disabled) name = findRenderedDOMComponentWithName(element, 'buyerAddress') name.value = 'Norra Ågatan 10' ReactTestUtils.Simulate.change(name) aok(button.disabled) email = findRenderedDOMComponentWithName(element, 'buyerEmail') email.value = 'foo@bar.baz' ReactTestUtils.Simulate.change(email) aok(button.disabled) cart.contents = ['a cart full of data'] signals.signal(cart, 'changed') aok(not button.disabled) test_order: -> order = null props = cart: contents: [] get_data: -> items: true place_order: (o) -> order = o [root, component, element] = render_form(props) element.state = name: 'mr foo' address: 'address' email: 'foo@example' phone: '12345' annotation: 'stuff' date: '2010-01-01' expiryDate: '2011-01-01' element._order() expect = items: {items: true} name: 'mr foo' address: 'address' email: 'foo@example' phone: '12345' annotation: 'stuff' date: '2010-01-01' expiryDate: '2011-01-01' aisDeeply(order, expect) ) )
12130
/* Copyright 2019 Open End AB Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ Tests = new Deferred() require(['react', 'react-dom', 'signals', 'widgets/product/order'], -> [React, ReactDOM, signals, Order] = arguments ReactTestUtils = React.addons.TestUtils findRenderedDOMComponentWithName = (tree, name) -> [dom] = ReactTestUtils.findAllInRenderedTree(tree, (elem) -> return elem.name == name ) return dom render_form = (props={cart: {contents: []}}) -> root = insertTestNode() component = React.createElement(Order.Form, props) element = ReactDOM.render(component, root) return [root, component, element] Tests.callback( test_create: -> [root, component, element] = render_form() node = ReactDOM.findDOMNode(element) aok(node) test_valid: -> cart = {contents: []} [root, component, element] = render_form({cart: cart}) button = ReactTestUtils.findRenderedDOMComponentWithTag(element, 'button') aok(button.disabled) name = findRenderedDOMComponentWithName(element, 'buyerName') name.value = 'Mr. <NAME>' ReactTestUtils.Simulate.change(name) aok(button.disabled) name = findRenderedDOMComponentWithName(element, 'buyerAddress') name.value = 'Norra Ågatan 10' ReactTestUtils.Simulate.change(name) aok(button.disabled) email = findRenderedDOMComponentWithName(element, 'buyerEmail') email.value = '<EMAIL>' ReactTestUtils.Simulate.change(email) aok(button.disabled) cart.contents = ['a cart full of data'] signals.signal(cart, 'changed') aok(not button.disabled) test_order: -> order = null props = cart: contents: [] get_data: -> items: true place_order: (o) -> order = o [root, component, element] = render_form(props) element.state = name: '<NAME>' address: 'address' email: '<EMAIL>' phone: '12345' annotation: 'stuff' date: '2010-01-01' expiryDate: '2011-01-01' element._order() expect = items: {items: true} name: '<NAME>' address: 'address' email: '<EMAIL>' phone: '12345' annotation: 'stuff' date: '2010-01-01' expiryDate: '2011-01-01' aisDeeply(order, expect) ) )
true
/* Copyright 2019 Open End AB Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ Tests = new Deferred() require(['react', 'react-dom', 'signals', 'widgets/product/order'], -> [React, ReactDOM, signals, Order] = arguments ReactTestUtils = React.addons.TestUtils findRenderedDOMComponentWithName = (tree, name) -> [dom] = ReactTestUtils.findAllInRenderedTree(tree, (elem) -> return elem.name == name ) return dom render_form = (props={cart: {contents: []}}) -> root = insertTestNode() component = React.createElement(Order.Form, props) element = ReactDOM.render(component, root) return [root, component, element] Tests.callback( test_create: -> [root, component, element] = render_form() node = ReactDOM.findDOMNode(element) aok(node) test_valid: -> cart = {contents: []} [root, component, element] = render_form({cart: cart}) button = ReactTestUtils.findRenderedDOMComponentWithTag(element, 'button') aok(button.disabled) name = findRenderedDOMComponentWithName(element, 'buyerName') name.value = 'Mr. PI:NAME:<NAME>END_PI' ReactTestUtils.Simulate.change(name) aok(button.disabled) name = findRenderedDOMComponentWithName(element, 'buyerAddress') name.value = 'Norra Ågatan 10' ReactTestUtils.Simulate.change(name) aok(button.disabled) email = findRenderedDOMComponentWithName(element, 'buyerEmail') email.value = 'PI:EMAIL:<EMAIL>END_PI' ReactTestUtils.Simulate.change(email) aok(button.disabled) cart.contents = ['a cart full of data'] signals.signal(cart, 'changed') aok(not button.disabled) test_order: -> order = null props = cart: contents: [] get_data: -> items: true place_order: (o) -> order = o [root, component, element] = render_form(props) element.state = name: 'PI:NAME:<NAME>END_PI' address: 'address' email: 'PI:EMAIL:<EMAIL>END_PI' phone: '12345' annotation: 'stuff' date: '2010-01-01' expiryDate: '2011-01-01' element._order() expect = items: {items: true} name: 'PI:NAME:<NAME>END_PI' address: 'address' email: 'PI:EMAIL:<EMAIL>END_PI' phone: '12345' annotation: 'stuff' date: '2010-01-01' expiryDate: '2011-01-01' aisDeeply(order, expect) ) )
[ { "context": " = 'mailto:set-default-no'\n\nNOTIF_SETTINGS_KEY = 'nylas.mailto.prompted-about-default'\n\nmodule.exports =\n activate: (@state) ->\n @s", "end": 197, "score": 0.924466073513031, "start": 162, "tag": "KEY", "value": "nylas.mailto.prompted-about-default" } ]
app/internal_packages/notification-mailto/lib/main.coffee
immershy/nodemail
0
{Actions, LaunchServices} = require 'nylas-exports' NOTIF_ACTION_YES = 'mailto:set-default-yes' NOTIF_ACTION_NO = 'mailto:set-default-no' NOTIF_SETTINGS_KEY = 'nylas.mailto.prompted-about-default' module.exports = activate: (@state) -> @services = new LaunchServices() # We can't do anything unless they're on Mac OS X return unless @services.available() # We shouldn't ask if they've already said No return if NylasEnv.config.get(NOTIF_SETTINGS_KEY) is true @services.isRegisteredForURLScheme 'mailto', (registered) => # Prompt them to make Nylas their default client unless registered @_unlisten = Actions.notificationActionTaken.listen(@_onNotificationActionTaken, @) Actions.postNotification type: 'info', sticky: true message: "Thanks for trying out N1! Would you like to make it your default mail client?", icon: 'fa-inbox', actions: [{ label: 'Not Now' dismisses: true id: NOTIF_ACTION_NO },{ label: 'Yes' dismisses: true default: true id: NOTIF_ACTION_YES }] deactivate: -> @_unlisten?() serialize: -> @state _onNotificationActionTaken: ({notification, action}) -> if action.id is NOTIF_ACTION_YES @services.registerForURLScheme 'mailto', (err) -> console.log(err) if err if action.id is NOTIF_ACTION_NO NylasEnv.config.set(NOTIF_SETTINGS_KEY, true)
131610
{Actions, LaunchServices} = require 'nylas-exports' NOTIF_ACTION_YES = 'mailto:set-default-yes' NOTIF_ACTION_NO = 'mailto:set-default-no' NOTIF_SETTINGS_KEY = '<KEY>' module.exports = activate: (@state) -> @services = new LaunchServices() # We can't do anything unless they're on Mac OS X return unless @services.available() # We shouldn't ask if they've already said No return if NylasEnv.config.get(NOTIF_SETTINGS_KEY) is true @services.isRegisteredForURLScheme 'mailto', (registered) => # Prompt them to make Nylas their default client unless registered @_unlisten = Actions.notificationActionTaken.listen(@_onNotificationActionTaken, @) Actions.postNotification type: 'info', sticky: true message: "Thanks for trying out N1! Would you like to make it your default mail client?", icon: 'fa-inbox', actions: [{ label: 'Not Now' dismisses: true id: NOTIF_ACTION_NO },{ label: 'Yes' dismisses: true default: true id: NOTIF_ACTION_YES }] deactivate: -> @_unlisten?() serialize: -> @state _onNotificationActionTaken: ({notification, action}) -> if action.id is NOTIF_ACTION_YES @services.registerForURLScheme 'mailto', (err) -> console.log(err) if err if action.id is NOTIF_ACTION_NO NylasEnv.config.set(NOTIF_SETTINGS_KEY, true)
true
{Actions, LaunchServices} = require 'nylas-exports' NOTIF_ACTION_YES = 'mailto:set-default-yes' NOTIF_ACTION_NO = 'mailto:set-default-no' NOTIF_SETTINGS_KEY = 'PI:KEY:<KEY>END_PI' module.exports = activate: (@state) -> @services = new LaunchServices() # We can't do anything unless they're on Mac OS X return unless @services.available() # We shouldn't ask if they've already said No return if NylasEnv.config.get(NOTIF_SETTINGS_KEY) is true @services.isRegisteredForURLScheme 'mailto', (registered) => # Prompt them to make Nylas their default client unless registered @_unlisten = Actions.notificationActionTaken.listen(@_onNotificationActionTaken, @) Actions.postNotification type: 'info', sticky: true message: "Thanks for trying out N1! Would you like to make it your default mail client?", icon: 'fa-inbox', actions: [{ label: 'Not Now' dismisses: true id: NOTIF_ACTION_NO },{ label: 'Yes' dismisses: true default: true id: NOTIF_ACTION_YES }] deactivate: -> @_unlisten?() serialize: -> @state _onNotificationActionTaken: ({notification, action}) -> if action.id is NOTIF_ACTION_YES @services.registerForURLScheme 'mailto', (err) -> console.log(err) if err if action.id is NOTIF_ACTION_NO NylasEnv.config.set(NOTIF_SETTINGS_KEY, true)
[ { "context": "er, password ] = u.auth.split ':'\n o.username = user\n o.password = password\n o.hostname = u.host #", "end": 351, "score": 0.9890334606170654, "start": 347, "tag": "USERNAME", "value": "user" }, { "context": "h.split ':'\n o.username = user\n o.password = password\n o.hostname = u.host # includes port\n o.protoco", "end": 377, "score": 0.9992125034332275, "start": 369, "tag": "PASSWORD", "value": "password" } ]
src/rabbitmq.coffee
jonnor/gov
15
# guv - Scaling governor of cloud workers # (c) 2015 The Grid # guv may be freely distributed under the MIT license AMQPStats = require 'amqp-stats' debug = require('debug')('guv:rabbitmq') url = require 'url' amqpOptions = (str) -> o = {} u = url.parse str if u.auth [ user, password ] = u.auth.split ':' o.username = user o.password = password o.hostname = u.host # includes port o.protocol = 'https' return o # http://hg.rabbitmq.com/rabbitmq-management/raw-file/9b44a7aca551/priv/www/doc/stats.html exports.getStats = (config, callback) -> options = amqpOptions config.broker debug 'options', options amqp = new AMQPStats options amqp.queues (err, res, queues) -> debug 'got queue info', err, queues?.length return callback err if err details = {} stats = {} for queue in queues details[queue.name] = queue details[queue.name].fillrate = queue.message_stats?.publish_details?.rate details[queue.name].drainrate = queue.message_stats?.ack_details?.rate stats[queue.name] = queue.messages return callback null, stats, details
163108
# guv - Scaling governor of cloud workers # (c) 2015 The Grid # guv may be freely distributed under the MIT license AMQPStats = require 'amqp-stats' debug = require('debug')('guv:rabbitmq') url = require 'url' amqpOptions = (str) -> o = {} u = url.parse str if u.auth [ user, password ] = u.auth.split ':' o.username = user o.password = <PASSWORD> o.hostname = u.host # includes port o.protocol = 'https' return o # http://hg.rabbitmq.com/rabbitmq-management/raw-file/9b44a7aca551/priv/www/doc/stats.html exports.getStats = (config, callback) -> options = amqpOptions config.broker debug 'options', options amqp = new AMQPStats options amqp.queues (err, res, queues) -> debug 'got queue info', err, queues?.length return callback err if err details = {} stats = {} for queue in queues details[queue.name] = queue details[queue.name].fillrate = queue.message_stats?.publish_details?.rate details[queue.name].drainrate = queue.message_stats?.ack_details?.rate stats[queue.name] = queue.messages return callback null, stats, details
true
# guv - Scaling governor of cloud workers # (c) 2015 The Grid # guv may be freely distributed under the MIT license AMQPStats = require 'amqp-stats' debug = require('debug')('guv:rabbitmq') url = require 'url' amqpOptions = (str) -> o = {} u = url.parse str if u.auth [ user, password ] = u.auth.split ':' o.username = user o.password = PI:PASSWORD:<PASSWORD>END_PI o.hostname = u.host # includes port o.protocol = 'https' return o # http://hg.rabbitmq.com/rabbitmq-management/raw-file/9b44a7aca551/priv/www/doc/stats.html exports.getStats = (config, callback) -> options = amqpOptions config.broker debug 'options', options amqp = new AMQPStats options amqp.queues (err, res, queues) -> debug 'got queue info', err, queues?.length return callback err if err details = {} stats = {} for queue in queues details[queue.name] = queue details[queue.name].fillrate = queue.message_stats?.publish_details?.rate details[queue.name].drainrate = queue.message_stats?.ack_details?.rate stats[queue.name] = queue.messages return callback null, stats, details
[ { "context": "\napp.use session cookie: {secure: true}, secret: 'afa24e6f-6c8a-4748-a7ae-6c7a4f7ad6d9', name: 'twitter-proxy'\napp.use passport.initiali", "end": 1184, "score": 0.9906437993049622, "start": 1148, "tag": "KEY", "value": "afa24e6f-6c8a-4748-a7ae-6c7a4f7ad6d9" } ]
server.coffee
octoblu/twitter-proxy
0
_ = require 'lodash' url = require 'url' cors = require 'cors' morgan = require 'morgan' express = require 'express' passport = require 'passport' session = require 'cookie-session' bodyParser = require 'body-parser' errorHandler = require 'errorhandler' MeshbluAuth = require 'express-meshblu-auth' MeshbluAuthExpress = require 'express-meshblu-auth/src/meshblu-auth-express' MeshbluHealthCheck = require 'express-meshblu-healthcheck' MeshbluConfig = require 'meshblu-config' MeshbluHttp = require 'meshblu-http' debug = require('debug')('little-bits-cloud-proxy') CredentialManager = require './src/models/credential-manager' ProxyRequestModel = require './src/models/proxy-request-model' LittleBitsOptionsBuilder = require './src/models/little-bits-options-builder' meshbluConfig = new MeshbluConfig().toJSON() PORT = process.env.PORT || 80 passport.serializeUser (user, done) -> done null, JSON.stringify user passport.deserializeUser (id, done) -> done null, JSON.parse id app = express() app.use cors() app.use morgan('combined') app.use errorHandler() app.use MeshbluHealthCheck() app.use session cookie: {secure: true}, secret: 'afa24e6f-6c8a-4748-a7ae-6c7a4f7ad6d9', name: 'twitter-proxy' app.use passport.initialize() app.use passport.session() app.use bodyParser.urlencoded limit: '50mb', extended : true app.use bodyParser.json limit : '50mb' app.options '*', cors() meshbluAuthorizer = MeshbluAuth server: meshbluConfig.server port: meshbluConfig.port options = messageSchema: require './twitter-message-schema.json' messageFormSchemaUrl: './twitter-form.json' logo: 'https://cdn.octoblu.com/icons/devices/little-bits-cloud.svg' name: 'littleBits Cloud' credentialManager = new CredentialManager options, meshbluConfig app.post '/api/messages', meshbluAuthorizer, (req, res) -> proxyRequest = new ProxyRequestModel meshbluConfig, LittleBitsOptionsBuilder proxyRequest.sendMessage req.body, (error, message) => debug 'sendMessage response', error, message return res.status(422).send(error.message) if error? res.status(201).send message app.get '/api/authorize', (req, res) -> res.sendFile 'index.html', root: __dirname + '/public' app.post '/api/callback', (req, res) -> credentialManager.findOrCreate req.session.userUuid, req.body.clientId, req.body.clientSecret, (error, result) => return res.status(422).send(error.message) if error? if req.session.callbackUrl? callbackUrl = url.parse req.session.callbackUrl, true delete callbackUrl.search callbackUrl.query.uuid = result.uuid callbackUrl.query.creds_uuid = result.creds.uuid callbackUrl.query.creds_token = result.creds.token return res.redirect url.format(callbackUrl) res.status(201).send result app.get '/', (req, res) -> res.status(422).send message: 'UUID is required' app.get '/new/:uuid', (req, res) -> req.session.userUuid = req.params.uuid req.session.callbackUrl = req.query.callbackUrl debug 'callbackUrl', req.session.callbackUrl res.redirect '/api/authorize' server = app.listen PORT, -> host = server.address().address port = server.address().port console.log "Server running on #{host}:#{port}"
62394
_ = require 'lodash' url = require 'url' cors = require 'cors' morgan = require 'morgan' express = require 'express' passport = require 'passport' session = require 'cookie-session' bodyParser = require 'body-parser' errorHandler = require 'errorhandler' MeshbluAuth = require 'express-meshblu-auth' MeshbluAuthExpress = require 'express-meshblu-auth/src/meshblu-auth-express' MeshbluHealthCheck = require 'express-meshblu-healthcheck' MeshbluConfig = require 'meshblu-config' MeshbluHttp = require 'meshblu-http' debug = require('debug')('little-bits-cloud-proxy') CredentialManager = require './src/models/credential-manager' ProxyRequestModel = require './src/models/proxy-request-model' LittleBitsOptionsBuilder = require './src/models/little-bits-options-builder' meshbluConfig = new MeshbluConfig().toJSON() PORT = process.env.PORT || 80 passport.serializeUser (user, done) -> done null, JSON.stringify user passport.deserializeUser (id, done) -> done null, JSON.parse id app = express() app.use cors() app.use morgan('combined') app.use errorHandler() app.use MeshbluHealthCheck() app.use session cookie: {secure: true}, secret: '<KEY>', name: 'twitter-proxy' app.use passport.initialize() app.use passport.session() app.use bodyParser.urlencoded limit: '50mb', extended : true app.use bodyParser.json limit : '50mb' app.options '*', cors() meshbluAuthorizer = MeshbluAuth server: meshbluConfig.server port: meshbluConfig.port options = messageSchema: require './twitter-message-schema.json' messageFormSchemaUrl: './twitter-form.json' logo: 'https://cdn.octoblu.com/icons/devices/little-bits-cloud.svg' name: 'littleBits Cloud' credentialManager = new CredentialManager options, meshbluConfig app.post '/api/messages', meshbluAuthorizer, (req, res) -> proxyRequest = new ProxyRequestModel meshbluConfig, LittleBitsOptionsBuilder proxyRequest.sendMessage req.body, (error, message) => debug 'sendMessage response', error, message return res.status(422).send(error.message) if error? res.status(201).send message app.get '/api/authorize', (req, res) -> res.sendFile 'index.html', root: __dirname + '/public' app.post '/api/callback', (req, res) -> credentialManager.findOrCreate req.session.userUuid, req.body.clientId, req.body.clientSecret, (error, result) => return res.status(422).send(error.message) if error? if req.session.callbackUrl? callbackUrl = url.parse req.session.callbackUrl, true delete callbackUrl.search callbackUrl.query.uuid = result.uuid callbackUrl.query.creds_uuid = result.creds.uuid callbackUrl.query.creds_token = result.creds.token return res.redirect url.format(callbackUrl) res.status(201).send result app.get '/', (req, res) -> res.status(422).send message: 'UUID is required' app.get '/new/:uuid', (req, res) -> req.session.userUuid = req.params.uuid req.session.callbackUrl = req.query.callbackUrl debug 'callbackUrl', req.session.callbackUrl res.redirect '/api/authorize' server = app.listen PORT, -> host = server.address().address port = server.address().port console.log "Server running on #{host}:#{port}"
true
_ = require 'lodash' url = require 'url' cors = require 'cors' morgan = require 'morgan' express = require 'express' passport = require 'passport' session = require 'cookie-session' bodyParser = require 'body-parser' errorHandler = require 'errorhandler' MeshbluAuth = require 'express-meshblu-auth' MeshbluAuthExpress = require 'express-meshblu-auth/src/meshblu-auth-express' MeshbluHealthCheck = require 'express-meshblu-healthcheck' MeshbluConfig = require 'meshblu-config' MeshbluHttp = require 'meshblu-http' debug = require('debug')('little-bits-cloud-proxy') CredentialManager = require './src/models/credential-manager' ProxyRequestModel = require './src/models/proxy-request-model' LittleBitsOptionsBuilder = require './src/models/little-bits-options-builder' meshbluConfig = new MeshbluConfig().toJSON() PORT = process.env.PORT || 80 passport.serializeUser (user, done) -> done null, JSON.stringify user passport.deserializeUser (id, done) -> done null, JSON.parse id app = express() app.use cors() app.use morgan('combined') app.use errorHandler() app.use MeshbluHealthCheck() app.use session cookie: {secure: true}, secret: 'PI:KEY:<KEY>END_PI', name: 'twitter-proxy' app.use passport.initialize() app.use passport.session() app.use bodyParser.urlencoded limit: '50mb', extended : true app.use bodyParser.json limit : '50mb' app.options '*', cors() meshbluAuthorizer = MeshbluAuth server: meshbluConfig.server port: meshbluConfig.port options = messageSchema: require './twitter-message-schema.json' messageFormSchemaUrl: './twitter-form.json' logo: 'https://cdn.octoblu.com/icons/devices/little-bits-cloud.svg' name: 'littleBits Cloud' credentialManager = new CredentialManager options, meshbluConfig app.post '/api/messages', meshbluAuthorizer, (req, res) -> proxyRequest = new ProxyRequestModel meshbluConfig, LittleBitsOptionsBuilder proxyRequest.sendMessage req.body, (error, message) => debug 'sendMessage response', error, message return res.status(422).send(error.message) if error? res.status(201).send message app.get '/api/authorize', (req, res) -> res.sendFile 'index.html', root: __dirname + '/public' app.post '/api/callback', (req, res) -> credentialManager.findOrCreate req.session.userUuid, req.body.clientId, req.body.clientSecret, (error, result) => return res.status(422).send(error.message) if error? if req.session.callbackUrl? callbackUrl = url.parse req.session.callbackUrl, true delete callbackUrl.search callbackUrl.query.uuid = result.uuid callbackUrl.query.creds_uuid = result.creds.uuid callbackUrl.query.creds_token = result.creds.token return res.redirect url.format(callbackUrl) res.status(201).send result app.get '/', (req, res) -> res.status(422).send message: 'UUID is required' app.get '/new/:uuid', (req, res) -> req.session.userUuid = req.params.uuid req.session.callbackUrl = req.query.callbackUrl debug 'callbackUrl', req.session.callbackUrl res.redirect '/api/authorize' server = app.listen PORT, -> host = server.address().address port = server.address().port console.log "Server running on #{host}:#{port}"
[ { "context": "nfig util', ->\n watchHandler = null\n keyPath = 'emacs-mode:foo'\n\n getConfig = -> atom.config.get keyPath\n setC", "end": 119, "score": 0.9921064376831055, "start": 105, "tag": "KEY", "value": "emacs-mode:foo" } ]
packages/emacs-mode/spec/config-util-spec.coffee
jakepearson/atom
1
configUtil = require '../lib/config-util' describe 'config util', -> watchHandler = null keyPath = 'emacs-mode:foo' getConfig = -> atom.config.get keyPath setConfig = (value) -> atom.config.set keyPath, value beforeEach -> setConfig null watchHandler = jasmine.createSpy 'watchHandler' it 'should write default value if key does not exists', -> configUtil.watch keyPath, false, watchHandler expect(getConfig()).toBe(false) expect(watchHandler).toHaveBeenCalledWith(false) it 'should not write default value if key exists', -> setConfig false configUtil.watch keyPath, true, watchHandler expect(watchHandler).toHaveBeenCalledWith(false) expect(getConfig()).toBe(false) it 'should work with only two arguments', -> configUtil.watch keyPath, watchHandler setConfig true expect(watchHandler).toHaveBeenCalledWith(true) it 'should call handler with null if no config exists', -> configUtil.watch keyPath, watchHandler expect(watchHandler).toHaveBeenCalledWith(null) it 'should not throw error if there is only one argument', -> expect(-> configUtil.watch keyPath ).not.toThrow()
19647
configUtil = require '../lib/config-util' describe 'config util', -> watchHandler = null keyPath = '<KEY>' getConfig = -> atom.config.get keyPath setConfig = (value) -> atom.config.set keyPath, value beforeEach -> setConfig null watchHandler = jasmine.createSpy 'watchHandler' it 'should write default value if key does not exists', -> configUtil.watch keyPath, false, watchHandler expect(getConfig()).toBe(false) expect(watchHandler).toHaveBeenCalledWith(false) it 'should not write default value if key exists', -> setConfig false configUtil.watch keyPath, true, watchHandler expect(watchHandler).toHaveBeenCalledWith(false) expect(getConfig()).toBe(false) it 'should work with only two arguments', -> configUtil.watch keyPath, watchHandler setConfig true expect(watchHandler).toHaveBeenCalledWith(true) it 'should call handler with null if no config exists', -> configUtil.watch keyPath, watchHandler expect(watchHandler).toHaveBeenCalledWith(null) it 'should not throw error if there is only one argument', -> expect(-> configUtil.watch keyPath ).not.toThrow()
true
configUtil = require '../lib/config-util' describe 'config util', -> watchHandler = null keyPath = 'PI:KEY:<KEY>END_PI' getConfig = -> atom.config.get keyPath setConfig = (value) -> atom.config.set keyPath, value beforeEach -> setConfig null watchHandler = jasmine.createSpy 'watchHandler' it 'should write default value if key does not exists', -> configUtil.watch keyPath, false, watchHandler expect(getConfig()).toBe(false) expect(watchHandler).toHaveBeenCalledWith(false) it 'should not write default value if key exists', -> setConfig false configUtil.watch keyPath, true, watchHandler expect(watchHandler).toHaveBeenCalledWith(false) expect(getConfig()).toBe(false) it 'should work with only two arguments', -> configUtil.watch keyPath, watchHandler setConfig true expect(watchHandler).toHaveBeenCalledWith(true) it 'should call handler with null if no config exists', -> configUtil.watch keyPath, watchHandler expect(watchHandler).toHaveBeenCalledWith(null) it 'should not throw error if there is only one argument', -> expect(-> configUtil.watch keyPath ).not.toThrow()
[ { "context": " code: \"such-test-coupon\"\n name: \"Such Test Coupon\"\n type: \"flat\"\n startDate: new Date()\n", "end": 143, "score": 0.9806158542633057, "start": 127, "tag": "NAME", "value": "Such Test Coupon" } ]
test/server/coupon.coffee
hanzo-io/hanzo.js
147
moment = require 'moment-timezone' describe 'Api.coupon', -> testCoupon = code: "such-test-coupon" name: "Such Test Coupon" type: "flat" startDate: new Date() endDate: moment(new Date()).add(1, 'month') once: true enabled: true amount: 500 describe '.list', -> it 'should list coupons', -> {count, models} = yield api.coupon.list() models.length.should.be.gt 0 count.should.be.gt 0 describe '.get', -> it 'should get coupon', -> coupon = yield api.coupon.get 'such-coupon' coupon.amount.should.equal 500 describe '.create, .delete', -> it 'should create and delete coupons', -> coupon = yield api.coupon.create testCoupon coupon.amount.should.eq testCoupon.amount res = null tryDelete = -> try res = yield api.coupon.delete code: coupon.code catch err setTimeout tryDelete, 500 describe '.update', -> it 'should update coupons', -> coupon = yield api.coupon.update code: 'SUCH-COUPON' coupon.amount.should.eq 500
50516
moment = require 'moment-timezone' describe 'Api.coupon', -> testCoupon = code: "such-test-coupon" name: "<NAME>" type: "flat" startDate: new Date() endDate: moment(new Date()).add(1, 'month') once: true enabled: true amount: 500 describe '.list', -> it 'should list coupons', -> {count, models} = yield api.coupon.list() models.length.should.be.gt 0 count.should.be.gt 0 describe '.get', -> it 'should get coupon', -> coupon = yield api.coupon.get 'such-coupon' coupon.amount.should.equal 500 describe '.create, .delete', -> it 'should create and delete coupons', -> coupon = yield api.coupon.create testCoupon coupon.amount.should.eq testCoupon.amount res = null tryDelete = -> try res = yield api.coupon.delete code: coupon.code catch err setTimeout tryDelete, 500 describe '.update', -> it 'should update coupons', -> coupon = yield api.coupon.update code: 'SUCH-COUPON' coupon.amount.should.eq 500
true
moment = require 'moment-timezone' describe 'Api.coupon', -> testCoupon = code: "such-test-coupon" name: "PI:NAME:<NAME>END_PI" type: "flat" startDate: new Date() endDate: moment(new Date()).add(1, 'month') once: true enabled: true amount: 500 describe '.list', -> it 'should list coupons', -> {count, models} = yield api.coupon.list() models.length.should.be.gt 0 count.should.be.gt 0 describe '.get', -> it 'should get coupon', -> coupon = yield api.coupon.get 'such-coupon' coupon.amount.should.equal 500 describe '.create, .delete', -> it 'should create and delete coupons', -> coupon = yield api.coupon.create testCoupon coupon.amount.should.eq testCoupon.amount res = null tryDelete = -> try res = yield api.coupon.delete code: coupon.code catch err setTimeout tryDelete, 500 describe '.update', -> it 'should update coupons', -> coupon = yield api.coupon.update code: 'SUCH-COUPON' coupon.amount.should.eq 500
[ { "context": "scription: Analytics for programmers.\nMaintainer: WakaTime <support@wakatime.com>\nLicense: BSD, see LICE", "end": 74, "score": 0.9889010787010193, "start": 66, "tag": "USERNAME", "value": "WakaTime" }, { "context": "Analytics for programmers.\nMaintainer: WakaTime <support@wakatime.com>\nLicense: BSD, see LICENSE for more details.\n", "end": 96, "score": 0.9999261498451233, "start": 76, "tag": "EMAIL", "value": "support@wakatime.com" }, { "context": "ck) ->\n url = 'https://raw.githubusercontent.com/wakatime/wakatime/master/wakatime/__about__.py'\n request.", "end": 7745, "score": 0.9996289610862732, "start": 7737, "tag": "USERNAME", "value": "wakatime" }, { "context": "ding wakatime cli...'\n url = 'https://github.com/wakatime/wakatime/archive/master.zip'\n zipFile = __dirnam", "end": 8407, "score": 0.9996116161346436, "start": 8399, "tag": "USERNAME", "value": "wakatime" } ]
atom.symlink/packages/wakatime/lib/wakatime.coffee
sanata-/dotenv
0
### WakaTime Description: Analytics for programmers. Maintainer: WakaTime <support@wakatime.com> License: BSD, see LICENSE for more details. Website: https://wakatime.com/ ### # package-global attributes packageVersion = null unloadHandler = null lastHeartbeat = 0 lastFile = '' apiKey = null # lazy-load packages during activation to speed up Atom startup time AdmZip = null fs = null os = null path = null execFile = null request = null rimraf = null ini = null module.exports = config: apikey: title: 'Api Key' description: 'Your secret key from https://wakatime.com/settings.' type: 'string' default: '' order: 1 ignore: title: 'Exclude File Paths' description: 'Exclude these file paths from logging; POSIX regex patterns' type: 'array' default: ['^/var/', '^/tmp/', '^/private/', 'COMMIT_EDITMSG$', 'PULLREQ_EDITMSG$', 'MERGE_MSG$'] items: type: 'string' order: 2 activate: (state) -> packageVersion = atom.packages.getLoadedPackage('wakatime').metadata.version loadPackages() if not isCLIInstalled() installCLI(-> console.log 'Finished installing wakatime cli.' ) else isCLILatest((latest) -> if not latest installCLI(-> console.log 'Finished installing wakatime cli.' ) ) isPythonInstalled((installed) -> if not installed atom.confirm message: 'WakaTime requires Python' detailedMessage: 'Let\'s download and install Python now?' buttons: OK: -> installPython() Cancel: -> window.alert('Please install Python (https://www.python.org/downloads/) and restart Atom to enable the WakaTime plugin.') ) cleanupOnUninstall() setupEventHandlers() setApiKey() loadPackages = -> AdmZip = require 'adm-zip' fs = require 'fs' os = require 'os' path = require 'path' execFile = require('child_process').execFile request = require 'request' rimraf = require 'rimraf' ini = require 'ini' getUserHome = -> process.env[if process.platform == 'win32' then 'USERPROFILE' else 'HOME'] || '' setApiKey = -> loadApiKey (err, key) -> if err console.log err.message else apiKey = key loadApiKey = (cb) -> key = atom.config.get('wakatime.apikey') return cb(null, key) if key? && key.length > 0 wakatimeConfigFile = path.join getUserHome(), '.wakatime.cfg' fs.readFile wakatimeConfigFile, 'utf-8', (err, configContent) -> return cb(new Error('could not read wakatime config')) if err? wakatimeConfig = ini.parse configContent key = wakatimeConfig?.settings?.api_key if key? cb null, key else cb new Error('wakatime key not found') enoughTimePassed = (time) -> return lastHeartbeat + 120000 < time cleanupOnUninstall = () -> if unloadHandler? unloadHandler.dispose() unloadHandler = null unloadHandler = atom.packages.onDidUnloadPackage((p) -> if p? and p.name == 'wakatime' removeCLI() if unloadHandler? unloadHandler.dispose() unloadHandler = null ) setupEventHandlers = () -> atom.workspace.observeTextEditors (editor) => try buffer = editor.getBuffer() buffer.onDidSave (e) => file = buffer.file if file? and file lineno = null if editor.cursors.length > 0 lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1 sendHeartbeat(file, lineno, true) buffer.onDidChange (e) => file = buffer.file if file? and file lineno = null if editor.cursors.length > 0 lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1 sendHeartbeat(file, lineno) editor.onDidChangeCursorPosition (e) => file = buffer.file if file? and file lineno = null if editor.cursors.length > 0 lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1 sendHeartbeat(file, lineno) isPythonInstalled = (callback) -> pythonLocation((result) -> callback(result?) ) pythonLocation = (callback, locations) -> if global.cachedPythonLocation? callback(global.cachedPythonLocation) else if not locations? locations = [ __dirname + path.sep + 'python' + path.sep + 'pythonw', "pythonw", "python", "/usr/local/bin/python", "/usr/bin/python", "\\python37\\pythonw", "\\Python37\\pythonw", "\\python36\\pythonw", "\\Python36\\pythonw", "\\python35\\pythonw", "\\Python35\\pythonw", "\\python34\\pythonw", "\\Python34\\pythonw", "\\python33\\pythonw", "\\Python33\\pythonw", "\\python32\\pythonw", "\\Python32\\pythonw", "\\python31\\pythonw", "\\Python31\\pythonw", "\\python30\\pythonw", "\\Python30\\pythonw", "\\python27\\pythonw", "\\Python27\\pythonw", "\\python26\\pythonw", "\\Python26\\pythonw", "\\python37\\python", "\\Python37\\python", "\\python36\\python", "\\Python36\\python", "\\python35\\python", "\\Python35\\python", "\\python34\\python", "\\Python34\\python", "\\python33\\python", "\\Python33\\python", "\\python32\\python", "\\Python32\\python", "\\python31\\python", "\\Python31\\python", "\\python30\\python", "\\Python30\\python", "\\python27\\python", "\\Python27\\python", "\\python26\\python", "\\Python26\\python", ] args = ['--version'] if locations.length is 0 callback(null) return location = locations[0] execFile(location, args, (error, stdout, stderr) -> if not error? global.cachedPythonLocation = location callback(location) else locations.splice(0, 1) pythonLocation(callback, locations) ) installPython = () -> if os.type() is 'Windows_NT' pyVer = '3.5.0' arch = 'win32' if os.arch().indexOf('x64') > -1 arch = 'amd64' url = 'https://www.python.org/ftp/python/' + pyVer + '/python-' + pyVer + '-embed-' + arch + '.zip' console.log 'Downloading python...' zipFile = __dirname + path.sep + 'python.zip' downloadFile(url, zipFile, -> console.log 'Extracting python...' unzip(zipFile, __dirname + path.sep + 'python', -> fs.unlink(zipFile) console.log 'Finished installing python.' ) ) else window.alert('WakaTime depends on Python. Install it from https://python.org/downloads then restart Atom.') isCLIInstalled = () -> return fs.existsSync(cliLocation()) isCLILatest = (callback) -> pythonLocation((python) -> if python? args = [cliLocation(), '--version'] execFile(python, args, (error, stdout, stderr) -> if not error? currentVersion = stderr.trim() console.log 'Current wakatime-cli version is ' + currentVersion console.log 'Checking for updates to wakatime-cli...' getLatestCliVersion((latestVersion) -> if currentVersion == latestVersion console.log 'wakatime-cli is up to date.' if callback? callback(true) else console.log 'Found an updated wakatime-cli v' + latestVersion if callback? callback(false) ) else if callback? callback(false) ) ) getLatestCliVersion = (callback) -> url = 'https://raw.githubusercontent.com/wakatime/wakatime/master/wakatime/__about__.py' request.get(url, (error, response, body) -> version = null if !error and response.statusCode == 200 re = new RegExp(/__version_info__ = \('([0-9]+)', '([0-9]+)', '([0-9]+)'\)/g) for line in body.split('\n') match = re.exec(line) if match? version = match[1] + '.' + match[2] + '.' + match[3] if callback? callback(version) ) cliLocation = () -> dir = __dirname + path.sep + 'wakatime-master' + path.sep + 'wakatime' + path.sep + 'cli.py' return dir installCLI = (callback) -> console.log 'Downloading wakatime cli...' url = 'https://github.com/wakatime/wakatime/archive/master.zip' zipFile = __dirname + path.sep + 'wakatime-master.zip' downloadFile(url, zipFile, -> extractCLI(zipFile, callback) ) extractCLI = (zipFile, callback) -> console.log 'Extracting wakatime-master.zip file...' removeCLI(-> unzip(zipFile, __dirname, callback) ) removeCLI = (callback) -> if fs.existsSync(__dirname + path.sep + 'wakatime-master') try rimraf(__dirname + path.sep + 'wakatime-master', -> if callback? callback() ) catch e console.warn e if callback? callback() else if callback? callback() downloadFile = (url, outputFile, callback) -> r = request(url) out = fs.createWriteStream(outputFile) r.pipe(out) r.on('end', -> out.on('finish', -> if callback? callback() ) ) unzip = (file, outputDir, callback) -> if fs.existsSync(file) try zip = new AdmZip(file) zip.extractAllTo(outputDir, true) catch e console.warn e finally fs.unlink(file) if callback? callback() sendHeartbeat = (file, lineno, isWrite) -> time = Date.now() if isWrite or enoughTimePassed(time) or lastFile isnt file.path if not file.path? or file.path is undefined or fileIsIgnored(file.path) return pythonLocation (python) -> return unless python? && apiKey? args = [cliLocation(), '--file', file.path, '--key', apiKey, '--plugin', 'atom-wakatime/' + packageVersion] if isWrite args.push('--write') if lineno? args.push('--lineno') args.push(lineno) proc = execFile(python, args, (error, stdout, stderr) -> if error? if stderr? and stderr != '' console.warn stderr if stdout? and stdout != '' console.warn stdout if proc.exitCode == 102 console.warn 'Warning: api error (102); Check your ~/.wakatime.log file for more details.' else if proc.exitCode == 103 console.warn 'Warning: config parsing error (103); Check your ~/.wakatime.log file for more details.' else console.warn error ) lastHeartbeat = time lastFile = file.path fileIsIgnored = (file) -> if endsWith(file, 'COMMIT_EDITMSG') or endsWith(file, 'PULLREQ_EDITMSG') or endsWith(file, 'MERGE_MSG') or endsWith(file, 'TAG_EDITMSG') return true patterns = atom.config.get('wakatime.ignore') ignore = false for pattern in patterns re = new RegExp(pattern, 'gi') if re.test(file) ignore = true break return ignore endsWith = (str, suffix) -> if str? and suffix? return str.indexOf(suffix, str.length - suffix.length) != -1 return false
80735
### WakaTime Description: Analytics for programmers. Maintainer: WakaTime <<EMAIL>> License: BSD, see LICENSE for more details. Website: https://wakatime.com/ ### # package-global attributes packageVersion = null unloadHandler = null lastHeartbeat = 0 lastFile = '' apiKey = null # lazy-load packages during activation to speed up Atom startup time AdmZip = null fs = null os = null path = null execFile = null request = null rimraf = null ini = null module.exports = config: apikey: title: 'Api Key' description: 'Your secret key from https://wakatime.com/settings.' type: 'string' default: '' order: 1 ignore: title: 'Exclude File Paths' description: 'Exclude these file paths from logging; POSIX regex patterns' type: 'array' default: ['^/var/', '^/tmp/', '^/private/', 'COMMIT_EDITMSG$', 'PULLREQ_EDITMSG$', 'MERGE_MSG$'] items: type: 'string' order: 2 activate: (state) -> packageVersion = atom.packages.getLoadedPackage('wakatime').metadata.version loadPackages() if not isCLIInstalled() installCLI(-> console.log 'Finished installing wakatime cli.' ) else isCLILatest((latest) -> if not latest installCLI(-> console.log 'Finished installing wakatime cli.' ) ) isPythonInstalled((installed) -> if not installed atom.confirm message: 'WakaTime requires Python' detailedMessage: 'Let\'s download and install Python now?' buttons: OK: -> installPython() Cancel: -> window.alert('Please install Python (https://www.python.org/downloads/) and restart Atom to enable the WakaTime plugin.') ) cleanupOnUninstall() setupEventHandlers() setApiKey() loadPackages = -> AdmZip = require 'adm-zip' fs = require 'fs' os = require 'os' path = require 'path' execFile = require('child_process').execFile request = require 'request' rimraf = require 'rimraf' ini = require 'ini' getUserHome = -> process.env[if process.platform == 'win32' then 'USERPROFILE' else 'HOME'] || '' setApiKey = -> loadApiKey (err, key) -> if err console.log err.message else apiKey = key loadApiKey = (cb) -> key = atom.config.get('wakatime.apikey') return cb(null, key) if key? && key.length > 0 wakatimeConfigFile = path.join getUserHome(), '.wakatime.cfg' fs.readFile wakatimeConfigFile, 'utf-8', (err, configContent) -> return cb(new Error('could not read wakatime config')) if err? wakatimeConfig = ini.parse configContent key = wakatimeConfig?.settings?.api_key if key? cb null, key else cb new Error('wakatime key not found') enoughTimePassed = (time) -> return lastHeartbeat + 120000 < time cleanupOnUninstall = () -> if unloadHandler? unloadHandler.dispose() unloadHandler = null unloadHandler = atom.packages.onDidUnloadPackage((p) -> if p? and p.name == 'wakatime' removeCLI() if unloadHandler? unloadHandler.dispose() unloadHandler = null ) setupEventHandlers = () -> atom.workspace.observeTextEditors (editor) => try buffer = editor.getBuffer() buffer.onDidSave (e) => file = buffer.file if file? and file lineno = null if editor.cursors.length > 0 lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1 sendHeartbeat(file, lineno, true) buffer.onDidChange (e) => file = buffer.file if file? and file lineno = null if editor.cursors.length > 0 lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1 sendHeartbeat(file, lineno) editor.onDidChangeCursorPosition (e) => file = buffer.file if file? and file lineno = null if editor.cursors.length > 0 lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1 sendHeartbeat(file, lineno) isPythonInstalled = (callback) -> pythonLocation((result) -> callback(result?) ) pythonLocation = (callback, locations) -> if global.cachedPythonLocation? callback(global.cachedPythonLocation) else if not locations? locations = [ __dirname + path.sep + 'python' + path.sep + 'pythonw', "pythonw", "python", "/usr/local/bin/python", "/usr/bin/python", "\\python37\\pythonw", "\\Python37\\pythonw", "\\python36\\pythonw", "\\Python36\\pythonw", "\\python35\\pythonw", "\\Python35\\pythonw", "\\python34\\pythonw", "\\Python34\\pythonw", "\\python33\\pythonw", "\\Python33\\pythonw", "\\python32\\pythonw", "\\Python32\\pythonw", "\\python31\\pythonw", "\\Python31\\pythonw", "\\python30\\pythonw", "\\Python30\\pythonw", "\\python27\\pythonw", "\\Python27\\pythonw", "\\python26\\pythonw", "\\Python26\\pythonw", "\\python37\\python", "\\Python37\\python", "\\python36\\python", "\\Python36\\python", "\\python35\\python", "\\Python35\\python", "\\python34\\python", "\\Python34\\python", "\\python33\\python", "\\Python33\\python", "\\python32\\python", "\\Python32\\python", "\\python31\\python", "\\Python31\\python", "\\python30\\python", "\\Python30\\python", "\\python27\\python", "\\Python27\\python", "\\python26\\python", "\\Python26\\python", ] args = ['--version'] if locations.length is 0 callback(null) return location = locations[0] execFile(location, args, (error, stdout, stderr) -> if not error? global.cachedPythonLocation = location callback(location) else locations.splice(0, 1) pythonLocation(callback, locations) ) installPython = () -> if os.type() is 'Windows_NT' pyVer = '3.5.0' arch = 'win32' if os.arch().indexOf('x64') > -1 arch = 'amd64' url = 'https://www.python.org/ftp/python/' + pyVer + '/python-' + pyVer + '-embed-' + arch + '.zip' console.log 'Downloading python...' zipFile = __dirname + path.sep + 'python.zip' downloadFile(url, zipFile, -> console.log 'Extracting python...' unzip(zipFile, __dirname + path.sep + 'python', -> fs.unlink(zipFile) console.log 'Finished installing python.' ) ) else window.alert('WakaTime depends on Python. Install it from https://python.org/downloads then restart Atom.') isCLIInstalled = () -> return fs.existsSync(cliLocation()) isCLILatest = (callback) -> pythonLocation((python) -> if python? args = [cliLocation(), '--version'] execFile(python, args, (error, stdout, stderr) -> if not error? currentVersion = stderr.trim() console.log 'Current wakatime-cli version is ' + currentVersion console.log 'Checking for updates to wakatime-cli...' getLatestCliVersion((latestVersion) -> if currentVersion == latestVersion console.log 'wakatime-cli is up to date.' if callback? callback(true) else console.log 'Found an updated wakatime-cli v' + latestVersion if callback? callback(false) ) else if callback? callback(false) ) ) getLatestCliVersion = (callback) -> url = 'https://raw.githubusercontent.com/wakatime/wakatime/master/wakatime/__about__.py' request.get(url, (error, response, body) -> version = null if !error and response.statusCode == 200 re = new RegExp(/__version_info__ = \('([0-9]+)', '([0-9]+)', '([0-9]+)'\)/g) for line in body.split('\n') match = re.exec(line) if match? version = match[1] + '.' + match[2] + '.' + match[3] if callback? callback(version) ) cliLocation = () -> dir = __dirname + path.sep + 'wakatime-master' + path.sep + 'wakatime' + path.sep + 'cli.py' return dir installCLI = (callback) -> console.log 'Downloading wakatime cli...' url = 'https://github.com/wakatime/wakatime/archive/master.zip' zipFile = __dirname + path.sep + 'wakatime-master.zip' downloadFile(url, zipFile, -> extractCLI(zipFile, callback) ) extractCLI = (zipFile, callback) -> console.log 'Extracting wakatime-master.zip file...' removeCLI(-> unzip(zipFile, __dirname, callback) ) removeCLI = (callback) -> if fs.existsSync(__dirname + path.sep + 'wakatime-master') try rimraf(__dirname + path.sep + 'wakatime-master', -> if callback? callback() ) catch e console.warn e if callback? callback() else if callback? callback() downloadFile = (url, outputFile, callback) -> r = request(url) out = fs.createWriteStream(outputFile) r.pipe(out) r.on('end', -> out.on('finish', -> if callback? callback() ) ) unzip = (file, outputDir, callback) -> if fs.existsSync(file) try zip = new AdmZip(file) zip.extractAllTo(outputDir, true) catch e console.warn e finally fs.unlink(file) if callback? callback() sendHeartbeat = (file, lineno, isWrite) -> time = Date.now() if isWrite or enoughTimePassed(time) or lastFile isnt file.path if not file.path? or file.path is undefined or fileIsIgnored(file.path) return pythonLocation (python) -> return unless python? && apiKey? args = [cliLocation(), '--file', file.path, '--key', apiKey, '--plugin', 'atom-wakatime/' + packageVersion] if isWrite args.push('--write') if lineno? args.push('--lineno') args.push(lineno) proc = execFile(python, args, (error, stdout, stderr) -> if error? if stderr? and stderr != '' console.warn stderr if stdout? and stdout != '' console.warn stdout if proc.exitCode == 102 console.warn 'Warning: api error (102); Check your ~/.wakatime.log file for more details.' else if proc.exitCode == 103 console.warn 'Warning: config parsing error (103); Check your ~/.wakatime.log file for more details.' else console.warn error ) lastHeartbeat = time lastFile = file.path fileIsIgnored = (file) -> if endsWith(file, 'COMMIT_EDITMSG') or endsWith(file, 'PULLREQ_EDITMSG') or endsWith(file, 'MERGE_MSG') or endsWith(file, 'TAG_EDITMSG') return true patterns = atom.config.get('wakatime.ignore') ignore = false for pattern in patterns re = new RegExp(pattern, 'gi') if re.test(file) ignore = true break return ignore endsWith = (str, suffix) -> if str? and suffix? return str.indexOf(suffix, str.length - suffix.length) != -1 return false
true
### WakaTime Description: Analytics for programmers. Maintainer: WakaTime <PI:EMAIL:<EMAIL>END_PI> License: BSD, see LICENSE for more details. Website: https://wakatime.com/ ### # package-global attributes packageVersion = null unloadHandler = null lastHeartbeat = 0 lastFile = '' apiKey = null # lazy-load packages during activation to speed up Atom startup time AdmZip = null fs = null os = null path = null execFile = null request = null rimraf = null ini = null module.exports = config: apikey: title: 'Api Key' description: 'Your secret key from https://wakatime.com/settings.' type: 'string' default: '' order: 1 ignore: title: 'Exclude File Paths' description: 'Exclude these file paths from logging; POSIX regex patterns' type: 'array' default: ['^/var/', '^/tmp/', '^/private/', 'COMMIT_EDITMSG$', 'PULLREQ_EDITMSG$', 'MERGE_MSG$'] items: type: 'string' order: 2 activate: (state) -> packageVersion = atom.packages.getLoadedPackage('wakatime').metadata.version loadPackages() if not isCLIInstalled() installCLI(-> console.log 'Finished installing wakatime cli.' ) else isCLILatest((latest) -> if not latest installCLI(-> console.log 'Finished installing wakatime cli.' ) ) isPythonInstalled((installed) -> if not installed atom.confirm message: 'WakaTime requires Python' detailedMessage: 'Let\'s download and install Python now?' buttons: OK: -> installPython() Cancel: -> window.alert('Please install Python (https://www.python.org/downloads/) and restart Atom to enable the WakaTime plugin.') ) cleanupOnUninstall() setupEventHandlers() setApiKey() loadPackages = -> AdmZip = require 'adm-zip' fs = require 'fs' os = require 'os' path = require 'path' execFile = require('child_process').execFile request = require 'request' rimraf = require 'rimraf' ini = require 'ini' getUserHome = -> process.env[if process.platform == 'win32' then 'USERPROFILE' else 'HOME'] || '' setApiKey = -> loadApiKey (err, key) -> if err console.log err.message else apiKey = key loadApiKey = (cb) -> key = atom.config.get('wakatime.apikey') return cb(null, key) if key? && key.length > 0 wakatimeConfigFile = path.join getUserHome(), '.wakatime.cfg' fs.readFile wakatimeConfigFile, 'utf-8', (err, configContent) -> return cb(new Error('could not read wakatime config')) if err? wakatimeConfig = ini.parse configContent key = wakatimeConfig?.settings?.api_key if key? cb null, key else cb new Error('wakatime key not found') enoughTimePassed = (time) -> return lastHeartbeat + 120000 < time cleanupOnUninstall = () -> if unloadHandler? unloadHandler.dispose() unloadHandler = null unloadHandler = atom.packages.onDidUnloadPackage((p) -> if p? and p.name == 'wakatime' removeCLI() if unloadHandler? unloadHandler.dispose() unloadHandler = null ) setupEventHandlers = () -> atom.workspace.observeTextEditors (editor) => try buffer = editor.getBuffer() buffer.onDidSave (e) => file = buffer.file if file? and file lineno = null if editor.cursors.length > 0 lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1 sendHeartbeat(file, lineno, true) buffer.onDidChange (e) => file = buffer.file if file? and file lineno = null if editor.cursors.length > 0 lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1 sendHeartbeat(file, lineno) editor.onDidChangeCursorPosition (e) => file = buffer.file if file? and file lineno = null if editor.cursors.length > 0 lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1 sendHeartbeat(file, lineno) isPythonInstalled = (callback) -> pythonLocation((result) -> callback(result?) ) pythonLocation = (callback, locations) -> if global.cachedPythonLocation? callback(global.cachedPythonLocation) else if not locations? locations = [ __dirname + path.sep + 'python' + path.sep + 'pythonw', "pythonw", "python", "/usr/local/bin/python", "/usr/bin/python", "\\python37\\pythonw", "\\Python37\\pythonw", "\\python36\\pythonw", "\\Python36\\pythonw", "\\python35\\pythonw", "\\Python35\\pythonw", "\\python34\\pythonw", "\\Python34\\pythonw", "\\python33\\pythonw", "\\Python33\\pythonw", "\\python32\\pythonw", "\\Python32\\pythonw", "\\python31\\pythonw", "\\Python31\\pythonw", "\\python30\\pythonw", "\\Python30\\pythonw", "\\python27\\pythonw", "\\Python27\\pythonw", "\\python26\\pythonw", "\\Python26\\pythonw", "\\python37\\python", "\\Python37\\python", "\\python36\\python", "\\Python36\\python", "\\python35\\python", "\\Python35\\python", "\\python34\\python", "\\Python34\\python", "\\python33\\python", "\\Python33\\python", "\\python32\\python", "\\Python32\\python", "\\python31\\python", "\\Python31\\python", "\\python30\\python", "\\Python30\\python", "\\python27\\python", "\\Python27\\python", "\\python26\\python", "\\Python26\\python", ] args = ['--version'] if locations.length is 0 callback(null) return location = locations[0] execFile(location, args, (error, stdout, stderr) -> if not error? global.cachedPythonLocation = location callback(location) else locations.splice(0, 1) pythonLocation(callback, locations) ) installPython = () -> if os.type() is 'Windows_NT' pyVer = '3.5.0' arch = 'win32' if os.arch().indexOf('x64') > -1 arch = 'amd64' url = 'https://www.python.org/ftp/python/' + pyVer + '/python-' + pyVer + '-embed-' + arch + '.zip' console.log 'Downloading python...' zipFile = __dirname + path.sep + 'python.zip' downloadFile(url, zipFile, -> console.log 'Extracting python...' unzip(zipFile, __dirname + path.sep + 'python', -> fs.unlink(zipFile) console.log 'Finished installing python.' ) ) else window.alert('WakaTime depends on Python. Install it from https://python.org/downloads then restart Atom.') isCLIInstalled = () -> return fs.existsSync(cliLocation()) isCLILatest = (callback) -> pythonLocation((python) -> if python? args = [cliLocation(), '--version'] execFile(python, args, (error, stdout, stderr) -> if not error? currentVersion = stderr.trim() console.log 'Current wakatime-cli version is ' + currentVersion console.log 'Checking for updates to wakatime-cli...' getLatestCliVersion((latestVersion) -> if currentVersion == latestVersion console.log 'wakatime-cli is up to date.' if callback? callback(true) else console.log 'Found an updated wakatime-cli v' + latestVersion if callback? callback(false) ) else if callback? callback(false) ) ) getLatestCliVersion = (callback) -> url = 'https://raw.githubusercontent.com/wakatime/wakatime/master/wakatime/__about__.py' request.get(url, (error, response, body) -> version = null if !error and response.statusCode == 200 re = new RegExp(/__version_info__ = \('([0-9]+)', '([0-9]+)', '([0-9]+)'\)/g) for line in body.split('\n') match = re.exec(line) if match? version = match[1] + '.' + match[2] + '.' + match[3] if callback? callback(version) ) cliLocation = () -> dir = __dirname + path.sep + 'wakatime-master' + path.sep + 'wakatime' + path.sep + 'cli.py' return dir installCLI = (callback) -> console.log 'Downloading wakatime cli...' url = 'https://github.com/wakatime/wakatime/archive/master.zip' zipFile = __dirname + path.sep + 'wakatime-master.zip' downloadFile(url, zipFile, -> extractCLI(zipFile, callback) ) extractCLI = (zipFile, callback) -> console.log 'Extracting wakatime-master.zip file...' removeCLI(-> unzip(zipFile, __dirname, callback) ) removeCLI = (callback) -> if fs.existsSync(__dirname + path.sep + 'wakatime-master') try rimraf(__dirname + path.sep + 'wakatime-master', -> if callback? callback() ) catch e console.warn e if callback? callback() else if callback? callback() downloadFile = (url, outputFile, callback) -> r = request(url) out = fs.createWriteStream(outputFile) r.pipe(out) r.on('end', -> out.on('finish', -> if callback? callback() ) ) unzip = (file, outputDir, callback) -> if fs.existsSync(file) try zip = new AdmZip(file) zip.extractAllTo(outputDir, true) catch e console.warn e finally fs.unlink(file) if callback? callback() sendHeartbeat = (file, lineno, isWrite) -> time = Date.now() if isWrite or enoughTimePassed(time) or lastFile isnt file.path if not file.path? or file.path is undefined or fileIsIgnored(file.path) return pythonLocation (python) -> return unless python? && apiKey? args = [cliLocation(), '--file', file.path, '--key', apiKey, '--plugin', 'atom-wakatime/' + packageVersion] if isWrite args.push('--write') if lineno? args.push('--lineno') args.push(lineno) proc = execFile(python, args, (error, stdout, stderr) -> if error? if stderr? and stderr != '' console.warn stderr if stdout? and stdout != '' console.warn stdout if proc.exitCode == 102 console.warn 'Warning: api error (102); Check your ~/.wakatime.log file for more details.' else if proc.exitCode == 103 console.warn 'Warning: config parsing error (103); Check your ~/.wakatime.log file for more details.' else console.warn error ) lastHeartbeat = time lastFile = file.path fileIsIgnored = (file) -> if endsWith(file, 'COMMIT_EDITMSG') or endsWith(file, 'PULLREQ_EDITMSG') or endsWith(file, 'MERGE_MSG') or endsWith(file, 'TAG_EDITMSG') return true patterns = atom.config.get('wakatime.ignore') ignore = false for pattern in patterns re = new RegExp(pattern, 'gi') if re.test(file) ignore = true break return ignore endsWith = (str, suffix) -> if str? and suffix? return str.indexOf(suffix, str.length - suffix.length) != -1 return false
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.999912440776825, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/react/profile-page/beatmap-playcount.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import * as React from 'react' import { a, div, h2, h3, img, p, small, span } from 'react-dom-factories' el = React.createElement bn = 'beatmap-playcount' export class BeatmapPlaycount extends React.PureComponent render: => beatmap = @props.playcount.beatmap beatmapset = @props.playcount.beatmapset beatmapsetUrl = laroute.route 'beatmaps.show', beatmap: beatmap.id div className: bn a href: beatmapsetUrl className: "#{bn}__cover" style: backgroundImage: osu.urlPresence(beatmapset.covers.list) div className: "#{bn}__cover-count", @renderPlaycountText() div className: "#{bn}__detail" div className: "#{bn}__info" div className: "#{bn}__info-row u-ellipsis-overflow" a className: "#{bn}__title" href: beatmapsetUrl "#{beatmapset.title} [#{beatmap.version}] " span className: "#{bn}__title-artist" osu.trans('users.show.extra.beatmaps.by_artist', artist: beatmapset.artist) div className: "#{bn}__info-row u-ellipsis-overflow" span className: "#{bn}__artist" dangerouslySetInnerHTML: __html: osu.trans('users.show.extra.beatmaps.by_artist', artist: "<strong>#{_.escape(beatmapset.artist)}</strong>") ' ' # separator for overflow tooltip span className: "#{bn}__mapper" dangerouslySetInnerHTML: __html: osu.trans 'beatmapsets.show.details.mapped_by', mapper: laroute.link_to_route 'users.show', beatmapset.creator { user: beatmapset.user_id } class: "#{bn}__mapper-link js-usercard" 'data-user-id': beatmapset.user_id div className: "#{bn}__detail-count" @renderPlaycountText() renderPlaycountText: => div title: osu.trans('users.show.extra.historical.most_played.count') className: "#{bn}__count" span className: "#{bn}__count-icon" span className: 'fas fa-play' osu.formatNumber(@props.playcount.count)
226126
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import * as React from 'react' import { a, div, h2, h3, img, p, small, span } from 'react-dom-factories' el = React.createElement bn = 'beatmap-playcount' export class BeatmapPlaycount extends React.PureComponent render: => beatmap = @props.playcount.beatmap beatmapset = @props.playcount.beatmapset beatmapsetUrl = laroute.route 'beatmaps.show', beatmap: beatmap.id div className: bn a href: beatmapsetUrl className: "#{bn}__cover" style: backgroundImage: osu.urlPresence(beatmapset.covers.list) div className: "#{bn}__cover-count", @renderPlaycountText() div className: "#{bn}__detail" div className: "#{bn}__info" div className: "#{bn}__info-row u-ellipsis-overflow" a className: "#{bn}__title" href: beatmapsetUrl "#{beatmapset.title} [#{beatmap.version}] " span className: "#{bn}__title-artist" osu.trans('users.show.extra.beatmaps.by_artist', artist: beatmapset.artist) div className: "#{bn}__info-row u-ellipsis-overflow" span className: "#{bn}__artist" dangerouslySetInnerHTML: __html: osu.trans('users.show.extra.beatmaps.by_artist', artist: "<strong>#{_.escape(beatmapset.artist)}</strong>") ' ' # separator for overflow tooltip span className: "#{bn}__mapper" dangerouslySetInnerHTML: __html: osu.trans 'beatmapsets.show.details.mapped_by', mapper: laroute.link_to_route 'users.show', beatmapset.creator { user: beatmapset.user_id } class: "#{bn}__mapper-link js-usercard" 'data-user-id': beatmapset.user_id div className: "#{bn}__detail-count" @renderPlaycountText() renderPlaycountText: => div title: osu.trans('users.show.extra.historical.most_played.count') className: "#{bn}__count" span className: "#{bn}__count-icon" span className: 'fas fa-play' osu.formatNumber(@props.playcount.count)
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. import * as React from 'react' import { a, div, h2, h3, img, p, small, span } from 'react-dom-factories' el = React.createElement bn = 'beatmap-playcount' export class BeatmapPlaycount extends React.PureComponent render: => beatmap = @props.playcount.beatmap beatmapset = @props.playcount.beatmapset beatmapsetUrl = laroute.route 'beatmaps.show', beatmap: beatmap.id div className: bn a href: beatmapsetUrl className: "#{bn}__cover" style: backgroundImage: osu.urlPresence(beatmapset.covers.list) div className: "#{bn}__cover-count", @renderPlaycountText() div className: "#{bn}__detail" div className: "#{bn}__info" div className: "#{bn}__info-row u-ellipsis-overflow" a className: "#{bn}__title" href: beatmapsetUrl "#{beatmapset.title} [#{beatmap.version}] " span className: "#{bn}__title-artist" osu.trans('users.show.extra.beatmaps.by_artist', artist: beatmapset.artist) div className: "#{bn}__info-row u-ellipsis-overflow" span className: "#{bn}__artist" dangerouslySetInnerHTML: __html: osu.trans('users.show.extra.beatmaps.by_artist', artist: "<strong>#{_.escape(beatmapset.artist)}</strong>") ' ' # separator for overflow tooltip span className: "#{bn}__mapper" dangerouslySetInnerHTML: __html: osu.trans 'beatmapsets.show.details.mapped_by', mapper: laroute.link_to_route 'users.show', beatmapset.creator { user: beatmapset.user_id } class: "#{bn}__mapper-link js-usercard" 'data-user-id': beatmapset.user_id div className: "#{bn}__detail-count" @renderPlaycountText() renderPlaycountText: => div title: osu.trans('users.show.extra.historical.most_played.count') className: "#{bn}__count" span className: "#{bn}__count-icon" span className: 'fas fa-play' osu.formatNumber(@props.playcount.count)
[ { "context": "y!='timestamp' && key!='Botname')\n\t\t\t\t\t\t\tif(key=='Total_memeory')\n\t\t\t\t\t\t\t\tstr += '|' + 'Total_memory' + '|' + (pa", "end": 1404, "score": 0.9068878889083862, "start": 1391, "tag": "KEY", "value": "Total_memeory" } ]
scripts/master/scripts-mattermost/analytics.coffee
akash1233/OnBot_Demo
4
#------------------------------------------------------------------------------- # Copyright 2018 Cognizant Technology Solutions # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. #------------------------------------------------------------------------------- masterbot = require('./master_bot_analytics.js') # Importing js file as masterbot. botname = process.env.HUBOT_NAME module.exports = (robot) -> analytics = new RegExp('@'+process.env.HUBOT_NAME+' getMetrics (.*)') robot.listen( (message) -> return unless message.text message.text.match analytics (msg) -> first = msg.match[1] masterbot.masterbot first,(error, stdout, stderr) -> if stdout str = '' str += '|' + 'Parameter' + '|' + 'Value' + '|' + '\n' + '| :------------ |:---------------:| -----:|' + '\n'; for key of stdout if(key!='timestamp' && key!='Botname') if(key=='Total_memeory') str += '|' + 'Total_memory' + '|' + (parseFloat((stdout[key]/ Math.pow(1000, Math.floor(Math.log(stdout[key]) / Math.log(1000)))).toFixed(4)) + " " + "GB") + '|' + '\n' # Calculating total memory in GB. else if(key=='uptime') str += '|' + key + '|' + (Math.floor(stdout[key]/ 60 / 60 / 24) + ' Days ' + (Math.floor(stdout[key]/ 60 / 60)) % 24 + ' Hours ' + (Math.floor(stdout[key]/ 60)) % 60 + ' Minutes ' + ((stdout[key]) % 60).toFixed(0) + ' Seconds') + '|' # Calculating uptime in days,hours,minutes and seconds. else if(key=='rss') str += '|' + key + '|' + (parseFloat((stdout[key]/ Math.pow(1024000, Math.floor(Math.log(stdout[key]) / Math.log(1024000)))).toFixed(4)) + " " + "MB") + '|' + '\n' # Calculating rss in MB. else str += '|' + key + '|' + (parseFloat((stdout[key]/ Math.pow(1000, Math.floor(Math.log(stdout[key]) / Math.log(1000)))).toFixed(4)) + " " + "GB") + '|' + '\n' # Calculating memory in GB. msg.send str else if stderr msg.send stderr; else if error msg.send error; )
29685
#------------------------------------------------------------------------------- # Copyright 2018 Cognizant Technology Solutions # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. #------------------------------------------------------------------------------- masterbot = require('./master_bot_analytics.js') # Importing js file as masterbot. botname = process.env.HUBOT_NAME module.exports = (robot) -> analytics = new RegExp('@'+process.env.HUBOT_NAME+' getMetrics (.*)') robot.listen( (message) -> return unless message.text message.text.match analytics (msg) -> first = msg.match[1] masterbot.masterbot first,(error, stdout, stderr) -> if stdout str = '' str += '|' + 'Parameter' + '|' + 'Value' + '|' + '\n' + '| :------------ |:---------------:| -----:|' + '\n'; for key of stdout if(key!='timestamp' && key!='Botname') if(key=='<KEY>') str += '|' + 'Total_memory' + '|' + (parseFloat((stdout[key]/ Math.pow(1000, Math.floor(Math.log(stdout[key]) / Math.log(1000)))).toFixed(4)) + " " + "GB") + '|' + '\n' # Calculating total memory in GB. else if(key=='uptime') str += '|' + key + '|' + (Math.floor(stdout[key]/ 60 / 60 / 24) + ' Days ' + (Math.floor(stdout[key]/ 60 / 60)) % 24 + ' Hours ' + (Math.floor(stdout[key]/ 60)) % 60 + ' Minutes ' + ((stdout[key]) % 60).toFixed(0) + ' Seconds') + '|' # Calculating uptime in days,hours,minutes and seconds. else if(key=='rss') str += '|' + key + '|' + (parseFloat((stdout[key]/ Math.pow(1024000, Math.floor(Math.log(stdout[key]) / Math.log(1024000)))).toFixed(4)) + " " + "MB") + '|' + '\n' # Calculating rss in MB. else str += '|' + key + '|' + (parseFloat((stdout[key]/ Math.pow(1000, Math.floor(Math.log(stdout[key]) / Math.log(1000)))).toFixed(4)) + " " + "GB") + '|' + '\n' # Calculating memory in GB. msg.send str else if stderr msg.send stderr; else if error msg.send error; )
true
#------------------------------------------------------------------------------- # Copyright 2018 Cognizant Technology Solutions # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. #------------------------------------------------------------------------------- masterbot = require('./master_bot_analytics.js') # Importing js file as masterbot. botname = process.env.HUBOT_NAME module.exports = (robot) -> analytics = new RegExp('@'+process.env.HUBOT_NAME+' getMetrics (.*)') robot.listen( (message) -> return unless message.text message.text.match analytics (msg) -> first = msg.match[1] masterbot.masterbot first,(error, stdout, stderr) -> if stdout str = '' str += '|' + 'Parameter' + '|' + 'Value' + '|' + '\n' + '| :------------ |:---------------:| -----:|' + '\n'; for key of stdout if(key!='timestamp' && key!='Botname') if(key=='PI:KEY:<KEY>END_PI') str += '|' + 'Total_memory' + '|' + (parseFloat((stdout[key]/ Math.pow(1000, Math.floor(Math.log(stdout[key]) / Math.log(1000)))).toFixed(4)) + " " + "GB") + '|' + '\n' # Calculating total memory in GB. else if(key=='uptime') str += '|' + key + '|' + (Math.floor(stdout[key]/ 60 / 60 / 24) + ' Days ' + (Math.floor(stdout[key]/ 60 / 60)) % 24 + ' Hours ' + (Math.floor(stdout[key]/ 60)) % 60 + ' Minutes ' + ((stdout[key]) % 60).toFixed(0) + ' Seconds') + '|' # Calculating uptime in days,hours,minutes and seconds. else if(key=='rss') str += '|' + key + '|' + (parseFloat((stdout[key]/ Math.pow(1024000, Math.floor(Math.log(stdout[key]) / Math.log(1024000)))).toFixed(4)) + " " + "MB") + '|' + '\n' # Calculating rss in MB. else str += '|' + key + '|' + (parseFloat((stdout[key]/ Math.pow(1000, Math.floor(Math.log(stdout[key]) / Math.log(1000)))).toFixed(4)) + " " + "GB") + '|' + '\n' # Calculating memory in GB. msg.send str else if stderr msg.send stderr; else if error msg.send error; )
[ { "context": "do ->\n teamArray = [\"chelsea\", \"realMadrid\", \"milan\"]\n teamArray.forEach ( teamName ) ->\n pageI", "end": 50, "score": 0.5211700201034546, "start": 47, "tag": "NAME", "value": "mil" }, { "context": "Hash.currSlide\n when 0 then console.log \"fabregas\"\n when 1 then console.log \"drogba\"\n ", "end": 315, "score": 0.9995890259742737, "start": 307, "tag": "NAME", "value": "fabregas" }, { "context": "log \"fabregas\"\n when 1 then console.log \"drogba\"\n when 2 then console.log \"terry\"\n ", "end": 358, "score": 0.9994803071022034, "start": 352, "tag": "NAME", "value": "drogba" }, { "context": "e.log \"drogba\"\n when 2 then console.log \"terry\"\n else console.log \"courtois\"\n re", "end": 400, "score": 0.9991355538368225, "start": 395, "tag": "NAME", "value": "terry" }, { "context": "n console.log \"terry\"\n else console.log \"courtois\"\n return\n return\n return\n", "end": 438, "score": 0.9994101524353027, "start": 430, "tag": "NAME", "value": "courtois" } ]
coffee/swipeDetect.coffee
kaidez/build-css-tute
0
do -> teamArray = ["chelsea", "realMadrid", "milan"] teamArray.forEach ( teamName ) -> pageID = "#" + teamName $( pageID ).on "cycle-after", ( event, optionHash, incomingSlideEl ) -> console.log optionHash.currSlide switch optionHash.currSlide when 0 then console.log "fabregas" when 1 then console.log "drogba" when 2 then console.log "terry" else console.log "courtois" return return return
118337
do -> teamArray = ["chelsea", "realMadrid", "<NAME>an"] teamArray.forEach ( teamName ) -> pageID = "#" + teamName $( pageID ).on "cycle-after", ( event, optionHash, incomingSlideEl ) -> console.log optionHash.currSlide switch optionHash.currSlide when 0 then console.log "<NAME>" when 1 then console.log "<NAME>" when 2 then console.log "<NAME>" else console.log "<NAME>" return return return
true
do -> teamArray = ["chelsea", "realMadrid", "PI:NAME:<NAME>END_PIan"] teamArray.forEach ( teamName ) -> pageID = "#" + teamName $( pageID ).on "cycle-after", ( event, optionHash, incomingSlideEl ) -> console.log optionHash.currSlide switch optionHash.currSlide when 0 then console.log "PI:NAME:<NAME>END_PI" when 1 then console.log "PI:NAME:<NAME>END_PI" when 2 then console.log "PI:NAME:<NAME>END_PI" else console.log "PI:NAME:<NAME>END_PI" return return return
[ { "context": "18nTest: \"Some text..\"\n i18nHeadName: \"Maksim Kostromin\"\n i18nHeadIt: \"IT\"\n i18nHea", "end": 411, "score": 0.999882698059082, "start": 395, "tag": "NAME", "value": "Maksim Kostromin" }, { "context": "t: \"Какой-то текст...\"\n i18nHeadName: \"Максим Костромин\"\n i18nHeadIt: \"ИТ\"\n i18nHea", "end": 1003, "score": 0.9998760223388672, "start": 987, "tag": "NAME", "value": "Максим Костромин" } ]
src/main/www/src/scripts/i18n/config.coffee
daggerok/blog
0
angular .module 'i18nConfig', ['pascalprecht.translate'] .config [ '$translateProvider' ($translateProvider) -> $translateProvider .preferredLanguage 'ru' # escape html .useSanitizeValueStrategy 'escape' # english internationalization: .translations 'en', i18nTest: "Some text.." i18nHeadName: "Maksim Kostromin" i18nHeadIt: "IT" i18nHeadMusic: "Music" i18nHeadPhoto: "Photo" i18nHeadSport: "Sport" i18nHeadLangEn: "en" i18nHeadLangRu: "ru" i18nHeadAbout: "About" i18nContacts: "Contacts" i18nPageNotFound: "Sorry, but page wasn't found" i18nFooterCopyright: "copyright" i18nFooterDaggerok: "developed by daggerok" # русская интернационализация: .translations 'ru', i18nTest: "Какой-то текст..." i18nHeadName: "Максим Костромин" i18nHeadIt: "ИТ" i18nHeadMusic: "Музыка" i18nHeadPhoto: "Фотография" i18nHeadSport: "Спорт" i18nHeadLangEn: "англ" i18nHeadLangRu: "руск" i18nHeadAbout: "Обо мне" i18nContacts: "Контакты" i18nPageNotFound: "К сожалению, страница не найдена" i18nFooterCopyright: "все права защищены" i18nFooterDaggerok: "разработано Даггерком" ]
169790
angular .module 'i18nConfig', ['pascalprecht.translate'] .config [ '$translateProvider' ($translateProvider) -> $translateProvider .preferredLanguage 'ru' # escape html .useSanitizeValueStrategy 'escape' # english internationalization: .translations 'en', i18nTest: "Some text.." i18nHeadName: "<NAME>" i18nHeadIt: "IT" i18nHeadMusic: "Music" i18nHeadPhoto: "Photo" i18nHeadSport: "Sport" i18nHeadLangEn: "en" i18nHeadLangRu: "ru" i18nHeadAbout: "About" i18nContacts: "Contacts" i18nPageNotFound: "Sorry, but page wasn't found" i18nFooterCopyright: "copyright" i18nFooterDaggerok: "developed by daggerok" # русская интернационализация: .translations 'ru', i18nTest: "Какой-то текст..." i18nHeadName: "<NAME>" i18nHeadIt: "ИТ" i18nHeadMusic: "Музыка" i18nHeadPhoto: "Фотография" i18nHeadSport: "Спорт" i18nHeadLangEn: "англ" i18nHeadLangRu: "руск" i18nHeadAbout: "Обо мне" i18nContacts: "Контакты" i18nPageNotFound: "К сожалению, страница не найдена" i18nFooterCopyright: "все права защищены" i18nFooterDaggerok: "разработано Даггерком" ]
true
angular .module 'i18nConfig', ['pascalprecht.translate'] .config [ '$translateProvider' ($translateProvider) -> $translateProvider .preferredLanguage 'ru' # escape html .useSanitizeValueStrategy 'escape' # english internationalization: .translations 'en', i18nTest: "Some text.." i18nHeadName: "PI:NAME:<NAME>END_PI" i18nHeadIt: "IT" i18nHeadMusic: "Music" i18nHeadPhoto: "Photo" i18nHeadSport: "Sport" i18nHeadLangEn: "en" i18nHeadLangRu: "ru" i18nHeadAbout: "About" i18nContacts: "Contacts" i18nPageNotFound: "Sorry, but page wasn't found" i18nFooterCopyright: "copyright" i18nFooterDaggerok: "developed by daggerok" # русская интернационализация: .translations 'ru', i18nTest: "Какой-то текст..." i18nHeadName: "PI:NAME:<NAME>END_PI" i18nHeadIt: "ИТ" i18nHeadMusic: "Музыка" i18nHeadPhoto: "Фотография" i18nHeadSport: "Спорт" i18nHeadLangEn: "англ" i18nHeadLangRu: "руск" i18nHeadAbout: "Обо мне" i18nContacts: "Контакты" i18nPageNotFound: "К сожалению, страница не найдена" i18nFooterCopyright: "все права защищены" i18nFooterDaggerok: "разработано Даггерком" ]
[ { "context": "r Your Application's JavaScript\n\n Copyright 2012, Joschka Kintscher\n Released under the MIT License\n\n https://githu", "end": 99, "score": 0.9997861385345459, "start": 82, "tag": "NAME", "value": "Joschka Kintscher" }, { "context": "eased under the MIT License\n\n https://github.com/harvesthq/harvey/\n\n###\nclass this.Harvey\n\n # Hash of all c", "end": 164, "score": 0.9958861470222473, "start": 155, "tag": "USERNAME", "value": "harvesthq" }, { "context": "a interface for several engines\n\n * Inspired by Nicholas C. Zakas' article on the different problems with matchMedi", "end": 2394, "score": 0.9910213947296143, "start": 2377, "tag": "NAME", "value": "Nicholas C. Zakas" }, { "context": " Implementing a modified coffeescript version of Scott Jehl's and Paul Irish's matchMedia.js polyfill\n ", "end": 2593, "score": 0.6910024881362915, "start": 2589, "tag": "NAME", "value": "cott" }, { "context": " modified coffeescript version of Scott Jehl's and Paul Irish's matchMedia.js polyfill\n https://github.com", "end": 2615, "score": 0.8999544978141785, "start": 2605, "tag": "NAME", "value": "Paul Irish" }, { "context": "s matchMedia.js polyfill\n https://github.com/paulirish/matchMedia.js\n ###\n\n\n ###\n [FIX] for Firefox", "end": 2675, "score": 0.9985246062278748, "start": 2666, "tag": "USERNAME", "value": "paulirish" } ]
harvey.coffee
harvesthq/harvey
58
### Harvey, A Second Face for Your Application's JavaScript Copyright 2012, Joschka Kintscher Released under the MIT License https://github.com/harvesthq/harvey/ ### class this.Harvey # Hash of all currently attached media queries and their corresponding states @states : {} ### Creates a new State object for the given media query using the passed hash of callbacks and stores it in @states. The passed hash may contain up to three callbacks. See documentation of the State class for more information. ### @attach: (mediaQuery, callbacks) -> unless @states.hasOwnProperty mediaQuery @states[mediaQuery] = [] @_add_css_for(mediaQuery) # @TODO if userAgent is webkit (to avoid additional DOM manipulation) state = new State(mediaQuery, callbacks?.setup, callbacks?.on, callbacks?.off) # create a new listener for this query in case there is none already @_watch_query(mediaQuery) unless @states[mediaQuery].length @states[mediaQuery].push(state) # check whether the new State is valid at the moment and set it up @_update_states([state], yes) if @_window_matchmedia(mediaQuery).matches # return the new state object state ### Removes a given State object from the @states hash. @param object state A valid state object ### @detach: (state) -> for s, i in @states[state.condition] @states[s.condition][i] = undefined if state is s ### Create a new matchMediaListener for the passed media query. @param string mediaQuery A valid CSS media query to watch ### @_watch_query: (mediaQuery) -> @_window_matchmedia(mediaQuery).addListener((mql) => @_update_states(@states[mediaQuery], mql.matches) ) ### Activates/Deactivates every State object in the passed list. @param array states A list of State objects to update @param boolean active Whether to activate or deactivate the given states ### @_update_states: (states, active) -> for state in states if active then state.activate() else state.deactivate() ### BEWARE: You're at the edge of the map, mate. Here there be monsters! ------------------------------------------------------------------------------------ Private methods to fix and polyfill the matchMedia interface for several engines * Inspired by Nicholas C. Zakas' article on the different problems with matchMedia http://www.nczonline.net/blog/2012/01/19/css-media-queries-in-javascript-part-2/ * Implementing a modified coffeescript version of Scott Jehl's and Paul Irish's matchMedia.js polyfill https://github.com/paulirish/matchMedia.js ### ### [FIX] for Firefox/Gecko browsers that lose reference to the MediaQueryList object unless it's being stored for runtime. ### @_mediaList: {} ### @param string mediaQuery A valid CSS media query to monitor for updates @Return object MediaQueryList Depending on the browser and matchMedia support either a native mediaQueryList object or an instance of _mediaQueryList ### @_window_matchmedia: (mediaQuery) -> # always try to use the native matchMedia interface where available! if window.matchMedia and 'addListener' in window.matchMedia('all') @_mediaList[mediaQuery] = window.matchMedia(mediaQuery) if mediaQuery not of @_mediaList return @_mediaList[mediaQuery] ### [POLYFILL] for all browsers that don't support matchMedia() at all (CSS media query support is still mandatory though). ### # use other available window events to listen for update on the viewport @_listen() unless @_listening @_mediaList[mediaQuery] = new _mediaQueryList(mediaQuery) if mediaQuery not of @_mediaList # return the corresponding object from _mediaQueryList @_mediaList[mediaQuery] ### Add resize and orientationChange event listeners to the window element to monitor updates to the viewport ### @_listen: () -> evt = window.addEventListener || window.attachEvent evt 'resize', () => mediaList._process() for mediaQuery, mediaList of @_mediaList evt 'orientationChange', () => mediaList._process() for mediaQuery, mediaList of @_mediaList @_listening = yes ### [FIX] for Webkit engines that only trigger the MediaQueryListListener when there is at least one CSS selector for the respective media query @param string MediaQuery The media query to inject CSS for ### @_add_css_for: (mediaQuery) -> unless @style @style = document.createElement('style') @style.setAttribute('type', 'text/css') document.getElementsByTagName('head')[0].appendChild(@style) mediaQuery = "@media #{mediaQuery} {.harvey-test{}}" unless @style.styleSheet @style.appendChild(document.createTextNode(mediaQuery)) ### A State allows to execute a set of callbacks for the given valid CSS media query. Callbacks are executed in the context of their state object to allow access to the corresponding media query of the State. States are not exposed to the global namespace. They can be used by calling the static Harvey.attach() and Harvey.detach() methods. ### class State # Whether this State is active or inactive at the moment active : no # Whether this State has been set up is_setup: no ### Creates a new State object @param string condition The media query to check for @param function setup Called the first time `condition` becomes valid @param function on Called every time `condition` becomes valid @param function off Called every time `condition` becomes invalid ### constructor: (@condition, @setup, @on, @off) -> ### Activate this State object if it is currently deactivated. Also perform all set up tasks if this is the first time the State is activated ### activate: () -> return if @active unless @is_setup @setup?() @is_setup = yes @on?() @active = yes ### Deactive this State object if it is currently active ### deactivate: () -> return unless @active @off?() @active = no ### [FIX] simple implemenation of the matchMedia interface to mimic the native matchMedia interface behaviour to work as a polyfill for Harvey ### class _mediaQueryList ### Creates a new _mediaQueryList object @param string media A valid CSS media query ### constructor: (@media) -> # A list of all listeners that are attached this media query @_listeners = [] # Stores whether the registered media query is currently valid or not @matches = @_matches() ### Add a new listener to this mediaQueryList that will be called every time the media query becomes valid ### addListener: (listener) -> @_listeners.push(listener) # return undefined just like the native addListener method undefined ### Evaluate the media query of this mediaQueryList object and notify all registered listeners if the state has changed ### _process: () -> current = @_matches() return if @matches is current @matches = current callback(this) for callback in @_listeners ### Check whether the media query is currently valid ### _matches: () -> @_get_tester() unless @_tester # Replace all contents of the tester element with a CSS represenation of the media query @_tester.innerHTML = '&shy;<style media="' + @media + '">#harvey-mq-test{width:42px;}</style>' # Fix for browsers that won't process a <style> tag as the first child of a non <head>-element @_tester.removeChild(@_tester.firstChild) # Return whether the media query affected the test element (matches) or not (doesn't match) @_tester.offsetWidth is 42 ### Retrieve the element to test the media query on from the DOM or create it if it has not been injected into the page yet ### _get_tester: () -> @_tester = document.getElementById('harvey-mq-test') @_build_tester() unless @_tester ### Create a new div with a unique id, move it outsite of the viewport and inject it into the DOM. This element will be used to check whether the registered media query is currently valid. ### _build_tester: () -> @_tester = document.createElement('div') @_tester.id = 'harvey-mq-test' @_tester.style.cssText = 'position:absolute;top:-100em' document.body.insertBefore(@_tester, document.body.firstChild)
213630
### Harvey, A Second Face for Your Application's JavaScript Copyright 2012, <NAME> Released under the MIT License https://github.com/harvesthq/harvey/ ### class this.Harvey # Hash of all currently attached media queries and their corresponding states @states : {} ### Creates a new State object for the given media query using the passed hash of callbacks and stores it in @states. The passed hash may contain up to three callbacks. See documentation of the State class for more information. ### @attach: (mediaQuery, callbacks) -> unless @states.hasOwnProperty mediaQuery @states[mediaQuery] = [] @_add_css_for(mediaQuery) # @TODO if userAgent is webkit (to avoid additional DOM manipulation) state = new State(mediaQuery, callbacks?.setup, callbacks?.on, callbacks?.off) # create a new listener for this query in case there is none already @_watch_query(mediaQuery) unless @states[mediaQuery].length @states[mediaQuery].push(state) # check whether the new State is valid at the moment and set it up @_update_states([state], yes) if @_window_matchmedia(mediaQuery).matches # return the new state object state ### Removes a given State object from the @states hash. @param object state A valid state object ### @detach: (state) -> for s, i in @states[state.condition] @states[s.condition][i] = undefined if state is s ### Create a new matchMediaListener for the passed media query. @param string mediaQuery A valid CSS media query to watch ### @_watch_query: (mediaQuery) -> @_window_matchmedia(mediaQuery).addListener((mql) => @_update_states(@states[mediaQuery], mql.matches) ) ### Activates/Deactivates every State object in the passed list. @param array states A list of State objects to update @param boolean active Whether to activate or deactivate the given states ### @_update_states: (states, active) -> for state in states if active then state.activate() else state.deactivate() ### BEWARE: You're at the edge of the map, mate. Here there be monsters! ------------------------------------------------------------------------------------ Private methods to fix and polyfill the matchMedia interface for several engines * Inspired by <NAME>' article on the different problems with matchMedia http://www.nczonline.net/blog/2012/01/19/css-media-queries-in-javascript-part-2/ * Implementing a modified coffeescript version of S<NAME> Jehl's and <NAME>'s matchMedia.js polyfill https://github.com/paulirish/matchMedia.js ### ### [FIX] for Firefox/Gecko browsers that lose reference to the MediaQueryList object unless it's being stored for runtime. ### @_mediaList: {} ### @param string mediaQuery A valid CSS media query to monitor for updates @Return object MediaQueryList Depending on the browser and matchMedia support either a native mediaQueryList object or an instance of _mediaQueryList ### @_window_matchmedia: (mediaQuery) -> # always try to use the native matchMedia interface where available! if window.matchMedia and 'addListener' in window.matchMedia('all') @_mediaList[mediaQuery] = window.matchMedia(mediaQuery) if mediaQuery not of @_mediaList return @_mediaList[mediaQuery] ### [POLYFILL] for all browsers that don't support matchMedia() at all (CSS media query support is still mandatory though). ### # use other available window events to listen for update on the viewport @_listen() unless @_listening @_mediaList[mediaQuery] = new _mediaQueryList(mediaQuery) if mediaQuery not of @_mediaList # return the corresponding object from _mediaQueryList @_mediaList[mediaQuery] ### Add resize and orientationChange event listeners to the window element to monitor updates to the viewport ### @_listen: () -> evt = window.addEventListener || window.attachEvent evt 'resize', () => mediaList._process() for mediaQuery, mediaList of @_mediaList evt 'orientationChange', () => mediaList._process() for mediaQuery, mediaList of @_mediaList @_listening = yes ### [FIX] for Webkit engines that only trigger the MediaQueryListListener when there is at least one CSS selector for the respective media query @param string MediaQuery The media query to inject CSS for ### @_add_css_for: (mediaQuery) -> unless @style @style = document.createElement('style') @style.setAttribute('type', 'text/css') document.getElementsByTagName('head')[0].appendChild(@style) mediaQuery = "@media #{mediaQuery} {.harvey-test{}}" unless @style.styleSheet @style.appendChild(document.createTextNode(mediaQuery)) ### A State allows to execute a set of callbacks for the given valid CSS media query. Callbacks are executed in the context of their state object to allow access to the corresponding media query of the State. States are not exposed to the global namespace. They can be used by calling the static Harvey.attach() and Harvey.detach() methods. ### class State # Whether this State is active or inactive at the moment active : no # Whether this State has been set up is_setup: no ### Creates a new State object @param string condition The media query to check for @param function setup Called the first time `condition` becomes valid @param function on Called every time `condition` becomes valid @param function off Called every time `condition` becomes invalid ### constructor: (@condition, @setup, @on, @off) -> ### Activate this State object if it is currently deactivated. Also perform all set up tasks if this is the first time the State is activated ### activate: () -> return if @active unless @is_setup @setup?() @is_setup = yes @on?() @active = yes ### Deactive this State object if it is currently active ### deactivate: () -> return unless @active @off?() @active = no ### [FIX] simple implemenation of the matchMedia interface to mimic the native matchMedia interface behaviour to work as a polyfill for Harvey ### class _mediaQueryList ### Creates a new _mediaQueryList object @param string media A valid CSS media query ### constructor: (@media) -> # A list of all listeners that are attached this media query @_listeners = [] # Stores whether the registered media query is currently valid or not @matches = @_matches() ### Add a new listener to this mediaQueryList that will be called every time the media query becomes valid ### addListener: (listener) -> @_listeners.push(listener) # return undefined just like the native addListener method undefined ### Evaluate the media query of this mediaQueryList object and notify all registered listeners if the state has changed ### _process: () -> current = @_matches() return if @matches is current @matches = current callback(this) for callback in @_listeners ### Check whether the media query is currently valid ### _matches: () -> @_get_tester() unless @_tester # Replace all contents of the tester element with a CSS represenation of the media query @_tester.innerHTML = '&shy;<style media="' + @media + '">#harvey-mq-test{width:42px;}</style>' # Fix for browsers that won't process a <style> tag as the first child of a non <head>-element @_tester.removeChild(@_tester.firstChild) # Return whether the media query affected the test element (matches) or not (doesn't match) @_tester.offsetWidth is 42 ### Retrieve the element to test the media query on from the DOM or create it if it has not been injected into the page yet ### _get_tester: () -> @_tester = document.getElementById('harvey-mq-test') @_build_tester() unless @_tester ### Create a new div with a unique id, move it outsite of the viewport and inject it into the DOM. This element will be used to check whether the registered media query is currently valid. ### _build_tester: () -> @_tester = document.createElement('div') @_tester.id = 'harvey-mq-test' @_tester.style.cssText = 'position:absolute;top:-100em' document.body.insertBefore(@_tester, document.body.firstChild)
true
### Harvey, A Second Face for Your Application's JavaScript Copyright 2012, PI:NAME:<NAME>END_PI Released under the MIT License https://github.com/harvesthq/harvey/ ### class this.Harvey # Hash of all currently attached media queries and their corresponding states @states : {} ### Creates a new State object for the given media query using the passed hash of callbacks and stores it in @states. The passed hash may contain up to three callbacks. See documentation of the State class for more information. ### @attach: (mediaQuery, callbacks) -> unless @states.hasOwnProperty mediaQuery @states[mediaQuery] = [] @_add_css_for(mediaQuery) # @TODO if userAgent is webkit (to avoid additional DOM manipulation) state = new State(mediaQuery, callbacks?.setup, callbacks?.on, callbacks?.off) # create a new listener for this query in case there is none already @_watch_query(mediaQuery) unless @states[mediaQuery].length @states[mediaQuery].push(state) # check whether the new State is valid at the moment and set it up @_update_states([state], yes) if @_window_matchmedia(mediaQuery).matches # return the new state object state ### Removes a given State object from the @states hash. @param object state A valid state object ### @detach: (state) -> for s, i in @states[state.condition] @states[s.condition][i] = undefined if state is s ### Create a new matchMediaListener for the passed media query. @param string mediaQuery A valid CSS media query to watch ### @_watch_query: (mediaQuery) -> @_window_matchmedia(mediaQuery).addListener((mql) => @_update_states(@states[mediaQuery], mql.matches) ) ### Activates/Deactivates every State object in the passed list. @param array states A list of State objects to update @param boolean active Whether to activate or deactivate the given states ### @_update_states: (states, active) -> for state in states if active then state.activate() else state.deactivate() ### BEWARE: You're at the edge of the map, mate. Here there be monsters! ------------------------------------------------------------------------------------ Private methods to fix and polyfill the matchMedia interface for several engines * Inspired by PI:NAME:<NAME>END_PI' article on the different problems with matchMedia http://www.nczonline.net/blog/2012/01/19/css-media-queries-in-javascript-part-2/ * Implementing a modified coffeescript version of SPI:NAME:<NAME>END_PI Jehl's and PI:NAME:<NAME>END_PI's matchMedia.js polyfill https://github.com/paulirish/matchMedia.js ### ### [FIX] for Firefox/Gecko browsers that lose reference to the MediaQueryList object unless it's being stored for runtime. ### @_mediaList: {} ### @param string mediaQuery A valid CSS media query to monitor for updates @Return object MediaQueryList Depending on the browser and matchMedia support either a native mediaQueryList object or an instance of _mediaQueryList ### @_window_matchmedia: (mediaQuery) -> # always try to use the native matchMedia interface where available! if window.matchMedia and 'addListener' in window.matchMedia('all') @_mediaList[mediaQuery] = window.matchMedia(mediaQuery) if mediaQuery not of @_mediaList return @_mediaList[mediaQuery] ### [POLYFILL] for all browsers that don't support matchMedia() at all (CSS media query support is still mandatory though). ### # use other available window events to listen for update on the viewport @_listen() unless @_listening @_mediaList[mediaQuery] = new _mediaQueryList(mediaQuery) if mediaQuery not of @_mediaList # return the corresponding object from _mediaQueryList @_mediaList[mediaQuery] ### Add resize and orientationChange event listeners to the window element to monitor updates to the viewport ### @_listen: () -> evt = window.addEventListener || window.attachEvent evt 'resize', () => mediaList._process() for mediaQuery, mediaList of @_mediaList evt 'orientationChange', () => mediaList._process() for mediaQuery, mediaList of @_mediaList @_listening = yes ### [FIX] for Webkit engines that only trigger the MediaQueryListListener when there is at least one CSS selector for the respective media query @param string MediaQuery The media query to inject CSS for ### @_add_css_for: (mediaQuery) -> unless @style @style = document.createElement('style') @style.setAttribute('type', 'text/css') document.getElementsByTagName('head')[0].appendChild(@style) mediaQuery = "@media #{mediaQuery} {.harvey-test{}}" unless @style.styleSheet @style.appendChild(document.createTextNode(mediaQuery)) ### A State allows to execute a set of callbacks for the given valid CSS media query. Callbacks are executed in the context of their state object to allow access to the corresponding media query of the State. States are not exposed to the global namespace. They can be used by calling the static Harvey.attach() and Harvey.detach() methods. ### class State # Whether this State is active or inactive at the moment active : no # Whether this State has been set up is_setup: no ### Creates a new State object @param string condition The media query to check for @param function setup Called the first time `condition` becomes valid @param function on Called every time `condition` becomes valid @param function off Called every time `condition` becomes invalid ### constructor: (@condition, @setup, @on, @off) -> ### Activate this State object if it is currently deactivated. Also perform all set up tasks if this is the first time the State is activated ### activate: () -> return if @active unless @is_setup @setup?() @is_setup = yes @on?() @active = yes ### Deactive this State object if it is currently active ### deactivate: () -> return unless @active @off?() @active = no ### [FIX] simple implemenation of the matchMedia interface to mimic the native matchMedia interface behaviour to work as a polyfill for Harvey ### class _mediaQueryList ### Creates a new _mediaQueryList object @param string media A valid CSS media query ### constructor: (@media) -> # A list of all listeners that are attached this media query @_listeners = [] # Stores whether the registered media query is currently valid or not @matches = @_matches() ### Add a new listener to this mediaQueryList that will be called every time the media query becomes valid ### addListener: (listener) -> @_listeners.push(listener) # return undefined just like the native addListener method undefined ### Evaluate the media query of this mediaQueryList object and notify all registered listeners if the state has changed ### _process: () -> current = @_matches() return if @matches is current @matches = current callback(this) for callback in @_listeners ### Check whether the media query is currently valid ### _matches: () -> @_get_tester() unless @_tester # Replace all contents of the tester element with a CSS represenation of the media query @_tester.innerHTML = '&shy;<style media="' + @media + '">#harvey-mq-test{width:42px;}</style>' # Fix for browsers that won't process a <style> tag as the first child of a non <head>-element @_tester.removeChild(@_tester.firstChild) # Return whether the media query affected the test element (matches) or not (doesn't match) @_tester.offsetWidth is 42 ### Retrieve the element to test the media query on from the DOM or create it if it has not been injected into the page yet ### _get_tester: () -> @_tester = document.getElementById('harvey-mq-test') @_build_tester() unless @_tester ### Create a new div with a unique id, move it outsite of the viewport and inject it into the DOM. This element will be used to check whether the registered media query is currently valid. ### _build_tester: () -> @_tester = document.createElement('div') @_tester.id = 'harvey-mq-test' @_tester.style.cssText = 'position:absolute;top:-100em' document.body.insertBefore(@_tester, document.body.firstChild)
[ { "context": "ault: \"\"\n password:\n description: \"The August Connect Password\"\n type: \"string\"\n ", "end": 332, "score": 0.6013975739479065, "start": 326, "tag": "PASSWORD", "value": "August" }, { "context": "password:\n description: \"The August Connect Password\"\n type: \"string\"\n default: \"\"\n }\n}", "end": 349, "score": 0.8753190636634827, "start": 341, "tag": "PASSWORD", "value": "Password" } ]
device-config-schema.coffee
hongkongkiwi/pimatic-august-connect
0
module.exports = { title: "pimatic-august-connect device config schemas" MqttSwitch: { title: "AugustConnectDevice config options" type: "object" properties: username: description: "The August Connect Username" type: "string" default: "" password: description: "The August Connect Password" type: "string" default: "" } }
27670
module.exports = { title: "pimatic-august-connect device config schemas" MqttSwitch: { title: "AugustConnectDevice config options" type: "object" properties: username: description: "The August Connect Username" type: "string" default: "" password: description: "The <PASSWORD> Connect <PASSWORD>" type: "string" default: "" } }
true
module.exports = { title: "pimatic-august-connect device config schemas" MqttSwitch: { title: "AugustConnectDevice config options" type: "object" properties: username: description: "The August Connect Username" type: "string" default: "" password: description: "The PI:PASSWORD:<PASSWORD>END_PI Connect PI:PASSWORD:<PASSWORD>END_PI" type: "string" default: "" } }
[ { "context": "erId\": \"ygBckhuWfRTFBmFgy\",\n \"addedByUserName\": \"Nathan\",\n \"addedDate\": new Date(\"2017-08-18T13:29:59.89", "end": 596, "score": 0.9766944050788879, "start": 590, "tag": "USERNAME", "value": "Nathan" }, { "context": "\n \"population\": 684451,\n \"admin2Name\": \"King County\",\n \"admin1Name\": \"Washington\",\n \"countr", "end": 1056, "score": 0.981622576713562, "start": 1045, "tag": "NAME", "value": "King County" }, { "context": "\"admin2Name\": \"King County\",\n \"admin1Name\": \"Washington\",\n \"countryName\": \"United States\"\n }\n ],", "end": 1090, "score": 0.9879274964332581, "start": 1080, "tag": "NAME", "value": "Washington" } ]
server/methods.test.coffee
ecohealthalliance/eidr-connect
1
import { chai } from 'meteor/practicalmeteor:chai' import Articles from '/imports/collections/articles' import Incidents from '/imports/collections/incidentReports' import { autogenerateDocumentIncidents, getArticleEnhancements } from '/server/methods' testArticle = { "_id": "KGLJ9Xg9ivgvJyiAc", "content": "There were 19 cases of Ebola in Seattle, Washington on June 11, 2010.", "title": "Test Article", "publishDateTZ": "EST", "publishDate": new Date("2017-08-17T16:00:00.000Z"), "userEventIds": [ null ], "addedByUserId": "ygBckhuWfRTFBmFgy", "addedByUserName": "Nathan", "addedDate": new Date("2017-08-18T13:29:59.894Z") } testIncident = { "_id": "ADzsaBZWtKEyhSJdK", "locations": [ { "id": "5809844", "name": "Seattle", "alternateNames": [], "latitude": 47.60621, "longitude": -122.33207, "featureClass": "P", "featureCode": "PPLA2", "countryCode": "US", "admin1Code": "WA", "admin2Code": "033", "population": 684451, "admin2Name": "King County", "admin1Name": "Washington", "countryName": "United States" } ], "dateRange": { "start": "2010-05-11T00:00:00.000Z", "end": "2010-05-12T23:59:59.999Z", "type": "precise" }, "cases": 54321, "type": "caseCount", "articleId": "KGLJ9Xg9ivgvJyiAc", "resolvedDisease": { "id": "http://purl.obolibrary.org/obo/DOID_4325", "text": "Ebola hemorrhagic fever" }, "species": { "id": "tsn:180092", "text": "Homo sapiens" }, "annotations": { "case": [ { "textOffsets": [ 53, 55 ], "text": "to" } ], "location": [ { "textOffsets": [ 32, 51 ] } ], "date": [ { "textOffsets": [ 55, 68 ] } ], "disease": [ { "textOffsets": [ 23, 28 ] } ] }, "autogenerated": false, "addedDate": "2017-08-18T15:44:53.903Z" } describe 'Methods', -> it 'autogenerates incidents from a document', (done) -> @timeout(30000) Articles.remove(testArticle._id) Incidents.remove(articleId: testArticle._id) Articles.insert(testArticle) Incidents.insert(testIncident) getArticleEnhancements(testArticle).then (enhancements) -> testArticle.enhancements = enhancements autogenerateDocumentIncidents(testArticle) # Test that rerunning the function doesn't create more incidents. autogenerateDocumentIncidents(testArticle) chai.assert(Incidents.find(articleId: testArticle._id).count() == 2) # Alter the count to test count updating Incidents.update( articleId: testArticle._id cases: 19 , $set: cases: 20 ) # Test that the counts are updated when the function reruns autogenerateDocumentIncidents(testArticle) chai.assert(Incidents.find( articleId: testArticle._id cases: 19 ).count() == 1) # Test that user modified counts are not updated when the function reruns Incidents.update( articleId: testArticle._id cases: 19 , $set: modifiedByUserId: "ygBckhuWfRTFBmFgy" cases: 20 ) autogenerateDocumentIncidents(testArticle) chai.assert(Incidents.find( articleId: testArticle._id cases: 20 ).count() == 1) Articles.remove(testArticle._id) Incidents.remove(articleId: testArticle._id) done() .catch (error) -> done(error)
175243
import { chai } from 'meteor/practicalmeteor:chai' import Articles from '/imports/collections/articles' import Incidents from '/imports/collections/incidentReports' import { autogenerateDocumentIncidents, getArticleEnhancements } from '/server/methods' testArticle = { "_id": "KGLJ9Xg9ivgvJyiAc", "content": "There were 19 cases of Ebola in Seattle, Washington on June 11, 2010.", "title": "Test Article", "publishDateTZ": "EST", "publishDate": new Date("2017-08-17T16:00:00.000Z"), "userEventIds": [ null ], "addedByUserId": "ygBckhuWfRTFBmFgy", "addedByUserName": "Nathan", "addedDate": new Date("2017-08-18T13:29:59.894Z") } testIncident = { "_id": "ADzsaBZWtKEyhSJdK", "locations": [ { "id": "5809844", "name": "Seattle", "alternateNames": [], "latitude": 47.60621, "longitude": -122.33207, "featureClass": "P", "featureCode": "PPLA2", "countryCode": "US", "admin1Code": "WA", "admin2Code": "033", "population": 684451, "admin2Name": "<NAME>", "admin1Name": "<NAME>", "countryName": "United States" } ], "dateRange": { "start": "2010-05-11T00:00:00.000Z", "end": "2010-05-12T23:59:59.999Z", "type": "precise" }, "cases": 54321, "type": "caseCount", "articleId": "KGLJ9Xg9ivgvJyiAc", "resolvedDisease": { "id": "http://purl.obolibrary.org/obo/DOID_4325", "text": "Ebola hemorrhagic fever" }, "species": { "id": "tsn:180092", "text": "Homo sapiens" }, "annotations": { "case": [ { "textOffsets": [ 53, 55 ], "text": "to" } ], "location": [ { "textOffsets": [ 32, 51 ] } ], "date": [ { "textOffsets": [ 55, 68 ] } ], "disease": [ { "textOffsets": [ 23, 28 ] } ] }, "autogenerated": false, "addedDate": "2017-08-18T15:44:53.903Z" } describe 'Methods', -> it 'autogenerates incidents from a document', (done) -> @timeout(30000) Articles.remove(testArticle._id) Incidents.remove(articleId: testArticle._id) Articles.insert(testArticle) Incidents.insert(testIncident) getArticleEnhancements(testArticle).then (enhancements) -> testArticle.enhancements = enhancements autogenerateDocumentIncidents(testArticle) # Test that rerunning the function doesn't create more incidents. autogenerateDocumentIncidents(testArticle) chai.assert(Incidents.find(articleId: testArticle._id).count() == 2) # Alter the count to test count updating Incidents.update( articleId: testArticle._id cases: 19 , $set: cases: 20 ) # Test that the counts are updated when the function reruns autogenerateDocumentIncidents(testArticle) chai.assert(Incidents.find( articleId: testArticle._id cases: 19 ).count() == 1) # Test that user modified counts are not updated when the function reruns Incidents.update( articleId: testArticle._id cases: 19 , $set: modifiedByUserId: "ygBckhuWfRTFBmFgy" cases: 20 ) autogenerateDocumentIncidents(testArticle) chai.assert(Incidents.find( articleId: testArticle._id cases: 20 ).count() == 1) Articles.remove(testArticle._id) Incidents.remove(articleId: testArticle._id) done() .catch (error) -> done(error)
true
import { chai } from 'meteor/practicalmeteor:chai' import Articles from '/imports/collections/articles' import Incidents from '/imports/collections/incidentReports' import { autogenerateDocumentIncidents, getArticleEnhancements } from '/server/methods' testArticle = { "_id": "KGLJ9Xg9ivgvJyiAc", "content": "There were 19 cases of Ebola in Seattle, Washington on June 11, 2010.", "title": "Test Article", "publishDateTZ": "EST", "publishDate": new Date("2017-08-17T16:00:00.000Z"), "userEventIds": [ null ], "addedByUserId": "ygBckhuWfRTFBmFgy", "addedByUserName": "Nathan", "addedDate": new Date("2017-08-18T13:29:59.894Z") } testIncident = { "_id": "ADzsaBZWtKEyhSJdK", "locations": [ { "id": "5809844", "name": "Seattle", "alternateNames": [], "latitude": 47.60621, "longitude": -122.33207, "featureClass": "P", "featureCode": "PPLA2", "countryCode": "US", "admin1Code": "WA", "admin2Code": "033", "population": 684451, "admin2Name": "PI:NAME:<NAME>END_PI", "admin1Name": "PI:NAME:<NAME>END_PI", "countryName": "United States" } ], "dateRange": { "start": "2010-05-11T00:00:00.000Z", "end": "2010-05-12T23:59:59.999Z", "type": "precise" }, "cases": 54321, "type": "caseCount", "articleId": "KGLJ9Xg9ivgvJyiAc", "resolvedDisease": { "id": "http://purl.obolibrary.org/obo/DOID_4325", "text": "Ebola hemorrhagic fever" }, "species": { "id": "tsn:180092", "text": "Homo sapiens" }, "annotations": { "case": [ { "textOffsets": [ 53, 55 ], "text": "to" } ], "location": [ { "textOffsets": [ 32, 51 ] } ], "date": [ { "textOffsets": [ 55, 68 ] } ], "disease": [ { "textOffsets": [ 23, 28 ] } ] }, "autogenerated": false, "addedDate": "2017-08-18T15:44:53.903Z" } describe 'Methods', -> it 'autogenerates incidents from a document', (done) -> @timeout(30000) Articles.remove(testArticle._id) Incidents.remove(articleId: testArticle._id) Articles.insert(testArticle) Incidents.insert(testIncident) getArticleEnhancements(testArticle).then (enhancements) -> testArticle.enhancements = enhancements autogenerateDocumentIncidents(testArticle) # Test that rerunning the function doesn't create more incidents. autogenerateDocumentIncidents(testArticle) chai.assert(Incidents.find(articleId: testArticle._id).count() == 2) # Alter the count to test count updating Incidents.update( articleId: testArticle._id cases: 19 , $set: cases: 20 ) # Test that the counts are updated when the function reruns autogenerateDocumentIncidents(testArticle) chai.assert(Incidents.find( articleId: testArticle._id cases: 19 ).count() == 1) # Test that user modified counts are not updated when the function reruns Incidents.update( articleId: testArticle._id cases: 19 , $set: modifiedByUserId: "ygBckhuWfRTFBmFgy" cases: 20 ) autogenerateDocumentIncidents(testArticle) chai.assert(Incidents.find( articleId: testArticle._id cases: 20 ).count() == 1) Articles.remove(testArticle._id) Incidents.remove(articleId: testArticle._id) done() .catch (error) -> done(error)
[ { "context": "ricate('featured_partners_profiles',\n id: 'gagosian'\n owner: new Partner(fabricate('partner',\n", "end": 633, "score": 0.9995068907737732, "start": 625, "tag": "USERNAME", "value": "gagosian" }, { "context": "ricate('featured_partners_profiles',\n id: 'getty'\n owner: new Partner(fabricate('partner',\n", "end": 862, "score": 0.9951039552688599, "start": 857, "tag": "USERNAME", "value": "getty" }, { "context": "',\n type: \"Institution\"\n name: \"J. Paul Getty Museum\"\n locations: new Backbone.Collection([fa", "end": 979, "score": 0.9998007416725159, "start": 959, "tag": "NAME", "value": "J. Paul Getty Museum" }, { "context": "ricate('featured_partners_profiles',\n id: 'lacma'\n owner: new Partner(fabricate('partner',\n", "end": 1134, "score": 0.9986165165901184, "start": 1129, "tag": "USERNAME", "value": "lacma" }, { "context": "',\n type: \"Institution\"\n name: \"LACMA\"\n locations: new Backbone.Collection([fa", "end": 1236, "score": 0.9986464381217957, "start": 1231, "tag": "NAME", "value": "LACMA" }, { "context": "te('featured_partners_profiles',\n id: 'gagosian'\n owner: new Partner(fabricate('partne", "end": 3024, "score": 0.985657811164856, "start": 3016, "tag": "USERNAME", "value": "gagosian" }, { "context": "te('featured_partners_profiles',\n id: 'pace'\n owner: new Partner(fabricate('partne", "end": 3273, "score": 0.5911595225334167, "start": 3269, "tag": "NAME", "value": "pace" } ]
src/mobile/apps/partners/test/template.coffee
kanaabe/force
1
_ = require 'underscore' jade = require 'jade' path = require 'path' fs = require 'fs' cheerio = require 'cheerio' Backbone = require 'backbone' { fabricate } = require 'antigravity' Partner = require '../../../models/partner' Profiles = require '../../../collections/profiles' render = (templateName) -> filename = path.resolve __dirname, "../#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'Partners', -> before -> @sd = API_URL: 'http://localhost:5000' @profiles = new Profiles [ fabricate('featured_partners_profiles', id: 'gagosian' owner: new Partner(fabricate('partner', type: "Gallery" locations: new Backbone.Collection([fabricate('location')]) )) ) fabricate('featured_partners_profiles', id: 'getty' owner: new Partner(fabricate('partner', type: "Institution" name: "J. Paul Getty Museum" locations: new Backbone.Collection([fabricate('location')]) )) ) fabricate('featured_partners_profiles', id: 'lacma' owner: new Partner(fabricate('partner', type: "Institution" name: "LACMA" locations: new Backbone.Collection([fabricate('location')]) )) ) ] @html = render('template')({ sd: @sd featuredPartnerProfiles: @profiles }) describe 'template', -> it 'renders featured partners', -> $ = cheerio.load @html $("a.nav-image-item").length.should.equal 3 @profiles.each (profile) -> partner = profile.get 'owner' $partnerItem = $("a.nav-image-item[href='/#{profile.get('id')}']") $partnerItem.length.should.equal 1 $partnerItem.find(".nav-image-item-label-title").length.should.equal 1 $partnerItem.find(".nav-image-item-label-title").text().should.equal partner.get 'name' $partnerItem.find(".nav-image-item-label-subtitle").text().should.containEql partner.get('locations').first().get('city') it 'includes a page title', -> $ = cheerio.load @html $('.page-heading').text().should.equal "Featured Partners" it 'includes a link to the "become a partner" form', -> $ = cheerio.load @html $('.featured-partners-invite').length.should.equal 1 $('.featured-partners-invite a').attr('href').should.equal "https://www.artsy.net/apply/" # TODO: Add this with the other index pages #it 'includes links to galleries and instutions in the header and footer', -> # $ = cheerio.load @html # $('.featured-partners-nav').length.should.equal 2 # $(".featured-partners-nav a[href='/galleries']").length.should.equal 2 # $(".featured-partners-nav a[href='/institutions']").length.should.equal 2 describe 'with incomplete location data', -> it 'renders without a location', -> @profiles = new Profiles [ fabricate('featured_partners_profiles', id: 'gagosian' owner: new Partner(fabricate('partner', type: "Gallery" locations: new Backbone.Collection() # No locations )) ) fabricate('featured_partners_profiles', id: 'pace' owner: new Partner(fabricate('partner', type: "Gallery" locations: new Backbone.Collection([fabricate 'location', city: '']) # No city )) ) ] html = render('template')({ sd: @sd featuredPartnerProfiles: @profiles }) $ = cheerio.load html $(".nav-image-item-label-subtitle").length.should.equal 1 $(".nav-image-item-label-subtitle").text().should.equal ''
101779
_ = require 'underscore' jade = require 'jade' path = require 'path' fs = require 'fs' cheerio = require 'cheerio' Backbone = require 'backbone' { fabricate } = require 'antigravity' Partner = require '../../../models/partner' Profiles = require '../../../collections/profiles' render = (templateName) -> filename = path.resolve __dirname, "../#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'Partners', -> before -> @sd = API_URL: 'http://localhost:5000' @profiles = new Profiles [ fabricate('featured_partners_profiles', id: 'gagosian' owner: new Partner(fabricate('partner', type: "Gallery" locations: new Backbone.Collection([fabricate('location')]) )) ) fabricate('featured_partners_profiles', id: 'getty' owner: new Partner(fabricate('partner', type: "Institution" name: "<NAME>" locations: new Backbone.Collection([fabricate('location')]) )) ) fabricate('featured_partners_profiles', id: 'lacma' owner: new Partner(fabricate('partner', type: "Institution" name: "<NAME>" locations: new Backbone.Collection([fabricate('location')]) )) ) ] @html = render('template')({ sd: @sd featuredPartnerProfiles: @profiles }) describe 'template', -> it 'renders featured partners', -> $ = cheerio.load @html $("a.nav-image-item").length.should.equal 3 @profiles.each (profile) -> partner = profile.get 'owner' $partnerItem = $("a.nav-image-item[href='/#{profile.get('id')}']") $partnerItem.length.should.equal 1 $partnerItem.find(".nav-image-item-label-title").length.should.equal 1 $partnerItem.find(".nav-image-item-label-title").text().should.equal partner.get 'name' $partnerItem.find(".nav-image-item-label-subtitle").text().should.containEql partner.get('locations').first().get('city') it 'includes a page title', -> $ = cheerio.load @html $('.page-heading').text().should.equal "Featured Partners" it 'includes a link to the "become a partner" form', -> $ = cheerio.load @html $('.featured-partners-invite').length.should.equal 1 $('.featured-partners-invite a').attr('href').should.equal "https://www.artsy.net/apply/" # TODO: Add this with the other index pages #it 'includes links to galleries and instutions in the header and footer', -> # $ = cheerio.load @html # $('.featured-partners-nav').length.should.equal 2 # $(".featured-partners-nav a[href='/galleries']").length.should.equal 2 # $(".featured-partners-nav a[href='/institutions']").length.should.equal 2 describe 'with incomplete location data', -> it 'renders without a location', -> @profiles = new Profiles [ fabricate('featured_partners_profiles', id: 'gagosian' owner: new Partner(fabricate('partner', type: "Gallery" locations: new Backbone.Collection() # No locations )) ) fabricate('featured_partners_profiles', id: '<NAME>' owner: new Partner(fabricate('partner', type: "Gallery" locations: new Backbone.Collection([fabricate 'location', city: '']) # No city )) ) ] html = render('template')({ sd: @sd featuredPartnerProfiles: @profiles }) $ = cheerio.load html $(".nav-image-item-label-subtitle").length.should.equal 1 $(".nav-image-item-label-subtitle").text().should.equal ''
true
_ = require 'underscore' jade = require 'jade' path = require 'path' fs = require 'fs' cheerio = require 'cheerio' Backbone = require 'backbone' { fabricate } = require 'antigravity' Partner = require '../../../models/partner' Profiles = require '../../../collections/profiles' render = (templateName) -> filename = path.resolve __dirname, "../#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'Partners', -> before -> @sd = API_URL: 'http://localhost:5000' @profiles = new Profiles [ fabricate('featured_partners_profiles', id: 'gagosian' owner: new Partner(fabricate('partner', type: "Gallery" locations: new Backbone.Collection([fabricate('location')]) )) ) fabricate('featured_partners_profiles', id: 'getty' owner: new Partner(fabricate('partner', type: "Institution" name: "PI:NAME:<NAME>END_PI" locations: new Backbone.Collection([fabricate('location')]) )) ) fabricate('featured_partners_profiles', id: 'lacma' owner: new Partner(fabricate('partner', type: "Institution" name: "PI:NAME:<NAME>END_PI" locations: new Backbone.Collection([fabricate('location')]) )) ) ] @html = render('template')({ sd: @sd featuredPartnerProfiles: @profiles }) describe 'template', -> it 'renders featured partners', -> $ = cheerio.load @html $("a.nav-image-item").length.should.equal 3 @profiles.each (profile) -> partner = profile.get 'owner' $partnerItem = $("a.nav-image-item[href='/#{profile.get('id')}']") $partnerItem.length.should.equal 1 $partnerItem.find(".nav-image-item-label-title").length.should.equal 1 $partnerItem.find(".nav-image-item-label-title").text().should.equal partner.get 'name' $partnerItem.find(".nav-image-item-label-subtitle").text().should.containEql partner.get('locations').first().get('city') it 'includes a page title', -> $ = cheerio.load @html $('.page-heading').text().should.equal "Featured Partners" it 'includes a link to the "become a partner" form', -> $ = cheerio.load @html $('.featured-partners-invite').length.should.equal 1 $('.featured-partners-invite a').attr('href').should.equal "https://www.artsy.net/apply/" # TODO: Add this with the other index pages #it 'includes links to galleries and instutions in the header and footer', -> # $ = cheerio.load @html # $('.featured-partners-nav').length.should.equal 2 # $(".featured-partners-nav a[href='/galleries']").length.should.equal 2 # $(".featured-partners-nav a[href='/institutions']").length.should.equal 2 describe 'with incomplete location data', -> it 'renders without a location', -> @profiles = new Profiles [ fabricate('featured_partners_profiles', id: 'gagosian' owner: new Partner(fabricate('partner', type: "Gallery" locations: new Backbone.Collection() # No locations )) ) fabricate('featured_partners_profiles', id: 'PI:NAME:<NAME>END_PI' owner: new Partner(fabricate('partner', type: "Gallery" locations: new Backbone.Collection([fabricate 'location', city: '']) # No city )) ) ] html = render('template')({ sd: @sd featuredPartnerProfiles: @profiles }) $ = cheerio.load html $(".nav-image-item-label-subtitle").length.should.equal 1 $(".nav-image-item-label-subtitle").text().should.equal ''
[ { "context": " = () ->\n new lib.Observable\n firstName: 'Shaun'\n lastName: 'Farrell'\n email: 'sfarrell", "end": 125, "score": 0.999657392501831, "start": 120, "tag": "NAME", "value": "Shaun" }, { "context": "ervable\n firstName: 'Shaun'\n lastName: 'Farrell'\n email: 'sfarrell.development@gmail.com'\n\n ", "end": 151, "score": 0.9844041466712952, "start": 144, "tag": "NAME", "value": "Farrell" }, { "context": ": 'Shaun'\n lastName: 'Farrell'\n email: 'sfarrell.development@gmail.com'\n\n it 'should construct an instance', () ->\n ", "end": 197, "score": 0.99993497133255, "start": 167, "tag": "EMAIL", "value": "sfarrell.development@gmail.com" }, { "context": ".toBe 'email'\n done()\n\n instance.email = 'shaunfarrell@g.harvard.edu'\n", "end": 555, "score": 0.9999331831932068, "start": 529, "tag": "EMAIL", "value": "shaunfarrell@g.harvard.edu" } ]
src/test/observable.spec.coffee
Soundscape/sublime-core
1
lib = require '../' describe 'Observable test suite', () -> create = () -> new lib.Observable firstName: 'Shaun' lastName: 'Farrell' email: 'sfarrell.development@gmail.com' it 'should construct an instance', () -> instance = create() expect(instance).not.toBeNull() it 'should emit change events', (done) -> instance = create() expect(instance).not.toBeNull() instance.on 'change', () -> expect arguments[1].key .toBe 'email' done() instance.email = 'shaunfarrell@g.harvard.edu'
44457
lib = require '../' describe 'Observable test suite', () -> create = () -> new lib.Observable firstName: '<NAME>' lastName: '<NAME>' email: '<EMAIL>' it 'should construct an instance', () -> instance = create() expect(instance).not.toBeNull() it 'should emit change events', (done) -> instance = create() expect(instance).not.toBeNull() instance.on 'change', () -> expect arguments[1].key .toBe 'email' done() instance.email = '<EMAIL>'
true
lib = require '../' describe 'Observable test suite', () -> create = () -> new lib.Observable firstName: 'PI:NAME:<NAME>END_PI' lastName: 'PI:NAME:<NAME>END_PI' email: 'PI:EMAIL:<EMAIL>END_PI' it 'should construct an instance', () -> instance = create() expect(instance).not.toBeNull() it 'should emit change events', (done) -> instance = create() expect(instance).not.toBeNull() instance.on 'change', () -> expect arguments[1].key .toBe 'email' done() instance.email = 'PI:EMAIL:<EMAIL>END_PI'
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9992227554321289, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": " socket.send buf, 0, buf.length, common.PORT, \"127.0.0.1\", afterSend\n return\n afterSend = ->\n ", "end": 1913, "score": 0.9995332360267639, "start": 1904, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
test/simple/test-cluster-dgram-1.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. master = -> # Fork 4 workers. # Wait until all workers are listening. # Start sending messages. # Set up event handlers for every worker. Each worker sends a message when # it has received the expected number of packets. After that it disconnects. setupWorker = (worker) -> received = 0 worker.on "message", (msg) -> received = msg.received console.log "worker %d received %d packets", worker.id, received return worker.on "disconnect", -> assert received is PACKETS_PER_WORKER console.log "worker %d disconnected", worker.id return return listening = 0 i = 0 while i < NUM_WORKERS cluster.fork() i++ cluster.on "listening", -> doSend = -> socket.send buf, 0, buf.length, common.PORT, "127.0.0.1", afterSend return afterSend = -> sent++ if sent < NUM_WORKERS * PACKETS_PER_WORKER doSend() else console.log "master sent %d packets", sent socket.close() return return if ++listening < NUM_WORKERS buf = new Buffer("hello world") socket = dgram.createSocket("udp4") sent = 0 doSend() return for key of cluster.workers setupWorker cluster.workers[key] if cluster.workers.hasOwnProperty(key) return worker = -> received = 0 # Create udp socket and start listening. socket = dgram.createSocket("udp4") socket.on "message", (data, info) -> received++ # Every 10 messages, notify the master. if received is PACKETS_PER_WORKER process.send received: received process.disconnect() return socket.bind common.PORT return NUM_WORKERS = 4 PACKETS_PER_WORKER = 10 assert = require("assert") cluster = require("cluster") common = require("../common") dgram = require("dgram") if process.platform is "win32" console.warn "dgram clustering is currently not supported on windows." process.exit 0 if cluster.isMaster master() else worker()
22455
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. master = -> # Fork 4 workers. # Wait until all workers are listening. # Start sending messages. # Set up event handlers for every worker. Each worker sends a message when # it has received the expected number of packets. After that it disconnects. setupWorker = (worker) -> received = 0 worker.on "message", (msg) -> received = msg.received console.log "worker %d received %d packets", worker.id, received return worker.on "disconnect", -> assert received is PACKETS_PER_WORKER console.log "worker %d disconnected", worker.id return return listening = 0 i = 0 while i < NUM_WORKERS cluster.fork() i++ cluster.on "listening", -> doSend = -> socket.send buf, 0, buf.length, common.PORT, "127.0.0.1", afterSend return afterSend = -> sent++ if sent < NUM_WORKERS * PACKETS_PER_WORKER doSend() else console.log "master sent %d packets", sent socket.close() return return if ++listening < NUM_WORKERS buf = new Buffer("hello world") socket = dgram.createSocket("udp4") sent = 0 doSend() return for key of cluster.workers setupWorker cluster.workers[key] if cluster.workers.hasOwnProperty(key) return worker = -> received = 0 # Create udp socket and start listening. socket = dgram.createSocket("udp4") socket.on "message", (data, info) -> received++ # Every 10 messages, notify the master. if received is PACKETS_PER_WORKER process.send received: received process.disconnect() return socket.bind common.PORT return NUM_WORKERS = 4 PACKETS_PER_WORKER = 10 assert = require("assert") cluster = require("cluster") common = require("../common") dgram = require("dgram") if process.platform is "win32" console.warn "dgram clustering is currently not supported on windows." process.exit 0 if cluster.isMaster master() else worker()
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. master = -> # Fork 4 workers. # Wait until all workers are listening. # Start sending messages. # Set up event handlers for every worker. Each worker sends a message when # it has received the expected number of packets. After that it disconnects. setupWorker = (worker) -> received = 0 worker.on "message", (msg) -> received = msg.received console.log "worker %d received %d packets", worker.id, received return worker.on "disconnect", -> assert received is PACKETS_PER_WORKER console.log "worker %d disconnected", worker.id return return listening = 0 i = 0 while i < NUM_WORKERS cluster.fork() i++ cluster.on "listening", -> doSend = -> socket.send buf, 0, buf.length, common.PORT, "127.0.0.1", afterSend return afterSend = -> sent++ if sent < NUM_WORKERS * PACKETS_PER_WORKER doSend() else console.log "master sent %d packets", sent socket.close() return return if ++listening < NUM_WORKERS buf = new Buffer("hello world") socket = dgram.createSocket("udp4") sent = 0 doSend() return for key of cluster.workers setupWorker cluster.workers[key] if cluster.workers.hasOwnProperty(key) return worker = -> received = 0 # Create udp socket and start listening. socket = dgram.createSocket("udp4") socket.on "message", (data, info) -> received++ # Every 10 messages, notify the master. if received is PACKETS_PER_WORKER process.send received: received process.disconnect() return socket.bind common.PORT return NUM_WORKERS = 4 PACKETS_PER_WORKER = 10 assert = require("assert") cluster = require("cluster") common = require("../common") dgram = require("dgram") if process.platform is "win32" console.warn "dgram clustering is currently not supported on windows." process.exit 0 if cluster.isMaster master() else worker()
[ { "context": "ual('password').set((password) ->\n @_password = password\n @salt = @makeSalt()\n @hashedPassword = @ha", "end": 929, "score": 0.9966938495635986, "start": 921, "tag": "PASSWORD", "value": "password" } ]
src/server/models/user.coffee
yournal/YournalProject
1
exports.UserSchema = ($mongoose, crypto) -> validate = (value) -> return (@provider and @provider isnt 'local') or value.length UserSchema = new $mongoose.Schema( firstName: type: String, required: true validate: [validate, 'First name cannot be blank.'] lastName: type: String, required: true validate: [validate, 'Last name cannot be blank.'] email: type: String required: true unique: true match: [/.+\@.+\..+/, 'Please enter a valid email.'] validate: [validate, 'Email cannot be blank.'] roles: type: Array default: ['authenticated'] hashedPassword: type: String required: true validate: [validate, 'Password cannot be blank.'] provider: type: String default: 'local' salt: String facebook: {} ) UserSchema.virtual('password').set((password) -> @_password = password @salt = @makeSalt() @hashedPassword = @hashPassword password ).get -> @_password UserSchema.pre 'save', (next) -> if @isNew and @provider is 'local' and @password and not @password.length return next new Error('Invalid password.') next() UserSchema.methods = authenticate: (plainText) -> @hashPassword(plainText) is @hashedPassword makeSalt: -> crypto.randomBytes(16).toString('base64') hashPassword: (password) -> if not password or !@salt return '' salt = new Buffer this.salt, 'base64' crypto.pbkdf2Sync(password, salt, 10000, 64).toString 'base64' return UserSchema exports.UserModel = ($connection, UserSchema) -> $connection.model('User', UserSchema)
69398
exports.UserSchema = ($mongoose, crypto) -> validate = (value) -> return (@provider and @provider isnt 'local') or value.length UserSchema = new $mongoose.Schema( firstName: type: String, required: true validate: [validate, 'First name cannot be blank.'] lastName: type: String, required: true validate: [validate, 'Last name cannot be blank.'] email: type: String required: true unique: true match: [/.+\@.+\..+/, 'Please enter a valid email.'] validate: [validate, 'Email cannot be blank.'] roles: type: Array default: ['authenticated'] hashedPassword: type: String required: true validate: [validate, 'Password cannot be blank.'] provider: type: String default: 'local' salt: String facebook: {} ) UserSchema.virtual('password').set((password) -> @_password = <PASSWORD> @salt = @makeSalt() @hashedPassword = @hashPassword password ).get -> @_password UserSchema.pre 'save', (next) -> if @isNew and @provider is 'local' and @password and not @password.length return next new Error('Invalid password.') next() UserSchema.methods = authenticate: (plainText) -> @hashPassword(plainText) is @hashedPassword makeSalt: -> crypto.randomBytes(16).toString('base64') hashPassword: (password) -> if not password or !@salt return '' salt = new Buffer this.salt, 'base64' crypto.pbkdf2Sync(password, salt, 10000, 64).toString 'base64' return UserSchema exports.UserModel = ($connection, UserSchema) -> $connection.model('User', UserSchema)
true
exports.UserSchema = ($mongoose, crypto) -> validate = (value) -> return (@provider and @provider isnt 'local') or value.length UserSchema = new $mongoose.Schema( firstName: type: String, required: true validate: [validate, 'First name cannot be blank.'] lastName: type: String, required: true validate: [validate, 'Last name cannot be blank.'] email: type: String required: true unique: true match: [/.+\@.+\..+/, 'Please enter a valid email.'] validate: [validate, 'Email cannot be blank.'] roles: type: Array default: ['authenticated'] hashedPassword: type: String required: true validate: [validate, 'Password cannot be blank.'] provider: type: String default: 'local' salt: String facebook: {} ) UserSchema.virtual('password').set((password) -> @_password = PI:PASSWORD:<PASSWORD>END_PI @salt = @makeSalt() @hashedPassword = @hashPassword password ).get -> @_password UserSchema.pre 'save', (next) -> if @isNew and @provider is 'local' and @password and not @password.length return next new Error('Invalid password.') next() UserSchema.methods = authenticate: (plainText) -> @hashPassword(plainText) is @hashedPassword makeSalt: -> crypto.randomBytes(16).toString('base64') hashPassword: (password) -> if not password or !@salt return '' salt = new Buffer this.salt, 'base64' crypto.pbkdf2Sync(password, salt, 10000, 64).toString 'base64' return UserSchema exports.UserModel = ($connection, UserSchema) -> $connection.model('User', UserSchema)
[ { "context": " $('.venice-overlay__subscribe-form input').val('email@email.com')\n $('.venice-overlay__subscribe-form button')", "end": 8036, "score": 0.9997875094413757, "start": 8021, "tag": "EMAIL", "value": "email@email.com" } ]
src/desktop/apps/editorial_features/test/components/venice_2017/index.coffee
kanaabe/force
0
_ = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' Article = require '../../../../../models/article' Curation = require '../../../../../models/curation.coffee' { resolve } = require 'path' markdown = require '../../../../../components/util/markdown.coffee' describe 'Venice Main', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require('jquery') jQuery: benv.require('jquery') window: history: replaceState: @replaceState = sinon.stub() innerHeight: 900 moment: require 'moment' markdown: markdown crop: crop = sinon.stub().returns 'http://artsy.net/image.jpg' Backbone.$ = $ $.fn.fadeOut = @fadeOut = sinon.stub() @animateSpy = sinon.spy $.fn, 'animate' @curation = description: 'description' sub_articles: [{thumbnail_title:{'Sub 1'}, thumbnail_image: 'http://artsy.net/image.jpg'}, {thumbnail_title:{'Sub 2'}, thumbnail_image: 'http://artsy.net/image2.jpg'}] sections: [ { description: 'description' cover_image: '' video_url: '/vanity/url.mp4' video_url_medium: '/vanity/url-medium.mp4' video_url_adaptive: '/vanity/url.mpd' slug: 'slug-one' artist_ids: [] }, { description: 'description2' cover_image: '' video_url: '/vanity/url2.mp4' video_url_medium: '/vanity/url2-medium.mp4' video_url_adaptive: '/vanity/url2.mpd' slug: 'slug-two' published: true artist_ids: [] }, { description: 'description2' cover_image: '' video_url: '/vanity/url3.mp4' video_url_medium: '/vanity/url3-medium.mp4' video_url_adaptive: '/vanity/url3.mpd' slug: 'slug-three' published: true artist_ids: [] } ] @options = asset: -> sd: APP_URL: 'localhost' videoIndex: 0 curation: new Curation @curation videoGuide: new Article {id: '123', title: 'Video Guide'} sub_articles: [{title:{'Sub 1'}, thumbnail_image: 'http://artsy.net/image.jpg'}, {title:{'Sub 2'}, thumbnail_image: 'http://artsy.net/image2.jpg'}] benv.render resolve(__dirname, '../../../components/venice_2017/templates/index.jade'), @options, => VeniceView = benv.requireWithJadeify resolve(__dirname, '../../../components/venice_2017/client/index'), ['videoDescription'] VeniceView.__set__ 'sd', APP_URL: 'localhost' VIDEO_INDEX: 0 CURATION: @curation VeniceView.__set__ 'VeniceVideoView', @VeniceVideoView = sinon.stub().returns vrView: play: @play = sinon.stub() pause: @pause = sinon.stub() trigger: sinon.stub() fadeOutControls: sinon.stub() VeniceView.__set__ 'initCarousel', @initCarousel = sinon.stub().yields cells: flickity: on: @on = sinon.stub() selectedIndex: 1 select: sinon.stub() next: sinon.stub() VeniceView.__set__ 'initFooterCarousel', @initFooterCarousel = sinon.stub() VeniceView.__set__ 'FlashMessage', sinon.stub() @view = new VeniceView el: $('body') done() afterEach -> @animateSpy.restore() benv.teardown() it 'initializes VeniceVideoView', -> @VeniceVideoView.args[0][0].el.selector.should.equal '.venice-video' @VeniceVideoView.args[0][0].video.should.equal 'localhost/vanity/url.mp4' it 'sets up the carousel', -> @initCarousel.args[0][0].selector.should.equal '.venice-carousel' @initCarousel.args[0][1].advanceBy.should.equal 1 @initCarousel.args[0][1].wrapAround.should.be.true() @initCarousel.args[0][1].initialIndex.should.equal 0 @initCarousel.args[0][2](cells: flickity: on: ->) @fadeOut.callCount.should.equal 2 it 'Sets up the footer carousel', -> $(@view.el).find('.venice-footer').html().should.containEql '<h2 class="title">The Venice Biennale</h2>' $(@view.el).find('.venice-footer .mgr-cell').length.should.eql 2 $(@view.el).find('.venice-footer .mgr-cells').html().should.containEql '<img src="http://artsy.net/image.jpg">' it 'changes the section when flickity has settled #settleSection', -> @on.args[0][1]() @on.args[0][0].should.equal 'settle' @view.VeniceVideoView.trigger.args[0][0].should.equal 'swapVideo' @view.VeniceVideoView.trigger.args[0][1].video.should.equal 'localhost/vanity/url2.mp4' it 'changes the section when flickity item has been selected #selectSection', -> @on.args[1][1]() @on.args[1][0].should.equal 'select' @replaceState.args[0][1].should.equal 1 @replaceState.args[0][2].should.equal '/venice-biennale/slug-two' $('.venice-overlay__play').attr('data-state').should.equal 'loading' it '#fadeOutCoverAndStartVideo does not play if it is not ready', -> $('.venice-overlay__play').click() @play.callCount.should.equal 0 it '#fadeOutCoverAndStartVideo', -> $('.venice-overlay__play').first().attr 'data-state', 'ready' $('.venice-overlay__play').first().click() @play.callCount.should.equal 1 @view.VeniceVideoView.fadeOutControls.callCount.should.equal 1 it 'fades out controls after pressing play on mobile', -> $('.venice-overlay__play').first().attr 'data-state', 'ready' @view.parser = getDevice: sinon.stub().returns type: 'mobile' $('.venice-overlay__play').first().click() @view.VeniceVideoView.fadeOutControls.callCount.should.equal 1 it '#fadeInCoverAndPauseVideo', -> @view.fadeInCoverAndPauseVideo() @pause.callCount.should.equal 1 it '#onVideoReady', -> @view.onVideoReady() $('.venice-overlay__play').attr('data-state').should.equal 'ready' it 'chooses a medium quality mp4 video for iOS', -> @view.parser = getOS: sinon.stub().returns name: 'iOS' @view.chooseVideoFile().should.equal 'localhost/vanity/url-medium.mp4' it 'chooses an adaptive video for mobile', -> @view.parser = getOS: sinon.stub().returns name: 'Android' getDevice: sinon.stub().returns type: 'mobile' @view.chooseVideoFile().should.equal 'localhost/vanity/url.mpd' it 'chooses a high quality video for desktop', -> @view.parser = getOS: sinon.stub().returns name: 'Mac OS' getDevice: sinon.stub().returns type: null @view.chooseVideoFile().should.equal 'localhost/vanity/url.mp4' it '#onVideoCompleted fades out the video player and displays completed cover', -> @view.fadeInCoverAndPauseVideo = sinon.stub() @view.onVideoCompleted() @view.fadeInCoverAndPauseVideo.callCount.should.eql 1 it '#onNextVideo advances the carousel to the next slide', -> @view.onVideoCompleted() $('.venice-overlay--completed .next')[0].click() @view.flickity.next.args[0][0].should.be.true() @view.flickity.next.callCount.should.equal 1 it '#onReadMore scrolls to the video description and hides completed cover (read-more)', -> @view.onVideoCompleted() $('.venice-overlay--completed .read-more').click() @animateSpy.args[1][0].opacity.should.eql 0 @animateSpy.args[1][0]['z-index'].should.eql -1 @animateSpy.args[2][0].scrollTop.should.eql 900 it '#onReadMore scrolls to the video description and hides completed cover (info icon)', -> @view.onVideoCompleted() $('.venice-info-icon').click() @animateSpy.args[1][0].opacity.should.eql 0 @animateSpy.args[1][0]['z-index'].should.eql -1 @animateSpy.args[2][0].scrollTop.should.eql 900 it '#showCta reveals a signup form', -> $('.venice-overlay__cta-button').click() $('.venice-overlay__subscribe-form').css('opacity').should.eql '1' it '#onSubscribe', -> $('.venice-overlay__cta-button').click() $('.venice-overlay__subscribe-form input').val('email@email.com') $('.venice-overlay__subscribe-form button').click() $('.venice-overlay__cta-button').css('opacity').should.not.eql '0' it 'displays an error if there is one', -> @view.onVideoError 'Sorry, your browser is not supported.' $('.venice-overlay__play').attr('data-state').should.equal 'error' $('.venice-overlay__error').html().should.equal 'Sorry, your browser is not supported.' describe 'VeniceView isSubscribed', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require('jquery') jQuery: benv.require('jquery') window: history: replaceState: @replaceState = sinon.stub() innerHeight: 900 moment: require 'moment' markdown: markdown crop: sinon.stub().returns 'http://artsy.net/image.jpg' Backbone.$ = $ @curation = description: 'description' sub_articles: [] sections: [ { description: 'description' cover_image: '' video_url: '/vanity/url.mp4' video_url_medium: '/vanity/url-medium.mp4' video_url_adaptive: '/vanity/url.mpd' slug: 'slug-one' artist_ids: [] } ] @options = asset: -> sd: APP_URL: 'localhost' videoIndex: 0 curation: new Curation @curation videoGuide: new Article {id: '123', title: 'Video Guide'} isSubscribed: true benv.render resolve(__dirname, '../../../components/venice_2017/templates/index.jade'), @options, => VeniceView = benv.requireWithJadeify resolve(__dirname, '../../../components/venice_2017/client/index'), ['videoDescription'] VeniceView.__set__ 'sd', APP_URL: 'localhost' VIDEO_INDEX: 0 CURATION: @curation VeniceView.__set__ 'VeniceVideoView', @VeniceVideoView = sinon.stub().returns vrView: play: @play = sinon.stub() pause: @pause = sinon.stub() trigger: sinon.stub() VeniceView.__set__ 'initCarousel', @initCarousel = sinon.stub().yields cells: flickity: on: @on = sinon.stub() selectedIndex: 1 select: sinon.stub() next: sinon.stub() @view = new VeniceView el: $('body') done() afterEach -> benv.teardown() it 'Hides the subscribe to editorial form if user is subscribed', -> $('.venice-overlay__subscribe-form').length.should.eql 0
126366
_ = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' Article = require '../../../../../models/article' Curation = require '../../../../../models/curation.coffee' { resolve } = require 'path' markdown = require '../../../../../components/util/markdown.coffee' describe 'Venice Main', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require('jquery') jQuery: benv.require('jquery') window: history: replaceState: @replaceState = sinon.stub() innerHeight: 900 moment: require 'moment' markdown: markdown crop: crop = sinon.stub().returns 'http://artsy.net/image.jpg' Backbone.$ = $ $.fn.fadeOut = @fadeOut = sinon.stub() @animateSpy = sinon.spy $.fn, 'animate' @curation = description: 'description' sub_articles: [{thumbnail_title:{'Sub 1'}, thumbnail_image: 'http://artsy.net/image.jpg'}, {thumbnail_title:{'Sub 2'}, thumbnail_image: 'http://artsy.net/image2.jpg'}] sections: [ { description: 'description' cover_image: '' video_url: '/vanity/url.mp4' video_url_medium: '/vanity/url-medium.mp4' video_url_adaptive: '/vanity/url.mpd' slug: 'slug-one' artist_ids: [] }, { description: 'description2' cover_image: '' video_url: '/vanity/url2.mp4' video_url_medium: '/vanity/url2-medium.mp4' video_url_adaptive: '/vanity/url2.mpd' slug: 'slug-two' published: true artist_ids: [] }, { description: 'description2' cover_image: '' video_url: '/vanity/url3.mp4' video_url_medium: '/vanity/url3-medium.mp4' video_url_adaptive: '/vanity/url3.mpd' slug: 'slug-three' published: true artist_ids: [] } ] @options = asset: -> sd: APP_URL: 'localhost' videoIndex: 0 curation: new Curation @curation videoGuide: new Article {id: '123', title: 'Video Guide'} sub_articles: [{title:{'Sub 1'}, thumbnail_image: 'http://artsy.net/image.jpg'}, {title:{'Sub 2'}, thumbnail_image: 'http://artsy.net/image2.jpg'}] benv.render resolve(__dirname, '../../../components/venice_2017/templates/index.jade'), @options, => VeniceView = benv.requireWithJadeify resolve(__dirname, '../../../components/venice_2017/client/index'), ['videoDescription'] VeniceView.__set__ 'sd', APP_URL: 'localhost' VIDEO_INDEX: 0 CURATION: @curation VeniceView.__set__ 'VeniceVideoView', @VeniceVideoView = sinon.stub().returns vrView: play: @play = sinon.stub() pause: @pause = sinon.stub() trigger: sinon.stub() fadeOutControls: sinon.stub() VeniceView.__set__ 'initCarousel', @initCarousel = sinon.stub().yields cells: flickity: on: @on = sinon.stub() selectedIndex: 1 select: sinon.stub() next: sinon.stub() VeniceView.__set__ 'initFooterCarousel', @initFooterCarousel = sinon.stub() VeniceView.__set__ 'FlashMessage', sinon.stub() @view = new VeniceView el: $('body') done() afterEach -> @animateSpy.restore() benv.teardown() it 'initializes VeniceVideoView', -> @VeniceVideoView.args[0][0].el.selector.should.equal '.venice-video' @VeniceVideoView.args[0][0].video.should.equal 'localhost/vanity/url.mp4' it 'sets up the carousel', -> @initCarousel.args[0][0].selector.should.equal '.venice-carousel' @initCarousel.args[0][1].advanceBy.should.equal 1 @initCarousel.args[0][1].wrapAround.should.be.true() @initCarousel.args[0][1].initialIndex.should.equal 0 @initCarousel.args[0][2](cells: flickity: on: ->) @fadeOut.callCount.should.equal 2 it 'Sets up the footer carousel', -> $(@view.el).find('.venice-footer').html().should.containEql '<h2 class="title">The Venice Biennale</h2>' $(@view.el).find('.venice-footer .mgr-cell').length.should.eql 2 $(@view.el).find('.venice-footer .mgr-cells').html().should.containEql '<img src="http://artsy.net/image.jpg">' it 'changes the section when flickity has settled #settleSection', -> @on.args[0][1]() @on.args[0][0].should.equal 'settle' @view.VeniceVideoView.trigger.args[0][0].should.equal 'swapVideo' @view.VeniceVideoView.trigger.args[0][1].video.should.equal 'localhost/vanity/url2.mp4' it 'changes the section when flickity item has been selected #selectSection', -> @on.args[1][1]() @on.args[1][0].should.equal 'select' @replaceState.args[0][1].should.equal 1 @replaceState.args[0][2].should.equal '/venice-biennale/slug-two' $('.venice-overlay__play').attr('data-state').should.equal 'loading' it '#fadeOutCoverAndStartVideo does not play if it is not ready', -> $('.venice-overlay__play').click() @play.callCount.should.equal 0 it '#fadeOutCoverAndStartVideo', -> $('.venice-overlay__play').first().attr 'data-state', 'ready' $('.venice-overlay__play').first().click() @play.callCount.should.equal 1 @view.VeniceVideoView.fadeOutControls.callCount.should.equal 1 it 'fades out controls after pressing play on mobile', -> $('.venice-overlay__play').first().attr 'data-state', 'ready' @view.parser = getDevice: sinon.stub().returns type: 'mobile' $('.venice-overlay__play').first().click() @view.VeniceVideoView.fadeOutControls.callCount.should.equal 1 it '#fadeInCoverAndPauseVideo', -> @view.fadeInCoverAndPauseVideo() @pause.callCount.should.equal 1 it '#onVideoReady', -> @view.onVideoReady() $('.venice-overlay__play').attr('data-state').should.equal 'ready' it 'chooses a medium quality mp4 video for iOS', -> @view.parser = getOS: sinon.stub().returns name: 'iOS' @view.chooseVideoFile().should.equal 'localhost/vanity/url-medium.mp4' it 'chooses an adaptive video for mobile', -> @view.parser = getOS: sinon.stub().returns name: 'Android' getDevice: sinon.stub().returns type: 'mobile' @view.chooseVideoFile().should.equal 'localhost/vanity/url.mpd' it 'chooses a high quality video for desktop', -> @view.parser = getOS: sinon.stub().returns name: 'Mac OS' getDevice: sinon.stub().returns type: null @view.chooseVideoFile().should.equal 'localhost/vanity/url.mp4' it '#onVideoCompleted fades out the video player and displays completed cover', -> @view.fadeInCoverAndPauseVideo = sinon.stub() @view.onVideoCompleted() @view.fadeInCoverAndPauseVideo.callCount.should.eql 1 it '#onNextVideo advances the carousel to the next slide', -> @view.onVideoCompleted() $('.venice-overlay--completed .next')[0].click() @view.flickity.next.args[0][0].should.be.true() @view.flickity.next.callCount.should.equal 1 it '#onReadMore scrolls to the video description and hides completed cover (read-more)', -> @view.onVideoCompleted() $('.venice-overlay--completed .read-more').click() @animateSpy.args[1][0].opacity.should.eql 0 @animateSpy.args[1][0]['z-index'].should.eql -1 @animateSpy.args[2][0].scrollTop.should.eql 900 it '#onReadMore scrolls to the video description and hides completed cover (info icon)', -> @view.onVideoCompleted() $('.venice-info-icon').click() @animateSpy.args[1][0].opacity.should.eql 0 @animateSpy.args[1][0]['z-index'].should.eql -1 @animateSpy.args[2][0].scrollTop.should.eql 900 it '#showCta reveals a signup form', -> $('.venice-overlay__cta-button').click() $('.venice-overlay__subscribe-form').css('opacity').should.eql '1' it '#onSubscribe', -> $('.venice-overlay__cta-button').click() $('.venice-overlay__subscribe-form input').val('<EMAIL>') $('.venice-overlay__subscribe-form button').click() $('.venice-overlay__cta-button').css('opacity').should.not.eql '0' it 'displays an error if there is one', -> @view.onVideoError 'Sorry, your browser is not supported.' $('.venice-overlay__play').attr('data-state').should.equal 'error' $('.venice-overlay__error').html().should.equal 'Sorry, your browser is not supported.' describe 'VeniceView isSubscribed', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require('jquery') jQuery: benv.require('jquery') window: history: replaceState: @replaceState = sinon.stub() innerHeight: 900 moment: require 'moment' markdown: markdown crop: sinon.stub().returns 'http://artsy.net/image.jpg' Backbone.$ = $ @curation = description: 'description' sub_articles: [] sections: [ { description: 'description' cover_image: '' video_url: '/vanity/url.mp4' video_url_medium: '/vanity/url-medium.mp4' video_url_adaptive: '/vanity/url.mpd' slug: 'slug-one' artist_ids: [] } ] @options = asset: -> sd: APP_URL: 'localhost' videoIndex: 0 curation: new Curation @curation videoGuide: new Article {id: '123', title: 'Video Guide'} isSubscribed: true benv.render resolve(__dirname, '../../../components/venice_2017/templates/index.jade'), @options, => VeniceView = benv.requireWithJadeify resolve(__dirname, '../../../components/venice_2017/client/index'), ['videoDescription'] VeniceView.__set__ 'sd', APP_URL: 'localhost' VIDEO_INDEX: 0 CURATION: @curation VeniceView.__set__ 'VeniceVideoView', @VeniceVideoView = sinon.stub().returns vrView: play: @play = sinon.stub() pause: @pause = sinon.stub() trigger: sinon.stub() VeniceView.__set__ 'initCarousel', @initCarousel = sinon.stub().yields cells: flickity: on: @on = sinon.stub() selectedIndex: 1 select: sinon.stub() next: sinon.stub() @view = new VeniceView el: $('body') done() afterEach -> benv.teardown() it 'Hides the subscribe to editorial form if user is subscribed', -> $('.venice-overlay__subscribe-form').length.should.eql 0
true
_ = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' Article = require '../../../../../models/article' Curation = require '../../../../../models/curation.coffee' { resolve } = require 'path' markdown = require '../../../../../components/util/markdown.coffee' describe 'Venice Main', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require('jquery') jQuery: benv.require('jquery') window: history: replaceState: @replaceState = sinon.stub() innerHeight: 900 moment: require 'moment' markdown: markdown crop: crop = sinon.stub().returns 'http://artsy.net/image.jpg' Backbone.$ = $ $.fn.fadeOut = @fadeOut = sinon.stub() @animateSpy = sinon.spy $.fn, 'animate' @curation = description: 'description' sub_articles: [{thumbnail_title:{'Sub 1'}, thumbnail_image: 'http://artsy.net/image.jpg'}, {thumbnail_title:{'Sub 2'}, thumbnail_image: 'http://artsy.net/image2.jpg'}] sections: [ { description: 'description' cover_image: '' video_url: '/vanity/url.mp4' video_url_medium: '/vanity/url-medium.mp4' video_url_adaptive: '/vanity/url.mpd' slug: 'slug-one' artist_ids: [] }, { description: 'description2' cover_image: '' video_url: '/vanity/url2.mp4' video_url_medium: '/vanity/url2-medium.mp4' video_url_adaptive: '/vanity/url2.mpd' slug: 'slug-two' published: true artist_ids: [] }, { description: 'description2' cover_image: '' video_url: '/vanity/url3.mp4' video_url_medium: '/vanity/url3-medium.mp4' video_url_adaptive: '/vanity/url3.mpd' slug: 'slug-three' published: true artist_ids: [] } ] @options = asset: -> sd: APP_URL: 'localhost' videoIndex: 0 curation: new Curation @curation videoGuide: new Article {id: '123', title: 'Video Guide'} sub_articles: [{title:{'Sub 1'}, thumbnail_image: 'http://artsy.net/image.jpg'}, {title:{'Sub 2'}, thumbnail_image: 'http://artsy.net/image2.jpg'}] benv.render resolve(__dirname, '../../../components/venice_2017/templates/index.jade'), @options, => VeniceView = benv.requireWithJadeify resolve(__dirname, '../../../components/venice_2017/client/index'), ['videoDescription'] VeniceView.__set__ 'sd', APP_URL: 'localhost' VIDEO_INDEX: 0 CURATION: @curation VeniceView.__set__ 'VeniceVideoView', @VeniceVideoView = sinon.stub().returns vrView: play: @play = sinon.stub() pause: @pause = sinon.stub() trigger: sinon.stub() fadeOutControls: sinon.stub() VeniceView.__set__ 'initCarousel', @initCarousel = sinon.stub().yields cells: flickity: on: @on = sinon.stub() selectedIndex: 1 select: sinon.stub() next: sinon.stub() VeniceView.__set__ 'initFooterCarousel', @initFooterCarousel = sinon.stub() VeniceView.__set__ 'FlashMessage', sinon.stub() @view = new VeniceView el: $('body') done() afterEach -> @animateSpy.restore() benv.teardown() it 'initializes VeniceVideoView', -> @VeniceVideoView.args[0][0].el.selector.should.equal '.venice-video' @VeniceVideoView.args[0][0].video.should.equal 'localhost/vanity/url.mp4' it 'sets up the carousel', -> @initCarousel.args[0][0].selector.should.equal '.venice-carousel' @initCarousel.args[0][1].advanceBy.should.equal 1 @initCarousel.args[0][1].wrapAround.should.be.true() @initCarousel.args[0][1].initialIndex.should.equal 0 @initCarousel.args[0][2](cells: flickity: on: ->) @fadeOut.callCount.should.equal 2 it 'Sets up the footer carousel', -> $(@view.el).find('.venice-footer').html().should.containEql '<h2 class="title">The Venice Biennale</h2>' $(@view.el).find('.venice-footer .mgr-cell').length.should.eql 2 $(@view.el).find('.venice-footer .mgr-cells').html().should.containEql '<img src="http://artsy.net/image.jpg">' it 'changes the section when flickity has settled #settleSection', -> @on.args[0][1]() @on.args[0][0].should.equal 'settle' @view.VeniceVideoView.trigger.args[0][0].should.equal 'swapVideo' @view.VeniceVideoView.trigger.args[0][1].video.should.equal 'localhost/vanity/url2.mp4' it 'changes the section when flickity item has been selected #selectSection', -> @on.args[1][1]() @on.args[1][0].should.equal 'select' @replaceState.args[0][1].should.equal 1 @replaceState.args[0][2].should.equal '/venice-biennale/slug-two' $('.venice-overlay__play').attr('data-state').should.equal 'loading' it '#fadeOutCoverAndStartVideo does not play if it is not ready', -> $('.venice-overlay__play').click() @play.callCount.should.equal 0 it '#fadeOutCoverAndStartVideo', -> $('.venice-overlay__play').first().attr 'data-state', 'ready' $('.venice-overlay__play').first().click() @play.callCount.should.equal 1 @view.VeniceVideoView.fadeOutControls.callCount.should.equal 1 it 'fades out controls after pressing play on mobile', -> $('.venice-overlay__play').first().attr 'data-state', 'ready' @view.parser = getDevice: sinon.stub().returns type: 'mobile' $('.venice-overlay__play').first().click() @view.VeniceVideoView.fadeOutControls.callCount.should.equal 1 it '#fadeInCoverAndPauseVideo', -> @view.fadeInCoverAndPauseVideo() @pause.callCount.should.equal 1 it '#onVideoReady', -> @view.onVideoReady() $('.venice-overlay__play').attr('data-state').should.equal 'ready' it 'chooses a medium quality mp4 video for iOS', -> @view.parser = getOS: sinon.stub().returns name: 'iOS' @view.chooseVideoFile().should.equal 'localhost/vanity/url-medium.mp4' it 'chooses an adaptive video for mobile', -> @view.parser = getOS: sinon.stub().returns name: 'Android' getDevice: sinon.stub().returns type: 'mobile' @view.chooseVideoFile().should.equal 'localhost/vanity/url.mpd' it 'chooses a high quality video for desktop', -> @view.parser = getOS: sinon.stub().returns name: 'Mac OS' getDevice: sinon.stub().returns type: null @view.chooseVideoFile().should.equal 'localhost/vanity/url.mp4' it '#onVideoCompleted fades out the video player and displays completed cover', -> @view.fadeInCoverAndPauseVideo = sinon.stub() @view.onVideoCompleted() @view.fadeInCoverAndPauseVideo.callCount.should.eql 1 it '#onNextVideo advances the carousel to the next slide', -> @view.onVideoCompleted() $('.venice-overlay--completed .next')[0].click() @view.flickity.next.args[0][0].should.be.true() @view.flickity.next.callCount.should.equal 1 it '#onReadMore scrolls to the video description and hides completed cover (read-more)', -> @view.onVideoCompleted() $('.venice-overlay--completed .read-more').click() @animateSpy.args[1][0].opacity.should.eql 0 @animateSpy.args[1][0]['z-index'].should.eql -1 @animateSpy.args[2][0].scrollTop.should.eql 900 it '#onReadMore scrolls to the video description and hides completed cover (info icon)', -> @view.onVideoCompleted() $('.venice-info-icon').click() @animateSpy.args[1][0].opacity.should.eql 0 @animateSpy.args[1][0]['z-index'].should.eql -1 @animateSpy.args[2][0].scrollTop.should.eql 900 it '#showCta reveals a signup form', -> $('.venice-overlay__cta-button').click() $('.venice-overlay__subscribe-form').css('opacity').should.eql '1' it '#onSubscribe', -> $('.venice-overlay__cta-button').click() $('.venice-overlay__subscribe-form input').val('PI:EMAIL:<EMAIL>END_PI') $('.venice-overlay__subscribe-form button').click() $('.venice-overlay__cta-button').css('opacity').should.not.eql '0' it 'displays an error if there is one', -> @view.onVideoError 'Sorry, your browser is not supported.' $('.venice-overlay__play').attr('data-state').should.equal 'error' $('.venice-overlay__error').html().should.equal 'Sorry, your browser is not supported.' describe 'VeniceView isSubscribed', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require('jquery') jQuery: benv.require('jquery') window: history: replaceState: @replaceState = sinon.stub() innerHeight: 900 moment: require 'moment' markdown: markdown crop: sinon.stub().returns 'http://artsy.net/image.jpg' Backbone.$ = $ @curation = description: 'description' sub_articles: [] sections: [ { description: 'description' cover_image: '' video_url: '/vanity/url.mp4' video_url_medium: '/vanity/url-medium.mp4' video_url_adaptive: '/vanity/url.mpd' slug: 'slug-one' artist_ids: [] } ] @options = asset: -> sd: APP_URL: 'localhost' videoIndex: 0 curation: new Curation @curation videoGuide: new Article {id: '123', title: 'Video Guide'} isSubscribed: true benv.render resolve(__dirname, '../../../components/venice_2017/templates/index.jade'), @options, => VeniceView = benv.requireWithJadeify resolve(__dirname, '../../../components/venice_2017/client/index'), ['videoDescription'] VeniceView.__set__ 'sd', APP_URL: 'localhost' VIDEO_INDEX: 0 CURATION: @curation VeniceView.__set__ 'VeniceVideoView', @VeniceVideoView = sinon.stub().returns vrView: play: @play = sinon.stub() pause: @pause = sinon.stub() trigger: sinon.stub() VeniceView.__set__ 'initCarousel', @initCarousel = sinon.stub().yields cells: flickity: on: @on = sinon.stub() selectedIndex: 1 select: sinon.stub() next: sinon.stub() @view = new VeniceView el: $('body') done() afterEach -> benv.teardown() it 'Hides the subscribe to editorial form if user is subscribed', -> $('.venice-overlay__subscribe-form').length.should.eql 0
[ { "context": "ileoverview Tests for no-overwrite rule.\n# @author Julian Rosse\n###\n\n'use strict'\n\n#-----------------------------", "end": 72, "score": 0.9998520016670227, "start": 60, "tag": "NAME", "value": "Julian Rosse" } ]
src/tests/rules/no-overwrite.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for no-overwrite rule. # @author Julian Rosse ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-overwrite' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' error = type: 'Identifier' ruleTester.run 'no-overwrite', rule, valid: [ 'a = 1' 'a = b = 2' ''' a = null a = 1 ''' ''' a = null a = -> 1 ''' ''' a = null -> a = 1 ''' ''' if x a = 1 else a = 2 ''' # , # code: ''' # if x # a = 1 # else # a = 2 # ''' # options: [allowSameScope: no] ''' a = 1 a = 2 unless b ''' ''' a = 1 -> a++ ''' ''' a = 1 a++ ''' 'class a' ''' a = class a ''' ''' a = null a = null ''' ''' a = 1 foo = (a) -> ''' ''' (a) -> (a) -> ''' ''' a = 1 do (a) -> ''' ''' a = (a) -> ''' ''' x = 1 for x in y ; ''' ''' x = null -> for x in y ; ''' ''' a = null -> for b, a of c ; ''' ''' a = 1 -> a ###:###= 2 ''' , code: ''' a = 1 a ###:=### = 2 ''' options: [allowSameScope: no] , ''' a = 1 -> for b, ###:=### a of c ; ''' ''' a = 1 -> for ###:=### a, b in c ; ''' ''' a = -> class ###:=### a ''' ''' a = -> class a ###:=### ''' ''' a = 1 -> [a, b] ###:### = 2 ''' ''' a = 1 -> a += 2 ''' ] invalid: [ code: ''' a = 1 -> a = 2 ''' errors: [error] , code: ''' a = 1 -> [a, b] = 2 ''' errors: [error] , code: ''' a = 1 a = 2 unless b ''' errors: [error] options: [allowSameScope: no] , code: ''' a = 1 a = 2 ''' errors: [error] options: [allowSameScope: no] , code: ''' a = null a = 1 ''' errors: [error] options: [allowSameScope: no, allowNullInitializers: no] , code: ''' a = null a = -> 1 ''' errors: [error] options: [allowSameScope: no, allowNullInitializers: no] , code: ''' a = null -> a = 1 ''' errors: [error] options: [allowNullInitializers: no] , code: ''' class a constructor: -> a = null ''' errors: [error] , code: ''' a = -> a = 10 ''' errors: [error] , code: ''' a = -> a = -> ''' errors: [error] , code: ''' a = -> class a ''' errors: [error] , code: ''' do -> a = class constructor: -> class a ''' errors: [error] , code: ''' class a constructor: -> a = null ''' errors: [error] , code: ''' class a constructor: -> class a ''' errors: [error] , code: ''' a = 1 for a in b ; ''' options: [allowSameScope: no] errors: [error] , code: ''' a = null -> for a in b ; ''' options: [allowNullInitializers: no] errors: [error] , code: ''' a = 1 -> for b, a of c ; ''' errors: [error] , code: ''' a = 1 -> for i in [0..10] a = i ''' errors: [error] , code: ''' a = null -> a = 1 a = 2 ''' errors: [error] ]
118623
###* # @fileoverview Tests for no-overwrite rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-overwrite' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' error = type: 'Identifier' ruleTester.run 'no-overwrite', rule, valid: [ 'a = 1' 'a = b = 2' ''' a = null a = 1 ''' ''' a = null a = -> 1 ''' ''' a = null -> a = 1 ''' ''' if x a = 1 else a = 2 ''' # , # code: ''' # if x # a = 1 # else # a = 2 # ''' # options: [allowSameScope: no] ''' a = 1 a = 2 unless b ''' ''' a = 1 -> a++ ''' ''' a = 1 a++ ''' 'class a' ''' a = class a ''' ''' a = null a = null ''' ''' a = 1 foo = (a) -> ''' ''' (a) -> (a) -> ''' ''' a = 1 do (a) -> ''' ''' a = (a) -> ''' ''' x = 1 for x in y ; ''' ''' x = null -> for x in y ; ''' ''' a = null -> for b, a of c ; ''' ''' a = 1 -> a ###:###= 2 ''' , code: ''' a = 1 a ###:=### = 2 ''' options: [allowSameScope: no] , ''' a = 1 -> for b, ###:=### a of c ; ''' ''' a = 1 -> for ###:=### a, b in c ; ''' ''' a = -> class ###:=### a ''' ''' a = -> class a ###:=### ''' ''' a = 1 -> [a, b] ###:### = 2 ''' ''' a = 1 -> a += 2 ''' ] invalid: [ code: ''' a = 1 -> a = 2 ''' errors: [error] , code: ''' a = 1 -> [a, b] = 2 ''' errors: [error] , code: ''' a = 1 a = 2 unless b ''' errors: [error] options: [allowSameScope: no] , code: ''' a = 1 a = 2 ''' errors: [error] options: [allowSameScope: no] , code: ''' a = null a = 1 ''' errors: [error] options: [allowSameScope: no, allowNullInitializers: no] , code: ''' a = null a = -> 1 ''' errors: [error] options: [allowSameScope: no, allowNullInitializers: no] , code: ''' a = null -> a = 1 ''' errors: [error] options: [allowNullInitializers: no] , code: ''' class a constructor: -> a = null ''' errors: [error] , code: ''' a = -> a = 10 ''' errors: [error] , code: ''' a = -> a = -> ''' errors: [error] , code: ''' a = -> class a ''' errors: [error] , code: ''' do -> a = class constructor: -> class a ''' errors: [error] , code: ''' class a constructor: -> a = null ''' errors: [error] , code: ''' class a constructor: -> class a ''' errors: [error] , code: ''' a = 1 for a in b ; ''' options: [allowSameScope: no] errors: [error] , code: ''' a = null -> for a in b ; ''' options: [allowNullInitializers: no] errors: [error] , code: ''' a = 1 -> for b, a of c ; ''' errors: [error] , code: ''' a = 1 -> for i in [0..10] a = i ''' errors: [error] , code: ''' a = null -> a = 1 a = 2 ''' errors: [error] ]
true
###* # @fileoverview Tests for no-overwrite rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-overwrite' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' error = type: 'Identifier' ruleTester.run 'no-overwrite', rule, valid: [ 'a = 1' 'a = b = 2' ''' a = null a = 1 ''' ''' a = null a = -> 1 ''' ''' a = null -> a = 1 ''' ''' if x a = 1 else a = 2 ''' # , # code: ''' # if x # a = 1 # else # a = 2 # ''' # options: [allowSameScope: no] ''' a = 1 a = 2 unless b ''' ''' a = 1 -> a++ ''' ''' a = 1 a++ ''' 'class a' ''' a = class a ''' ''' a = null a = null ''' ''' a = 1 foo = (a) -> ''' ''' (a) -> (a) -> ''' ''' a = 1 do (a) -> ''' ''' a = (a) -> ''' ''' x = 1 for x in y ; ''' ''' x = null -> for x in y ; ''' ''' a = null -> for b, a of c ; ''' ''' a = 1 -> a ###:###= 2 ''' , code: ''' a = 1 a ###:=### = 2 ''' options: [allowSameScope: no] , ''' a = 1 -> for b, ###:=### a of c ; ''' ''' a = 1 -> for ###:=### a, b in c ; ''' ''' a = -> class ###:=### a ''' ''' a = -> class a ###:=### ''' ''' a = 1 -> [a, b] ###:### = 2 ''' ''' a = 1 -> a += 2 ''' ] invalid: [ code: ''' a = 1 -> a = 2 ''' errors: [error] , code: ''' a = 1 -> [a, b] = 2 ''' errors: [error] , code: ''' a = 1 a = 2 unless b ''' errors: [error] options: [allowSameScope: no] , code: ''' a = 1 a = 2 ''' errors: [error] options: [allowSameScope: no] , code: ''' a = null a = 1 ''' errors: [error] options: [allowSameScope: no, allowNullInitializers: no] , code: ''' a = null a = -> 1 ''' errors: [error] options: [allowSameScope: no, allowNullInitializers: no] , code: ''' a = null -> a = 1 ''' errors: [error] options: [allowNullInitializers: no] , code: ''' class a constructor: -> a = null ''' errors: [error] , code: ''' a = -> a = 10 ''' errors: [error] , code: ''' a = -> a = -> ''' errors: [error] , code: ''' a = -> class a ''' errors: [error] , code: ''' do -> a = class constructor: -> class a ''' errors: [error] , code: ''' class a constructor: -> a = null ''' errors: [error] , code: ''' class a constructor: -> class a ''' errors: [error] , code: ''' a = 1 for a in b ; ''' options: [allowSameScope: no] errors: [error] , code: ''' a = null -> for a in b ; ''' options: [allowNullInitializers: no] errors: [error] , code: ''' a = 1 -> for b, a of c ; ''' errors: [error] , code: ''' a = 1 -> for i in [0..10] a = i ''' errors: [error] , code: ''' a = null -> a = 1 a = 2 ''' errors: [error] ]
[ { "context": " @package\t\tBlogs\n * @category\tmodules\n * @author\t\tNazar Mokrynskyi <nazar@mokrynskyi.com>\n * @copyright\tCopyright (c", "end": 73, "score": 0.9998857975006104, "start": 57, "tag": "NAME", "value": "Nazar Mokrynskyi" }, { "context": "* @category\tmodules\n * @author\t\tNazar Mokrynskyi <nazar@mokrynskyi.com>\n * @copyright\tCopyright (c) 2011-2014, Nazar Mok", "end": 95, "score": 0.999930739402771, "start": 75, "tag": "EMAIL", "value": "nazar@mokrynskyi.com" }, { "context": "ynskyi.com>\n * @copyright\tCopyright (c) 2011-2014, Nazar Mokrynskyi\n * @license\t\tMIT License, see license.txt\n###\n$ -", "end": 152, "score": 0.9998924732208252, "start": 136, "tag": "NAME", "value": "Nazar Mokrynskyi" } ]
components/modules/Blogs/includes/js/general.coffee
nazar-pc/cherrytea.org-old
1
###* * @package Blogs * @category modules * @author Nazar Mokrynskyi <nazar@mokrynskyi.com> * @copyright Copyright (c) 2011-2014, Nazar Mokrynskyi * @license MIT License, see license.txt ### $ -> if cs.module != 'Blogs' return title = $('.cs-blogs-new-post-title') if title.length window.onbeforeunload = -> true content = $('.cs-blogs-new-post-content') $('.cs-blogs-post-preview').mousedown -> data = id : $(this).data('id') title : title.val() || title.text() sections : $('.cs-blogs-new-post-sections').val() content : content.val() || content.html() tags : $('.cs-blogs-new-post-tags').val() $.ajax url : 'api/Blogs/posts/preview' cache : false data : data type : 'post' success : (result) -> preview = $('.cs-blogs-post-preview-content'); preview.html(result); $('html, body') .stop(). animate( scrollTop : preview.offset().top 500 ) $('.cs-blogs-post-form') .parents('form') .submit -> window.onbeforeunload = null form = $(this) if !title.is('input') form.append( $('<input name="title" class="uk-hidden" />').val(title.text()) ) if !content.is('textarea') form.append( $('<textarea name="content" class="uk-hidden" />').val(content.html()) )
98950
###* * @package Blogs * @category modules * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2011-2014, <NAME> * @license MIT License, see license.txt ### $ -> if cs.module != 'Blogs' return title = $('.cs-blogs-new-post-title') if title.length window.onbeforeunload = -> true content = $('.cs-blogs-new-post-content') $('.cs-blogs-post-preview').mousedown -> data = id : $(this).data('id') title : title.val() || title.text() sections : $('.cs-blogs-new-post-sections').val() content : content.val() || content.html() tags : $('.cs-blogs-new-post-tags').val() $.ajax url : 'api/Blogs/posts/preview' cache : false data : data type : 'post' success : (result) -> preview = $('.cs-blogs-post-preview-content'); preview.html(result); $('html, body') .stop(). animate( scrollTop : preview.offset().top 500 ) $('.cs-blogs-post-form') .parents('form') .submit -> window.onbeforeunload = null form = $(this) if !title.is('input') form.append( $('<input name="title" class="uk-hidden" />').val(title.text()) ) if !content.is('textarea') form.append( $('<textarea name="content" class="uk-hidden" />').val(content.html()) )
true
###* * @package Blogs * @category modules * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * @copyright Copyright (c) 2011-2014, PI:NAME:<NAME>END_PI * @license MIT License, see license.txt ### $ -> if cs.module != 'Blogs' return title = $('.cs-blogs-new-post-title') if title.length window.onbeforeunload = -> true content = $('.cs-blogs-new-post-content') $('.cs-blogs-post-preview').mousedown -> data = id : $(this).data('id') title : title.val() || title.text() sections : $('.cs-blogs-new-post-sections').val() content : content.val() || content.html() tags : $('.cs-blogs-new-post-tags').val() $.ajax url : 'api/Blogs/posts/preview' cache : false data : data type : 'post' success : (result) -> preview = $('.cs-blogs-post-preview-content'); preview.html(result); $('html, body') .stop(). animate( scrollTop : preview.offset().top 500 ) $('.cs-blogs-post-form') .parents('form') .submit -> window.onbeforeunload = null form = $(this) if !title.is('input') form.append( $('<input name="title" class="uk-hidden" />').val(title.text()) ) if !content.is('textarea') form.append( $('<textarea name="content" class="uk-hidden" />').val(content.html()) )
[ { "context": ") ->\n if key instanceof Translation\n key[@options.language()] || key['EN']\n else\n value = @translati", "end": 3903, "score": 0.8844428062438965, "start": 3887, "tag": "EMAIL", "value": "options.language" } ]
plugins/starpeace-client/language/translation-manager.coffee
starpeace-project/starpeace-client-website
1
import _ from 'lodash' import Vue from 'vue' import FactoryDefinition from '~/plugins/starpeace-client/building/simulation/factory/factory-definition.coffee' import StorageDefinition from '~/plugins/starpeace-client/building/simulation/storage/storage-definition.coffee' import Translation from '~/plugins/starpeace-client/language/translation.coffee' import Utils from '~/plugins/starpeace-client/utils/utils.coffee' import DURATION from '~/plugins/starpeace-client/language/language-duration.json' import IDENTITY from '~/plugins/starpeace-client/language/language-identity.json' import MISC from '~/plugins/starpeace-client/language/language-misc.json' import OVERLAY from '~/plugins/starpeace-client/language/language-overlay.json' import TOOLBAR_INSPECT from '~/plugins/starpeace-client/language/language-toolbar-inspect.json' import TOOLBAR_RIBBON from '~/plugins/starpeace-client/language/language-toolbar-ribbon.json' import UI_MENU_BOOKMARKS from '~/plugins/starpeace-client/language/language-ui-menu-bookmarks.json' import UI_MENU_CHAT from '~/plugins/starpeace-client/language/language-ui-menu-chat.json' import UI_MENU_COMPANY from '~/plugins/starpeace-client/language/language-ui-menu-company.json' import UI_MENU_CONSTUCTION from '~/plugins/starpeace-client/language/language-ui-menu-construction.json' import UI_MENU_CORPORATION from '~/plugins/starpeace-client/language/language-ui-menu-corporation.json' import UI_MENU_GALAXY from '~/plugins/starpeace-client/language/language-ui-menu-galaxy.json' import UI_MENU_HELP from '~/plugins/starpeace-client/language/language-ui-menu-help.json' import UI_MENU_MAIL from '~/plugins/starpeace-client/language/language-ui-menu-mail.json' import UI_MENU_OPTIONS from '~/plugins/starpeace-client/language/language-ui-menu-options.json' import UI_MENU_POLITICS from '~/plugins/starpeace-client/language/language-ui-menu-politics.json' import UI_MENU_RANKINGS from '~/plugins/starpeace-client/language/language-ui-menu-rankings.json' import UI_MENU_RELEASE_NOTES from '~/plugins/starpeace-client/language/language-ui-menu-release-notes.json' import UI_MENU_RESEARCH from '~/plugins/starpeace-client/language/language-ui-menu-research.json' import UI_MENU_TOWN_SEARCH from '~/plugins/starpeace-client/language/language-ui-menu-town-search.json' import UI_MENU_TYCOON_DETAILS from '~/plugins/starpeace-client/language/language-ui-menu-tycoon-details.json' import UI_MENU_TYCOON_SEARCH from '~/plugins/starpeace-client/language/language-ui-menu-tycoon-search.json' import UI_PAGE_LAYOUT from '~/plugins/starpeace-client/language/language-ui-page-layout.json' import UI_WORKFLOW_LOADING from '~/plugins/starpeace-client/language/language-ui-workflow-loading.json' import UI_WORKFLOW_UNIVERSE from '~/plugins/starpeace-client/language/language-ui-workflow-universe.json' LANGUAGE_STRINGS = [ DURATION, IDENTITY, MISC, OVERLAY, TOOLBAR_INSPECT, TOOLBAR_RIBBON, UI_MENU_BOOKMARKS, UI_MENU_CHAT, UI_MENU_COMPANY, UI_MENU_CONSTUCTION, UI_MENU_CORPORATION, UI_MENU_GALAXY, UI_MENU_HELP, UI_MENU_MAIL, UI_MENU_OPTIONS, UI_MENU_POLITICS, UI_MENU_RANKINGS, UI_MENU_RELEASE_NOTES, UI_MENU_RESEARCH, UI_MENU_TOWN_SEARCH, UI_MENU_TYCOON_DETAILS, UI_MENU_TYCOON_SEARCH, UI_PAGE_LAYOUT, UI_WORKFLOW_LOADING, UI_WORKFLOW_UNIVERSE ] export default class TranslationManager constructor: (@asset_manager, @ajax_state, @options, @client_state) -> @translations_by_language_code = {} for language_values in LANGUAGE_STRINGS for text_key,languages of language_values for language_code,value of languages Vue.set(@translations_by_language_code, language_code, {}) unless @translations_by_language_code[language_code]? Vue.set(@translations_by_language_code[language_code], text_key, value) text: (key) -> if key instanceof Translation key[@options.language()] || key['EN'] else value = @translations_by_language_code[@options.language()]?[key] value = @translations_by_language_code['EN']?[key] unless value? || @options.language() == 'EN' value || key description_for_building: (building_definition) -> text_separator = @text('misc.and') simulation_definition = @client_state.core.building_library.simulation_definition_for_id(building_definition.id) if simulation_definition instanceof FactoryDefinition template_description = _.template(@text('ui.menu.construction.description.industry.label')) template_output = _.template(@text('ui.menu.construction.description.industry.output.label')) template_input = _.template(@text('ui.menu.construction.description.industry.input.label')) description_parts = [] for stage in simulation_definition.stages output_label_parts = _.map(stage.outputs, (output) => type = @client_state.core.planet_library.resource_type_for_id(output.resource_id) unit = if type? then @client_state.core.planet_library.resource_unit_for_id(type.unit_id) else null template_output({amount: output.max_velocity, resource: @text(type?.label_plural), unit: @text(unit?.label_plural), duration: @text('duration.day')}) ) description_parts.push template_description({output: Utils.join_with_oxford_comma(output_label_parts, text_separator)}) if output_label_parts.length inputs = _.map(stage.inputs, (input) => @text(@client_state.core.planet_library.resource_type_for_id(input.resource_id)?.label_plural)) description_parts.push template_input({input: Utils.join_with_oxford_comma(inputs, text_separator)}) if inputs.length return description_parts.join(' ') if simulation_definition instanceof StorageDefinition template_description = _.template(@text('ui.menu.construction.description.warehouse.label')) template_output = _.template(@text('ui.menu.construction.description.warehouse.output.label')) storage_parts = _.map(simulation_definition.storage, (storage) => type = @client_state.core.planet_library.resource_type_for_id(storage.resource_id) unit = if type? then @client_state.core.planet_library.resource_unit_for_id(type.unit_id) else null template_output({amount: storage.max, resource: @text(type?.label_plural), unit: @text(unit?.label_plural)}) ) return template_description({storage: Utils.join_with_oxford_comma(storage_parts, text_separator)}) ''
183811
import _ from 'lodash' import Vue from 'vue' import FactoryDefinition from '~/plugins/starpeace-client/building/simulation/factory/factory-definition.coffee' import StorageDefinition from '~/plugins/starpeace-client/building/simulation/storage/storage-definition.coffee' import Translation from '~/plugins/starpeace-client/language/translation.coffee' import Utils from '~/plugins/starpeace-client/utils/utils.coffee' import DURATION from '~/plugins/starpeace-client/language/language-duration.json' import IDENTITY from '~/plugins/starpeace-client/language/language-identity.json' import MISC from '~/plugins/starpeace-client/language/language-misc.json' import OVERLAY from '~/plugins/starpeace-client/language/language-overlay.json' import TOOLBAR_INSPECT from '~/plugins/starpeace-client/language/language-toolbar-inspect.json' import TOOLBAR_RIBBON from '~/plugins/starpeace-client/language/language-toolbar-ribbon.json' import UI_MENU_BOOKMARKS from '~/plugins/starpeace-client/language/language-ui-menu-bookmarks.json' import UI_MENU_CHAT from '~/plugins/starpeace-client/language/language-ui-menu-chat.json' import UI_MENU_COMPANY from '~/plugins/starpeace-client/language/language-ui-menu-company.json' import UI_MENU_CONSTUCTION from '~/plugins/starpeace-client/language/language-ui-menu-construction.json' import UI_MENU_CORPORATION from '~/plugins/starpeace-client/language/language-ui-menu-corporation.json' import UI_MENU_GALAXY from '~/plugins/starpeace-client/language/language-ui-menu-galaxy.json' import UI_MENU_HELP from '~/plugins/starpeace-client/language/language-ui-menu-help.json' import UI_MENU_MAIL from '~/plugins/starpeace-client/language/language-ui-menu-mail.json' import UI_MENU_OPTIONS from '~/plugins/starpeace-client/language/language-ui-menu-options.json' import UI_MENU_POLITICS from '~/plugins/starpeace-client/language/language-ui-menu-politics.json' import UI_MENU_RANKINGS from '~/plugins/starpeace-client/language/language-ui-menu-rankings.json' import UI_MENU_RELEASE_NOTES from '~/plugins/starpeace-client/language/language-ui-menu-release-notes.json' import UI_MENU_RESEARCH from '~/plugins/starpeace-client/language/language-ui-menu-research.json' import UI_MENU_TOWN_SEARCH from '~/plugins/starpeace-client/language/language-ui-menu-town-search.json' import UI_MENU_TYCOON_DETAILS from '~/plugins/starpeace-client/language/language-ui-menu-tycoon-details.json' import UI_MENU_TYCOON_SEARCH from '~/plugins/starpeace-client/language/language-ui-menu-tycoon-search.json' import UI_PAGE_LAYOUT from '~/plugins/starpeace-client/language/language-ui-page-layout.json' import UI_WORKFLOW_LOADING from '~/plugins/starpeace-client/language/language-ui-workflow-loading.json' import UI_WORKFLOW_UNIVERSE from '~/plugins/starpeace-client/language/language-ui-workflow-universe.json' LANGUAGE_STRINGS = [ DURATION, IDENTITY, MISC, OVERLAY, TOOLBAR_INSPECT, TOOLBAR_RIBBON, UI_MENU_BOOKMARKS, UI_MENU_CHAT, UI_MENU_COMPANY, UI_MENU_CONSTUCTION, UI_MENU_CORPORATION, UI_MENU_GALAXY, UI_MENU_HELP, UI_MENU_MAIL, UI_MENU_OPTIONS, UI_MENU_POLITICS, UI_MENU_RANKINGS, UI_MENU_RELEASE_NOTES, UI_MENU_RESEARCH, UI_MENU_TOWN_SEARCH, UI_MENU_TYCOON_DETAILS, UI_MENU_TYCOON_SEARCH, UI_PAGE_LAYOUT, UI_WORKFLOW_LOADING, UI_WORKFLOW_UNIVERSE ] export default class TranslationManager constructor: (@asset_manager, @ajax_state, @options, @client_state) -> @translations_by_language_code = {} for language_values in LANGUAGE_STRINGS for text_key,languages of language_values for language_code,value of languages Vue.set(@translations_by_language_code, language_code, {}) unless @translations_by_language_code[language_code]? Vue.set(@translations_by_language_code[language_code], text_key, value) text: (key) -> if key instanceof Translation key[@<EMAIL>()] || key['EN'] else value = @translations_by_language_code[@options.language()]?[key] value = @translations_by_language_code['EN']?[key] unless value? || @options.language() == 'EN' value || key description_for_building: (building_definition) -> text_separator = @text('misc.and') simulation_definition = @client_state.core.building_library.simulation_definition_for_id(building_definition.id) if simulation_definition instanceof FactoryDefinition template_description = _.template(@text('ui.menu.construction.description.industry.label')) template_output = _.template(@text('ui.menu.construction.description.industry.output.label')) template_input = _.template(@text('ui.menu.construction.description.industry.input.label')) description_parts = [] for stage in simulation_definition.stages output_label_parts = _.map(stage.outputs, (output) => type = @client_state.core.planet_library.resource_type_for_id(output.resource_id) unit = if type? then @client_state.core.planet_library.resource_unit_for_id(type.unit_id) else null template_output({amount: output.max_velocity, resource: @text(type?.label_plural), unit: @text(unit?.label_plural), duration: @text('duration.day')}) ) description_parts.push template_description({output: Utils.join_with_oxford_comma(output_label_parts, text_separator)}) if output_label_parts.length inputs = _.map(stage.inputs, (input) => @text(@client_state.core.planet_library.resource_type_for_id(input.resource_id)?.label_plural)) description_parts.push template_input({input: Utils.join_with_oxford_comma(inputs, text_separator)}) if inputs.length return description_parts.join(' ') if simulation_definition instanceof StorageDefinition template_description = _.template(@text('ui.menu.construction.description.warehouse.label')) template_output = _.template(@text('ui.menu.construction.description.warehouse.output.label')) storage_parts = _.map(simulation_definition.storage, (storage) => type = @client_state.core.planet_library.resource_type_for_id(storage.resource_id) unit = if type? then @client_state.core.planet_library.resource_unit_for_id(type.unit_id) else null template_output({amount: storage.max, resource: @text(type?.label_plural), unit: @text(unit?.label_plural)}) ) return template_description({storage: Utils.join_with_oxford_comma(storage_parts, text_separator)}) ''
true
import _ from 'lodash' import Vue from 'vue' import FactoryDefinition from '~/plugins/starpeace-client/building/simulation/factory/factory-definition.coffee' import StorageDefinition from '~/plugins/starpeace-client/building/simulation/storage/storage-definition.coffee' import Translation from '~/plugins/starpeace-client/language/translation.coffee' import Utils from '~/plugins/starpeace-client/utils/utils.coffee' import DURATION from '~/plugins/starpeace-client/language/language-duration.json' import IDENTITY from '~/plugins/starpeace-client/language/language-identity.json' import MISC from '~/plugins/starpeace-client/language/language-misc.json' import OVERLAY from '~/plugins/starpeace-client/language/language-overlay.json' import TOOLBAR_INSPECT from '~/plugins/starpeace-client/language/language-toolbar-inspect.json' import TOOLBAR_RIBBON from '~/plugins/starpeace-client/language/language-toolbar-ribbon.json' import UI_MENU_BOOKMARKS from '~/plugins/starpeace-client/language/language-ui-menu-bookmarks.json' import UI_MENU_CHAT from '~/plugins/starpeace-client/language/language-ui-menu-chat.json' import UI_MENU_COMPANY from '~/plugins/starpeace-client/language/language-ui-menu-company.json' import UI_MENU_CONSTUCTION from '~/plugins/starpeace-client/language/language-ui-menu-construction.json' import UI_MENU_CORPORATION from '~/plugins/starpeace-client/language/language-ui-menu-corporation.json' import UI_MENU_GALAXY from '~/plugins/starpeace-client/language/language-ui-menu-galaxy.json' import UI_MENU_HELP from '~/plugins/starpeace-client/language/language-ui-menu-help.json' import UI_MENU_MAIL from '~/plugins/starpeace-client/language/language-ui-menu-mail.json' import UI_MENU_OPTIONS from '~/plugins/starpeace-client/language/language-ui-menu-options.json' import UI_MENU_POLITICS from '~/plugins/starpeace-client/language/language-ui-menu-politics.json' import UI_MENU_RANKINGS from '~/plugins/starpeace-client/language/language-ui-menu-rankings.json' import UI_MENU_RELEASE_NOTES from '~/plugins/starpeace-client/language/language-ui-menu-release-notes.json' import UI_MENU_RESEARCH from '~/plugins/starpeace-client/language/language-ui-menu-research.json' import UI_MENU_TOWN_SEARCH from '~/plugins/starpeace-client/language/language-ui-menu-town-search.json' import UI_MENU_TYCOON_DETAILS from '~/plugins/starpeace-client/language/language-ui-menu-tycoon-details.json' import UI_MENU_TYCOON_SEARCH from '~/plugins/starpeace-client/language/language-ui-menu-tycoon-search.json' import UI_PAGE_LAYOUT from '~/plugins/starpeace-client/language/language-ui-page-layout.json' import UI_WORKFLOW_LOADING from '~/plugins/starpeace-client/language/language-ui-workflow-loading.json' import UI_WORKFLOW_UNIVERSE from '~/plugins/starpeace-client/language/language-ui-workflow-universe.json' LANGUAGE_STRINGS = [ DURATION, IDENTITY, MISC, OVERLAY, TOOLBAR_INSPECT, TOOLBAR_RIBBON, UI_MENU_BOOKMARKS, UI_MENU_CHAT, UI_MENU_COMPANY, UI_MENU_CONSTUCTION, UI_MENU_CORPORATION, UI_MENU_GALAXY, UI_MENU_HELP, UI_MENU_MAIL, UI_MENU_OPTIONS, UI_MENU_POLITICS, UI_MENU_RANKINGS, UI_MENU_RELEASE_NOTES, UI_MENU_RESEARCH, UI_MENU_TOWN_SEARCH, UI_MENU_TYCOON_DETAILS, UI_MENU_TYCOON_SEARCH, UI_PAGE_LAYOUT, UI_WORKFLOW_LOADING, UI_WORKFLOW_UNIVERSE ] export default class TranslationManager constructor: (@asset_manager, @ajax_state, @options, @client_state) -> @translations_by_language_code = {} for language_values in LANGUAGE_STRINGS for text_key,languages of language_values for language_code,value of languages Vue.set(@translations_by_language_code, language_code, {}) unless @translations_by_language_code[language_code]? Vue.set(@translations_by_language_code[language_code], text_key, value) text: (key) -> if key instanceof Translation key[@PI:EMAIL:<EMAIL>END_PI()] || key['EN'] else value = @translations_by_language_code[@options.language()]?[key] value = @translations_by_language_code['EN']?[key] unless value? || @options.language() == 'EN' value || key description_for_building: (building_definition) -> text_separator = @text('misc.and') simulation_definition = @client_state.core.building_library.simulation_definition_for_id(building_definition.id) if simulation_definition instanceof FactoryDefinition template_description = _.template(@text('ui.menu.construction.description.industry.label')) template_output = _.template(@text('ui.menu.construction.description.industry.output.label')) template_input = _.template(@text('ui.menu.construction.description.industry.input.label')) description_parts = [] for stage in simulation_definition.stages output_label_parts = _.map(stage.outputs, (output) => type = @client_state.core.planet_library.resource_type_for_id(output.resource_id) unit = if type? then @client_state.core.planet_library.resource_unit_for_id(type.unit_id) else null template_output({amount: output.max_velocity, resource: @text(type?.label_plural), unit: @text(unit?.label_plural), duration: @text('duration.day')}) ) description_parts.push template_description({output: Utils.join_with_oxford_comma(output_label_parts, text_separator)}) if output_label_parts.length inputs = _.map(stage.inputs, (input) => @text(@client_state.core.planet_library.resource_type_for_id(input.resource_id)?.label_plural)) description_parts.push template_input({input: Utils.join_with_oxford_comma(inputs, text_separator)}) if inputs.length return description_parts.join(' ') if simulation_definition instanceof StorageDefinition template_description = _.template(@text('ui.menu.construction.description.warehouse.label')) template_output = _.template(@text('ui.menu.construction.description.warehouse.output.label')) storage_parts = _.map(simulation_definition.storage, (storage) => type = @client_state.core.planet_library.resource_type_for_id(storage.resource_id) unit = if type? then @client_state.core.planet_library.resource_unit_for_id(type.unit_id) else null template_output({amount: storage.max, resource: @text(type?.label_plural), unit: @text(unit?.label_plural)}) ) return template_description({storage: Utils.join_with_oxford_comma(storage_parts, text_separator)}) ''
[ { "context": "f not @options[key]?\n\t\t\t\treturn console.error \"Maxmertkit Affix. You're trying to set unpropriate option – ", "end": 1695, "score": 0.5714216828346252, "start": 1688, "tag": "NAME", "value": "mertkit" } ]
coffee/affix.coffee
maxmert/maxmertkit
69
"use strict" _name = "affix" _instances = [] _id = 0 _lastScrollY = 0 _ticking = no _resizingTick = no MaxmertkitHelpers = window['MaxmertkitHelpers'] class Affix extends MaxmertkitHelpers _name: _name _instances: _instances started: no # =============== Public methods constructor: ( @el, @options ) -> _options = # String; type of user insteractive spy: @el.getAttribute( 'data-spy' ) or _name # Number; in px, vertical offset from the top offset: @el.getAttribute( 'data-offset' ) or 5 # Boolean; on spying on mobile devices onMobile: @el.getAttribute( 'data-on-mobile' ) or no # Events beforeactive: -> onactive: -> failactive: -> beforedeactive: -> ondeactive: -> faildeactive: -> @options = @_merge _options, @options @_setOptions @options super @el, @options # Get scroll container @scroller = @_getScrollContainer() @container = @_getContainer() @onScroll = _onScroll.bind(@) @setPosition = _setPosition.bind(@) @onResize = _onResize.bind(@) @resizing = _resizing.bind(@) @_addEventListener window, 'resize', @onResize # Set global event @reactor.registerEvent "initialize.#{_name}" @reactor.registerEvent "start.#{_name}" @reactor.registerEvent "stop.#{_name}" @reactor.dispatchEvent "initialize.#{_name}" if (not (not @options.onMobile and _getWindowSize().width < 992)) then @start() destroy: -> _deactivate.call @ @el.data["kitAffix"] = null super start: -> if not @started _beforeactivate.call @ stop: -> if @started _beforedeactivate.call @ _setOptions: ( options ) -> for key, value of options if not @options[key]? return console.error "Maxmertkit Affix. You're trying to set unpropriate option – #{key}" # switch key # when 'keyhere' # # DO something here # else @options[key] = value if typeof value is 'function' then @[key] = value refresh: -> @HEIGHT = @_outerHeight() @CONTAINER_HEIGHT = @_outerHeight(@container) # =============== # PRIVATE METHODS _onResize = -> _requestResize.call @ _requestResize = -> if not _resizingTick # If element is out there if @resizing? requestAnimationFrame(@resizing) _resizingTick = true _resizing = -> if not @options.onMobile if _getWindowSize().width < 992 @stop() _setPositionRelative.call @ else @refresh() @start() _resizingTick = false _getWindowSize = -> clientWidth = 0 clientHeight = 0 if typeof (window.innerWidth) is "number" #Non-IE clientWidth = window.innerWidth clientHeight = window.innerHeight else if document.documentElement and (document.documentElement.clientWidth or document.documentElement.clientHeight) #IE 6+ in 'standards compliant mode' clientWidth = document.documentElement.clientWidth clientHeight = document.documentElement.clientHeight else if document.body and (document.body.clientWidth or document.body.clientHeight) #IE 4 compatible clientWidth = document.body.clientWidth clientHeight = document.body.clientHeight width: clientWidth height: clientHeight _onScroll = ( event ) -> _lastScrollY = if event.target.nodeName is '#document' then (document.documentElement && document.documentElement.scrollTop) or event.target.body.scrollTop else event.target.scrollTop _requestTick.call @ _requestTick = -> if not _ticking requestAnimationFrame(@setPosition) _ticking = true _beforeactivate = -> if @beforeactive? try deferred = @beforeactive.call @el deferred .done => _activate.call @ .fail => @failactive?.call @el catch _activate.call @ else _activate.call @ _activate = -> @refresh() @_addEventListener @scroller, 'scroll', @onScroll @_addClass '_active_' @onactive?.call @el @reactor.dispatchEvent "start.#{_name}" @started = yes # Set just in case refresher setTimeout => @refresh() , 100 _beforedeactivate = -> if @beforedeactive? try deferred = @beforedeactive.call @el deferred .done => _deactivate.call @ .fail => @faildeactive?.call @el catch _deactivate.call @ else _deactivate.call @ _deactivate = -> @_removeEventListener @scroller, 'scroll', @onScroll @_removeClass '_active_' @reactor.dispatchEvent "stop.#{_name}" @ondeactive?.call @el @started = no _setPositionFixed = -> @el.style.width = @el.offsetWidth @el.style.position = 'fixed' top = @options.offset try style = @el.currentStyle or getComputedStyle(@el) if style? if style.marginTop? and style.marginTop isnt '' then top += parseInt(style.marginTop) @el.style.top = "#{@options.offset}px" @el.style.bottom = 'auto' _setPositionRelative = -> @el.style.position = 'relative' @el.style.top = 'inherit' _setPositionAbsolute = -> @el.style.position = 'absolute' @el.style.top = 'auto' @el.style.bottom = "#{@options.offset}px" @el.style.width = @el.offsetWidth _setPosition = -> containerTop = @container.offsetTop if containerTop - @options.offset <= _lastScrollY if containerTop + @CONTAINER_HEIGHT - @options.offset - @HEIGHT >= _lastScrollY if @el.style.position isnt 'fixed' _setPositionFixed.call @ else if @el.style.position isnt 'absolute' if containerTop + @CONTAINER_HEIGHT - @options.offset - @HEIGHT < _lastScrollY + @HEIGHT _setPositionAbsolute.call @ else if @el.style.position isnt 'relative' _setPositionRelative.call @ _ticking = false window['Affix'] = Affix window['mkitAffix'] = ( options ) -> result = null if not @data? then @data = {} unless @data['kitAffix'] result = new Affix @, options @data['kitAffix'] = result else if typeof options is 'object' @data['kitAffix']._setOptions options else if typeof options is "string" and options.charAt(0) isnt "_" @data['kitAffix'][options] result = @data['kitAffix'] return result if Element? then Element::affix = window['mkitAffix'] if jQuery? $.fn[_name] = (options) -> @each -> window['mkitAffix'].call( @, options )
118653
"use strict" _name = "affix" _instances = [] _id = 0 _lastScrollY = 0 _ticking = no _resizingTick = no MaxmertkitHelpers = window['MaxmertkitHelpers'] class Affix extends MaxmertkitHelpers _name: _name _instances: _instances started: no # =============== Public methods constructor: ( @el, @options ) -> _options = # String; type of user insteractive spy: @el.getAttribute( 'data-spy' ) or _name # Number; in px, vertical offset from the top offset: @el.getAttribute( 'data-offset' ) or 5 # Boolean; on spying on mobile devices onMobile: @el.getAttribute( 'data-on-mobile' ) or no # Events beforeactive: -> onactive: -> failactive: -> beforedeactive: -> ondeactive: -> faildeactive: -> @options = @_merge _options, @options @_setOptions @options super @el, @options # Get scroll container @scroller = @_getScrollContainer() @container = @_getContainer() @onScroll = _onScroll.bind(@) @setPosition = _setPosition.bind(@) @onResize = _onResize.bind(@) @resizing = _resizing.bind(@) @_addEventListener window, 'resize', @onResize # Set global event @reactor.registerEvent "initialize.#{_name}" @reactor.registerEvent "start.#{_name}" @reactor.registerEvent "stop.#{_name}" @reactor.dispatchEvent "initialize.#{_name}" if (not (not @options.onMobile and _getWindowSize().width < 992)) then @start() destroy: -> _deactivate.call @ @el.data["kitAffix"] = null super start: -> if not @started _beforeactivate.call @ stop: -> if @started _beforedeactivate.call @ _setOptions: ( options ) -> for key, value of options if not @options[key]? return console.error "Max<NAME> Affix. You're trying to set unpropriate option – #{key}" # switch key # when 'keyhere' # # DO something here # else @options[key] = value if typeof value is 'function' then @[key] = value refresh: -> @HEIGHT = @_outerHeight() @CONTAINER_HEIGHT = @_outerHeight(@container) # =============== # PRIVATE METHODS _onResize = -> _requestResize.call @ _requestResize = -> if not _resizingTick # If element is out there if @resizing? requestAnimationFrame(@resizing) _resizingTick = true _resizing = -> if not @options.onMobile if _getWindowSize().width < 992 @stop() _setPositionRelative.call @ else @refresh() @start() _resizingTick = false _getWindowSize = -> clientWidth = 0 clientHeight = 0 if typeof (window.innerWidth) is "number" #Non-IE clientWidth = window.innerWidth clientHeight = window.innerHeight else if document.documentElement and (document.documentElement.clientWidth or document.documentElement.clientHeight) #IE 6+ in 'standards compliant mode' clientWidth = document.documentElement.clientWidth clientHeight = document.documentElement.clientHeight else if document.body and (document.body.clientWidth or document.body.clientHeight) #IE 4 compatible clientWidth = document.body.clientWidth clientHeight = document.body.clientHeight width: clientWidth height: clientHeight _onScroll = ( event ) -> _lastScrollY = if event.target.nodeName is '#document' then (document.documentElement && document.documentElement.scrollTop) or event.target.body.scrollTop else event.target.scrollTop _requestTick.call @ _requestTick = -> if not _ticking requestAnimationFrame(@setPosition) _ticking = true _beforeactivate = -> if @beforeactive? try deferred = @beforeactive.call @el deferred .done => _activate.call @ .fail => @failactive?.call @el catch _activate.call @ else _activate.call @ _activate = -> @refresh() @_addEventListener @scroller, 'scroll', @onScroll @_addClass '_active_' @onactive?.call @el @reactor.dispatchEvent "start.#{_name}" @started = yes # Set just in case refresher setTimeout => @refresh() , 100 _beforedeactivate = -> if @beforedeactive? try deferred = @beforedeactive.call @el deferred .done => _deactivate.call @ .fail => @faildeactive?.call @el catch _deactivate.call @ else _deactivate.call @ _deactivate = -> @_removeEventListener @scroller, 'scroll', @onScroll @_removeClass '_active_' @reactor.dispatchEvent "stop.#{_name}" @ondeactive?.call @el @started = no _setPositionFixed = -> @el.style.width = @el.offsetWidth @el.style.position = 'fixed' top = @options.offset try style = @el.currentStyle or getComputedStyle(@el) if style? if style.marginTop? and style.marginTop isnt '' then top += parseInt(style.marginTop) @el.style.top = "#{@options.offset}px" @el.style.bottom = 'auto' _setPositionRelative = -> @el.style.position = 'relative' @el.style.top = 'inherit' _setPositionAbsolute = -> @el.style.position = 'absolute' @el.style.top = 'auto' @el.style.bottom = "#{@options.offset}px" @el.style.width = @el.offsetWidth _setPosition = -> containerTop = @container.offsetTop if containerTop - @options.offset <= _lastScrollY if containerTop + @CONTAINER_HEIGHT - @options.offset - @HEIGHT >= _lastScrollY if @el.style.position isnt 'fixed' _setPositionFixed.call @ else if @el.style.position isnt 'absolute' if containerTop + @CONTAINER_HEIGHT - @options.offset - @HEIGHT < _lastScrollY + @HEIGHT _setPositionAbsolute.call @ else if @el.style.position isnt 'relative' _setPositionRelative.call @ _ticking = false window['Affix'] = Affix window['mkitAffix'] = ( options ) -> result = null if not @data? then @data = {} unless @data['kitAffix'] result = new Affix @, options @data['kitAffix'] = result else if typeof options is 'object' @data['kitAffix']._setOptions options else if typeof options is "string" and options.charAt(0) isnt "_" @data['kitAffix'][options] result = @data['kitAffix'] return result if Element? then Element::affix = window['mkitAffix'] if jQuery? $.fn[_name] = (options) -> @each -> window['mkitAffix'].call( @, options )
true
"use strict" _name = "affix" _instances = [] _id = 0 _lastScrollY = 0 _ticking = no _resizingTick = no MaxmertkitHelpers = window['MaxmertkitHelpers'] class Affix extends MaxmertkitHelpers _name: _name _instances: _instances started: no # =============== Public methods constructor: ( @el, @options ) -> _options = # String; type of user insteractive spy: @el.getAttribute( 'data-spy' ) or _name # Number; in px, vertical offset from the top offset: @el.getAttribute( 'data-offset' ) or 5 # Boolean; on spying on mobile devices onMobile: @el.getAttribute( 'data-on-mobile' ) or no # Events beforeactive: -> onactive: -> failactive: -> beforedeactive: -> ondeactive: -> faildeactive: -> @options = @_merge _options, @options @_setOptions @options super @el, @options # Get scroll container @scroller = @_getScrollContainer() @container = @_getContainer() @onScroll = _onScroll.bind(@) @setPosition = _setPosition.bind(@) @onResize = _onResize.bind(@) @resizing = _resizing.bind(@) @_addEventListener window, 'resize', @onResize # Set global event @reactor.registerEvent "initialize.#{_name}" @reactor.registerEvent "start.#{_name}" @reactor.registerEvent "stop.#{_name}" @reactor.dispatchEvent "initialize.#{_name}" if (not (not @options.onMobile and _getWindowSize().width < 992)) then @start() destroy: -> _deactivate.call @ @el.data["kitAffix"] = null super start: -> if not @started _beforeactivate.call @ stop: -> if @started _beforedeactivate.call @ _setOptions: ( options ) -> for key, value of options if not @options[key]? return console.error "MaxPI:NAME:<NAME>END_PI Affix. You're trying to set unpropriate option – #{key}" # switch key # when 'keyhere' # # DO something here # else @options[key] = value if typeof value is 'function' then @[key] = value refresh: -> @HEIGHT = @_outerHeight() @CONTAINER_HEIGHT = @_outerHeight(@container) # =============== # PRIVATE METHODS _onResize = -> _requestResize.call @ _requestResize = -> if not _resizingTick # If element is out there if @resizing? requestAnimationFrame(@resizing) _resizingTick = true _resizing = -> if not @options.onMobile if _getWindowSize().width < 992 @stop() _setPositionRelative.call @ else @refresh() @start() _resizingTick = false _getWindowSize = -> clientWidth = 0 clientHeight = 0 if typeof (window.innerWidth) is "number" #Non-IE clientWidth = window.innerWidth clientHeight = window.innerHeight else if document.documentElement and (document.documentElement.clientWidth or document.documentElement.clientHeight) #IE 6+ in 'standards compliant mode' clientWidth = document.documentElement.clientWidth clientHeight = document.documentElement.clientHeight else if document.body and (document.body.clientWidth or document.body.clientHeight) #IE 4 compatible clientWidth = document.body.clientWidth clientHeight = document.body.clientHeight width: clientWidth height: clientHeight _onScroll = ( event ) -> _lastScrollY = if event.target.nodeName is '#document' then (document.documentElement && document.documentElement.scrollTop) or event.target.body.scrollTop else event.target.scrollTop _requestTick.call @ _requestTick = -> if not _ticking requestAnimationFrame(@setPosition) _ticking = true _beforeactivate = -> if @beforeactive? try deferred = @beforeactive.call @el deferred .done => _activate.call @ .fail => @failactive?.call @el catch _activate.call @ else _activate.call @ _activate = -> @refresh() @_addEventListener @scroller, 'scroll', @onScroll @_addClass '_active_' @onactive?.call @el @reactor.dispatchEvent "start.#{_name}" @started = yes # Set just in case refresher setTimeout => @refresh() , 100 _beforedeactivate = -> if @beforedeactive? try deferred = @beforedeactive.call @el deferred .done => _deactivate.call @ .fail => @faildeactive?.call @el catch _deactivate.call @ else _deactivate.call @ _deactivate = -> @_removeEventListener @scroller, 'scroll', @onScroll @_removeClass '_active_' @reactor.dispatchEvent "stop.#{_name}" @ondeactive?.call @el @started = no _setPositionFixed = -> @el.style.width = @el.offsetWidth @el.style.position = 'fixed' top = @options.offset try style = @el.currentStyle or getComputedStyle(@el) if style? if style.marginTop? and style.marginTop isnt '' then top += parseInt(style.marginTop) @el.style.top = "#{@options.offset}px" @el.style.bottom = 'auto' _setPositionRelative = -> @el.style.position = 'relative' @el.style.top = 'inherit' _setPositionAbsolute = -> @el.style.position = 'absolute' @el.style.top = 'auto' @el.style.bottom = "#{@options.offset}px" @el.style.width = @el.offsetWidth _setPosition = -> containerTop = @container.offsetTop if containerTop - @options.offset <= _lastScrollY if containerTop + @CONTAINER_HEIGHT - @options.offset - @HEIGHT >= _lastScrollY if @el.style.position isnt 'fixed' _setPositionFixed.call @ else if @el.style.position isnt 'absolute' if containerTop + @CONTAINER_HEIGHT - @options.offset - @HEIGHT < _lastScrollY + @HEIGHT _setPositionAbsolute.call @ else if @el.style.position isnt 'relative' _setPositionRelative.call @ _ticking = false window['Affix'] = Affix window['mkitAffix'] = ( options ) -> result = null if not @data? then @data = {} unless @data['kitAffix'] result = new Affix @, options @data['kitAffix'] = result else if typeof options is 'object' @data['kitAffix']._setOptions options else if typeof options is "string" and options.charAt(0) isnt "_" @data['kitAffix'][options] result = @data['kitAffix'] return result if Element? then Element::affix = window['mkitAffix'] if jQuery? $.fn[_name] = (options) -> @each -> window['mkitAffix'].call( @, options )
[ { "context": "\n roles:\n type: [String]\n # TODO(aramk) Custom asynch validation doesn't work.\n # h", "end": 669, "score": 0.8684074878692627, "start": 668, "tag": "USERNAME", "value": "k" }, { "context": "lidation doesn't work.\n # https://github.com/aldeed/meteor-autoform/issues/919\n # custom: ->\n ", "end": 743, "score": 0.9996413588523865, "start": 737, "tag": "USERNAME", "value": "aldeed" }, { "context": "settings = getSettings(@template)\n password = insertDoc.password\n modifier =\n username: insertDoc.user", "end": 2205, "score": 0.998792290687561, "start": 2187, "tag": "PASSWORD", "value": "insertDoc.password" }, { "context": "f shouldChangePassword\n modifier.password = password\n settings.beforeSubmit?.call(@, modifier, op", "end": 2856, "score": 0.9969229102134705, "start": 2848, "tag": "PASSWORD", "value": "password" } ]
src/userForm.coffee
urbanetic/meteor-accounts-ui
2
formName = 'userForm' TemplateClass = Template[formName] collectionName = 'users' Meteor.startup -> getRoles = (callback) -> Meteor.subscribe 'roles', -> # Don't show "user" role as an option which is added to all users. roles = Meteor.roles.find({name: {$not: 'user'}}).map (role) -> role.name callback(roles) schema = new SimpleSchema username: type: String password: type: String optional: true 'profile.name': type: String email: type: String regEx: SimpleSchema.RegEx.Email enabled: type: Boolean defaultValue: false roles: type: [String] # TODO(aramk) Custom asynch validation doesn't work. # https://github.com/aldeed/meteor-autoform/issues/919 # custom: -> # getRoles (roles) -> # unless _.contains(roles, @value) # schema.namedContext(formName).addInvalidKeys [{ # name: 'roles' # type: 'notAllowed' # value: 'Invalid role provided for user' # }] defaultValue: [] optional: true Form = Forms.defineModelForm name: formName schema: schema collection: Meteor.users collectionName: collectionName onRender: -> # Hide password field unless checkbox is checked. $passwordCheckbox = getPasswordCheckbox(@) $passwordCheckbox.on 'change', => $password = getPasswordInput(@).parent() $password.toggle(Template.checkbox.isChecked(getPasswordCheckbox(@))) $passwordCheckbox.trigger('change') $buttons = @$('.buttons .button') $roles = @$('.roles.field select') return unless $roles.length > 0 $buttons.addClass('disabled') doc = @data.doc getRoles (roles) => $buttons.removeClass('disabled') _.each roles, (name) -> $role = $('<option value="' + name + '">' + name + '</option>') $roles.append $role if doc?.roles && _.contains(doc.roles, name) then $role.prop('selected', true) $roles.trigger('change') onSubmit: (insertDoc, updateDoc, currentDoc) -> settings = getSettings(@template) password = insertDoc.password modifier = username: insertDoc.username name: insertDoc.profile.name enabled: insertDoc.enabled modifier.roles = insertDoc.roles if insertDoc.roles? options = allowUpdate: settings.allowUpdate ? currentDoc? if currentDoc modifier._id = currentDoc._id email = insertDoc.email if email && email.trim().length > 0 modifier.emails = [{address: email, verified: false}] else modifier.emails = [] shouldChangePassword = !currentDoc || Template.checkbox.isChecked(getPasswordCheckbox()) if shouldChangePassword modifier.password = password settings.beforeSubmit?.call(@, modifier, options) # Only allow updates in an update form. Meteor.call 'users/upsert', modifier, options, (err, result) => delete modifier.password if err notifyArg = undefined if settings.loggerNotify == false then notifyArg = {notify: false} Logger.error('Error creating user', err, notifyArg) @done(err, null) else modifier._id = result @done(null, modifier) return false hooks: docToForm: (doc) -> emails = doc.emails if emails && emails.length > 0 doc.email = doc.emails[0].address doc Form.helpers isAdmin: -> AccountsUtil.isAdmin() canEnable: -> AccountsUtil.isAdmin() and !isEditingAdmin() hasCheckbox: -> Template.checkbox? isEditingAdmin = (template) -> userId = getTemplate().data?.doc?._id userId? and AccountsUtil.isAdmin(userId) getPasswordInput = (template) -> getTemplate(template).$('[name="password"]') getPasswordCheckbox = (template) -> getTemplate(template).$('.change-password.checkbox') getTemplate = (template) -> Templates.getNamedInstance(formName, template) getSettings = (template) -> getTemplate(template).data?.settings || {}
210463
formName = 'userForm' TemplateClass = Template[formName] collectionName = 'users' Meteor.startup -> getRoles = (callback) -> Meteor.subscribe 'roles', -> # Don't show "user" role as an option which is added to all users. roles = Meteor.roles.find({name: {$not: 'user'}}).map (role) -> role.name callback(roles) schema = new SimpleSchema username: type: String password: type: String optional: true 'profile.name': type: String email: type: String regEx: SimpleSchema.RegEx.Email enabled: type: Boolean defaultValue: false roles: type: [String] # TODO(aramk) Custom asynch validation doesn't work. # https://github.com/aldeed/meteor-autoform/issues/919 # custom: -> # getRoles (roles) -> # unless _.contains(roles, @value) # schema.namedContext(formName).addInvalidKeys [{ # name: 'roles' # type: 'notAllowed' # value: 'Invalid role provided for user' # }] defaultValue: [] optional: true Form = Forms.defineModelForm name: formName schema: schema collection: Meteor.users collectionName: collectionName onRender: -> # Hide password field unless checkbox is checked. $passwordCheckbox = getPasswordCheckbox(@) $passwordCheckbox.on 'change', => $password = getPasswordInput(@).parent() $password.toggle(Template.checkbox.isChecked(getPasswordCheckbox(@))) $passwordCheckbox.trigger('change') $buttons = @$('.buttons .button') $roles = @$('.roles.field select') return unless $roles.length > 0 $buttons.addClass('disabled') doc = @data.doc getRoles (roles) => $buttons.removeClass('disabled') _.each roles, (name) -> $role = $('<option value="' + name + '">' + name + '</option>') $roles.append $role if doc?.roles && _.contains(doc.roles, name) then $role.prop('selected', true) $roles.trigger('change') onSubmit: (insertDoc, updateDoc, currentDoc) -> settings = getSettings(@template) password = <PASSWORD> modifier = username: insertDoc.username name: insertDoc.profile.name enabled: insertDoc.enabled modifier.roles = insertDoc.roles if insertDoc.roles? options = allowUpdate: settings.allowUpdate ? currentDoc? if currentDoc modifier._id = currentDoc._id email = insertDoc.email if email && email.trim().length > 0 modifier.emails = [{address: email, verified: false}] else modifier.emails = [] shouldChangePassword = !currentDoc || Template.checkbox.isChecked(getPasswordCheckbox()) if shouldChangePassword modifier.password = <PASSWORD> settings.beforeSubmit?.call(@, modifier, options) # Only allow updates in an update form. Meteor.call 'users/upsert', modifier, options, (err, result) => delete modifier.password if err notifyArg = undefined if settings.loggerNotify == false then notifyArg = {notify: false} Logger.error('Error creating user', err, notifyArg) @done(err, null) else modifier._id = result @done(null, modifier) return false hooks: docToForm: (doc) -> emails = doc.emails if emails && emails.length > 0 doc.email = doc.emails[0].address doc Form.helpers isAdmin: -> AccountsUtil.isAdmin() canEnable: -> AccountsUtil.isAdmin() and !isEditingAdmin() hasCheckbox: -> Template.checkbox? isEditingAdmin = (template) -> userId = getTemplate().data?.doc?._id userId? and AccountsUtil.isAdmin(userId) getPasswordInput = (template) -> getTemplate(template).$('[name="password"]') getPasswordCheckbox = (template) -> getTemplate(template).$('.change-password.checkbox') getTemplate = (template) -> Templates.getNamedInstance(formName, template) getSettings = (template) -> getTemplate(template).data?.settings || {}
true
formName = 'userForm' TemplateClass = Template[formName] collectionName = 'users' Meteor.startup -> getRoles = (callback) -> Meteor.subscribe 'roles', -> # Don't show "user" role as an option which is added to all users. roles = Meteor.roles.find({name: {$not: 'user'}}).map (role) -> role.name callback(roles) schema = new SimpleSchema username: type: String password: type: String optional: true 'profile.name': type: String email: type: String regEx: SimpleSchema.RegEx.Email enabled: type: Boolean defaultValue: false roles: type: [String] # TODO(aramk) Custom asynch validation doesn't work. # https://github.com/aldeed/meteor-autoform/issues/919 # custom: -> # getRoles (roles) -> # unless _.contains(roles, @value) # schema.namedContext(formName).addInvalidKeys [{ # name: 'roles' # type: 'notAllowed' # value: 'Invalid role provided for user' # }] defaultValue: [] optional: true Form = Forms.defineModelForm name: formName schema: schema collection: Meteor.users collectionName: collectionName onRender: -> # Hide password field unless checkbox is checked. $passwordCheckbox = getPasswordCheckbox(@) $passwordCheckbox.on 'change', => $password = getPasswordInput(@).parent() $password.toggle(Template.checkbox.isChecked(getPasswordCheckbox(@))) $passwordCheckbox.trigger('change') $buttons = @$('.buttons .button') $roles = @$('.roles.field select') return unless $roles.length > 0 $buttons.addClass('disabled') doc = @data.doc getRoles (roles) => $buttons.removeClass('disabled') _.each roles, (name) -> $role = $('<option value="' + name + '">' + name + '</option>') $roles.append $role if doc?.roles && _.contains(doc.roles, name) then $role.prop('selected', true) $roles.trigger('change') onSubmit: (insertDoc, updateDoc, currentDoc) -> settings = getSettings(@template) password = PI:PASSWORD:<PASSWORD>END_PI modifier = username: insertDoc.username name: insertDoc.profile.name enabled: insertDoc.enabled modifier.roles = insertDoc.roles if insertDoc.roles? options = allowUpdate: settings.allowUpdate ? currentDoc? if currentDoc modifier._id = currentDoc._id email = insertDoc.email if email && email.trim().length > 0 modifier.emails = [{address: email, verified: false}] else modifier.emails = [] shouldChangePassword = !currentDoc || Template.checkbox.isChecked(getPasswordCheckbox()) if shouldChangePassword modifier.password = PI:PASSWORD:<PASSWORD>END_PI settings.beforeSubmit?.call(@, modifier, options) # Only allow updates in an update form. Meteor.call 'users/upsert', modifier, options, (err, result) => delete modifier.password if err notifyArg = undefined if settings.loggerNotify == false then notifyArg = {notify: false} Logger.error('Error creating user', err, notifyArg) @done(err, null) else modifier._id = result @done(null, modifier) return false hooks: docToForm: (doc) -> emails = doc.emails if emails && emails.length > 0 doc.email = doc.emails[0].address doc Form.helpers isAdmin: -> AccountsUtil.isAdmin() canEnable: -> AccountsUtil.isAdmin() and !isEditingAdmin() hasCheckbox: -> Template.checkbox? isEditingAdmin = (template) -> userId = getTemplate().data?.doc?._id userId? and AccountsUtil.isAdmin(userId) getPasswordInput = (template) -> getTemplate(template).$('[name="password"]') getPasswordCheckbox = (template) -> getTemplate(template).$('.change-password.checkbox') getTemplate = (template) -> Templates.getNamedInstance(formName, template) getSettings = (template) -> getTemplate(template).data?.settings || {}
[ { "context": "io.com\n\nCopyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>\n\nLicensed under the Apache License, Version 2.0 ", "end": 194, "score": 0.9999232292175293, "start": 178, "tag": "EMAIL", "value": "info@chaibio.com" } ]
frontend/javascripts/app/services/auth.js.coffee
MakerButt/chaipcr
1
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <info@chaibio.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### app = window.ChaiBioTech.ngApp app.factory 'Auth', [ '$http' '$window' '$cookies' ($http, $window, $cookies) -> logout: -> $http.post('/logout').then -> $window.$.jStorage.deleteKey 'authToken' # http://stackoverflow.com/questions/2144386/javascript-delete-cookie # delete auth cookie $cookies.authentication_token = '' ] app.factory 'AuthToken', [ -> request: (config) -> access_token = $.jStorage.get('authToken', null) if !access_token re = new RegExp("authentication_token" + "=([^;]+)") value = re.exec(document.cookie) if value access_token = unescape(value[1]) if access_token and config.url.indexOf('8000') >= 0 separator = if config.url.indexOf('?') >= 0 then '&' else '?' config.url = "#{config.url}#{separator}access_token=#{access_token}" # config.headers['Content-Type'] = 'multipart/form-data' config ] app.config [ '$httpProvider' ($httpProvider) -> $httpProvider.interceptors.push('AuthToken') ]
22232
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### app = window.ChaiBioTech.ngApp app.factory 'Auth', [ '$http' '$window' '$cookies' ($http, $window, $cookies) -> logout: -> $http.post('/logout').then -> $window.$.jStorage.deleteKey 'authToken' # http://stackoverflow.com/questions/2144386/javascript-delete-cookie # delete auth cookie $cookies.authentication_token = '' ] app.factory 'AuthToken', [ -> request: (config) -> access_token = $.jStorage.get('authToken', null) if !access_token re = new RegExp("authentication_token" + "=([^;]+)") value = re.exec(document.cookie) if value access_token = unescape(value[1]) if access_token and config.url.indexOf('8000') >= 0 separator = if config.url.indexOf('?') >= 0 then '&' else '?' config.url = "#{config.url}#{separator}access_token=#{access_token}" # config.headers['Content-Type'] = 'multipart/form-data' config ] app.config [ '$httpProvider' ($httpProvider) -> $httpProvider.interceptors.push('AuthToken') ]
true
### Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments. For more information visit http://www.chaibio.com Copyright 2016 Chai Biotechnologies Inc. <PI:EMAIL:<EMAIL>END_PI> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### app = window.ChaiBioTech.ngApp app.factory 'Auth', [ '$http' '$window' '$cookies' ($http, $window, $cookies) -> logout: -> $http.post('/logout').then -> $window.$.jStorage.deleteKey 'authToken' # http://stackoverflow.com/questions/2144386/javascript-delete-cookie # delete auth cookie $cookies.authentication_token = '' ] app.factory 'AuthToken', [ -> request: (config) -> access_token = $.jStorage.get('authToken', null) if !access_token re = new RegExp("authentication_token" + "=([^;]+)") value = re.exec(document.cookie) if value access_token = unescape(value[1]) if access_token and config.url.indexOf('8000') >= 0 separator = if config.url.indexOf('?') >= 0 then '&' else '?' config.url = "#{config.url}#{separator}access_token=#{access_token}" # config.headers['Content-Type'] = 'multipart/form-data' config ] app.config [ '$httpProvider' ($httpProvider) -> $httpProvider.interceptors.push('AuthToken') ]
[ { "context": " method : 'flickr.photos.search'\n api_key : 'f19913083f594fe98f448414cbd25b84'\n sort : 'date-posted-desc'\n tags : 'la", "end": 880, "score": 0.9997479915618896, "start": 848, "tag": "KEY", "value": "f19913083f594fe98f448414cbd25b84" } ]
app/assets/javascripts/background.coffee
adwd/twitterlike
0
# JSONから50個の画像のうち一つをランダムで選び、画像、タイトル、リンクを表示する getFlickrPhotos = (data) -> dataStat = data.stat if(dataStat == 'ok') index = Math.floor( Math.random() * 50 ) item = data.photos.photo[index] itemLink = "https://www.flickr.com/photos/#{item.owner}/#{item.id}" itemTitle = item.title itemTitle = "no title" if itemTitle == "" photoPath = "https://farm#{item.farm}.static.flickr.com/#{item.server}/#{item.id}_#{item.secret}_b.jpg" $("#flickr-box").css("visibility", "visible") $("#flickr-license").html('<a href="' + itemLink + '">' + itemTitle + '</a>') $.backstretch(photoPath, {fade: 1000}) $ -> # flickrから景色の画像で、ライセンスがCC BY 2.0のもののURLを50個得る $.ajax type : 'GET' url : 'https://www.flickr.com/services/rest/' data : format : 'json' method : 'flickr.photos.search' api_key : 'f19913083f594fe98f448414cbd25b84' sort : 'date-posted-desc' tags : 'landscape' per_page : '50' license: '4' dataType : 'jsonp' jsonp : 'jsoncallback' success : (data) -> getFlickrPhotos(data)
27367
# JSONから50個の画像のうち一つをランダムで選び、画像、タイトル、リンクを表示する getFlickrPhotos = (data) -> dataStat = data.stat if(dataStat == 'ok') index = Math.floor( Math.random() * 50 ) item = data.photos.photo[index] itemLink = "https://www.flickr.com/photos/#{item.owner}/#{item.id}" itemTitle = item.title itemTitle = "no title" if itemTitle == "" photoPath = "https://farm#{item.farm}.static.flickr.com/#{item.server}/#{item.id}_#{item.secret}_b.jpg" $("#flickr-box").css("visibility", "visible") $("#flickr-license").html('<a href="' + itemLink + '">' + itemTitle + '</a>') $.backstretch(photoPath, {fade: 1000}) $ -> # flickrから景色の画像で、ライセンスがCC BY 2.0のもののURLを50個得る $.ajax type : 'GET' url : 'https://www.flickr.com/services/rest/' data : format : 'json' method : 'flickr.photos.search' api_key : '<KEY>' sort : 'date-posted-desc' tags : 'landscape' per_page : '50' license: '4' dataType : 'jsonp' jsonp : 'jsoncallback' success : (data) -> getFlickrPhotos(data)
true
# JSONから50個の画像のうち一つをランダムで選び、画像、タイトル、リンクを表示する getFlickrPhotos = (data) -> dataStat = data.stat if(dataStat == 'ok') index = Math.floor( Math.random() * 50 ) item = data.photos.photo[index] itemLink = "https://www.flickr.com/photos/#{item.owner}/#{item.id}" itemTitle = item.title itemTitle = "no title" if itemTitle == "" photoPath = "https://farm#{item.farm}.static.flickr.com/#{item.server}/#{item.id}_#{item.secret}_b.jpg" $("#flickr-box").css("visibility", "visible") $("#flickr-license").html('<a href="' + itemLink + '">' + itemTitle + '</a>') $.backstretch(photoPath, {fade: 1000}) $ -> # flickrから景色の画像で、ライセンスがCC BY 2.0のもののURLを50個得る $.ajax type : 'GET' url : 'https://www.flickr.com/services/rest/' data : format : 'json' method : 'flickr.photos.search' api_key : 'PI:KEY:<KEY>END_PI' sort : 'date-posted-desc' tags : 'landscape' per_page : '50' license: '4' dataType : 'jsonp' jsonp : 'jsoncallback' success : (data) -> getFlickrPhotos(data)
[ { "context": "# Bhav Vriksha\nd3 = require 'd3'\n$ = require 'jquery'\npace = req", "end": 14, "score": 0.9998226165771484, "start": 2, "tag": "NAME", "value": "Bhav Vriksha" } ]
bhavriksha/app.coffee
prashnts/bhavriksha
0
# Bhav Vriksha d3 = require 'd3' $ = require 'jquery' pace = require 'pace-progress' _compact = require 'lodash/compact' App = init: -> pace.start() @init_canvas() @get_sentence() $('#new').on 'click', => @annotate_sentence() annotate_sentence: -> if @stahp is yes then return emotion = $('input[name="emotion"]:checked').attr('checked', no).val() $.ajax url: "/api/treebank/#{@oid}" method: 'POST' data: annotation: @flatten_tree(@root, emotion) .done => @get_sentence() get_sentence: -> @stahp = yes $.ajax url: '/api/treebank' .done (data) => @oid = data.id @root = @parse_tree data.parse_tree @draw_tree() .always => @stahp = no parse_tree: (data) -> parse = (nodes) -> if Array.isArray(nodes) if nodes.length is 2 children: (parse(_) for _ in nodes) name: flat(nodes) else parse(nodes[0]) else name: nodes.token flat = (nodes) -> if Array.isArray nodes return (flat(node) for node in nodes).join(' ') else return nodes.token parse JSON.parse(data) flatten_tree: (data, emotion) -> parse = (nodes) -> if nodes.children? nodes_s = (parse child for child in nodes.children) else nodes_s = nodes.name sentiment = do (d = nodes.sentiment) -> if d then "s:#{d}" [_compact [nodes_s, sentiment]] parsed_tree = parse(data) if emotion? then parsed_tree.push("e:#{emotion}") JSON.stringify parsed_tree init_canvas: -> margin = top: 40 left: do (w = $('header').width()) -> if w is 350 then 350 else 40 bottom: 40 right: 40 width = $(window).width() - (margin.left) - (margin.right) height = $(window).height() - (margin.top) - (margin.bottom) @tree = d3.layout .tree().size [width, height] @diagonal = d3.svg .diagonal() .projection (d) -> [d.x, d.y] @svg = d3.select('#body') .append('svg') .attr('width', width + margin.left + margin.right) .attr('height', height + margin.top + margin.bottom) .append('g') .attr('transform', "translate(#{margin.left}, #{margin.top})") $('.toolbar').on 'mouseleave touchend', (e) -> $(@).addClass 'hidden' draw_tree: -> @svg.selectAll('*').remove() nodes = @tree.nodes(@root) links = @tree.links(nodes) $('#sentence').text @root.name @svg.selectAll('.link') .data(links) .enter() .append('path') .attr('class', 'link') .attr('d', @diagonal) node = @svg.selectAll('.node') .data(nodes) .enter() .append('g') .attr('class', (d) -> "node #{d.type}") .attr('transform', (d) -> "translate(#{d.x}, #{d.y})") {top, left} = $('#body').offset() right = do (d = $('header').width()) -> if d is 350 then 260 else 0 node .append 'circle' .attr 'r', 10 .attr 'fill', '#FFF' .on 'mouseover', (d) -> self = @ $('.toolbar ul li').off 'click' $('.toolbar') .css 'top', d.y + top .css 'left', d.x + left + right .removeClass 'hidden' $('.toolbar .phrase').text d.name $('.toolbar ul li').on 'click', (e) -> el = $(@) d.sentiment = el.attr('role') $(self).attr 'fill', el.css('background-color') update_labels() update_labels = -> node .selectAll 'text.sentiment' .text (d) -> d.sentiment node .append 'text' .attr 'y', 4 .attr 'text-anchor', 'middle' .attr 'class', 'sentiment' .text (d) -> d.sentiment node .append 'text' .attr 'y', 25 .attr 'text-anchor', 'middle' .text (d) -> unless d.children then d.name update_labels() module.exports = App
224339
# <NAME> d3 = require 'd3' $ = require 'jquery' pace = require 'pace-progress' _compact = require 'lodash/compact' App = init: -> pace.start() @init_canvas() @get_sentence() $('#new').on 'click', => @annotate_sentence() annotate_sentence: -> if @stahp is yes then return emotion = $('input[name="emotion"]:checked').attr('checked', no).val() $.ajax url: "/api/treebank/#{@oid}" method: 'POST' data: annotation: @flatten_tree(@root, emotion) .done => @get_sentence() get_sentence: -> @stahp = yes $.ajax url: '/api/treebank' .done (data) => @oid = data.id @root = @parse_tree data.parse_tree @draw_tree() .always => @stahp = no parse_tree: (data) -> parse = (nodes) -> if Array.isArray(nodes) if nodes.length is 2 children: (parse(_) for _ in nodes) name: flat(nodes) else parse(nodes[0]) else name: nodes.token flat = (nodes) -> if Array.isArray nodes return (flat(node) for node in nodes).join(' ') else return nodes.token parse JSON.parse(data) flatten_tree: (data, emotion) -> parse = (nodes) -> if nodes.children? nodes_s = (parse child for child in nodes.children) else nodes_s = nodes.name sentiment = do (d = nodes.sentiment) -> if d then "s:#{d}" [_compact [nodes_s, sentiment]] parsed_tree = parse(data) if emotion? then parsed_tree.push("e:#{emotion}") JSON.stringify parsed_tree init_canvas: -> margin = top: 40 left: do (w = $('header').width()) -> if w is 350 then 350 else 40 bottom: 40 right: 40 width = $(window).width() - (margin.left) - (margin.right) height = $(window).height() - (margin.top) - (margin.bottom) @tree = d3.layout .tree().size [width, height] @diagonal = d3.svg .diagonal() .projection (d) -> [d.x, d.y] @svg = d3.select('#body') .append('svg') .attr('width', width + margin.left + margin.right) .attr('height', height + margin.top + margin.bottom) .append('g') .attr('transform', "translate(#{margin.left}, #{margin.top})") $('.toolbar').on 'mouseleave touchend', (e) -> $(@).addClass 'hidden' draw_tree: -> @svg.selectAll('*').remove() nodes = @tree.nodes(@root) links = @tree.links(nodes) $('#sentence').text @root.name @svg.selectAll('.link') .data(links) .enter() .append('path') .attr('class', 'link') .attr('d', @diagonal) node = @svg.selectAll('.node') .data(nodes) .enter() .append('g') .attr('class', (d) -> "node #{d.type}") .attr('transform', (d) -> "translate(#{d.x}, #{d.y})") {top, left} = $('#body').offset() right = do (d = $('header').width()) -> if d is 350 then 260 else 0 node .append 'circle' .attr 'r', 10 .attr 'fill', '#FFF' .on 'mouseover', (d) -> self = @ $('.toolbar ul li').off 'click' $('.toolbar') .css 'top', d.y + top .css 'left', d.x + left + right .removeClass 'hidden' $('.toolbar .phrase').text d.name $('.toolbar ul li').on 'click', (e) -> el = $(@) d.sentiment = el.attr('role') $(self).attr 'fill', el.css('background-color') update_labels() update_labels = -> node .selectAll 'text.sentiment' .text (d) -> d.sentiment node .append 'text' .attr 'y', 4 .attr 'text-anchor', 'middle' .attr 'class', 'sentiment' .text (d) -> d.sentiment node .append 'text' .attr 'y', 25 .attr 'text-anchor', 'middle' .text (d) -> unless d.children then d.name update_labels() module.exports = App
true
# PI:NAME:<NAME>END_PI d3 = require 'd3' $ = require 'jquery' pace = require 'pace-progress' _compact = require 'lodash/compact' App = init: -> pace.start() @init_canvas() @get_sentence() $('#new').on 'click', => @annotate_sentence() annotate_sentence: -> if @stahp is yes then return emotion = $('input[name="emotion"]:checked').attr('checked', no).val() $.ajax url: "/api/treebank/#{@oid}" method: 'POST' data: annotation: @flatten_tree(@root, emotion) .done => @get_sentence() get_sentence: -> @stahp = yes $.ajax url: '/api/treebank' .done (data) => @oid = data.id @root = @parse_tree data.parse_tree @draw_tree() .always => @stahp = no parse_tree: (data) -> parse = (nodes) -> if Array.isArray(nodes) if nodes.length is 2 children: (parse(_) for _ in nodes) name: flat(nodes) else parse(nodes[0]) else name: nodes.token flat = (nodes) -> if Array.isArray nodes return (flat(node) for node in nodes).join(' ') else return nodes.token parse JSON.parse(data) flatten_tree: (data, emotion) -> parse = (nodes) -> if nodes.children? nodes_s = (parse child for child in nodes.children) else nodes_s = nodes.name sentiment = do (d = nodes.sentiment) -> if d then "s:#{d}" [_compact [nodes_s, sentiment]] parsed_tree = parse(data) if emotion? then parsed_tree.push("e:#{emotion}") JSON.stringify parsed_tree init_canvas: -> margin = top: 40 left: do (w = $('header').width()) -> if w is 350 then 350 else 40 bottom: 40 right: 40 width = $(window).width() - (margin.left) - (margin.right) height = $(window).height() - (margin.top) - (margin.bottom) @tree = d3.layout .tree().size [width, height] @diagonal = d3.svg .diagonal() .projection (d) -> [d.x, d.y] @svg = d3.select('#body') .append('svg') .attr('width', width + margin.left + margin.right) .attr('height', height + margin.top + margin.bottom) .append('g') .attr('transform', "translate(#{margin.left}, #{margin.top})") $('.toolbar').on 'mouseleave touchend', (e) -> $(@).addClass 'hidden' draw_tree: -> @svg.selectAll('*').remove() nodes = @tree.nodes(@root) links = @tree.links(nodes) $('#sentence').text @root.name @svg.selectAll('.link') .data(links) .enter() .append('path') .attr('class', 'link') .attr('d', @diagonal) node = @svg.selectAll('.node') .data(nodes) .enter() .append('g') .attr('class', (d) -> "node #{d.type}") .attr('transform', (d) -> "translate(#{d.x}, #{d.y})") {top, left} = $('#body').offset() right = do (d = $('header').width()) -> if d is 350 then 260 else 0 node .append 'circle' .attr 'r', 10 .attr 'fill', '#FFF' .on 'mouseover', (d) -> self = @ $('.toolbar ul li').off 'click' $('.toolbar') .css 'top', d.y + top .css 'left', d.x + left + right .removeClass 'hidden' $('.toolbar .phrase').text d.name $('.toolbar ul li').on 'click', (e) -> el = $(@) d.sentiment = el.attr('role') $(self).attr 'fill', el.css('background-color') update_labels() update_labels = -> node .selectAll 'text.sentiment' .text (d) -> d.sentiment node .append 'text' .attr 'y', 4 .attr 'text-anchor', 'middle' .attr 'class', 'sentiment' .text (d) -> d.sentiment node .append 'text' .attr 'y', 25 .attr 'text-anchor', 'middle' .text (d) -> unless d.children then d.name update_labels() module.exports = App
[ { "context": " <div className=\"footer-text_22\">{\"©2018 Pagedraw\"}</div>\n </div>\n </", "end": 4842, "score": 0.9257957339286804, "start": 4834, "tag": "NAME", "value": "Pagedraw" } ]
src/pagedraw/footer.cjsx
caffed/pagedraw
3,213
# Generated by https://pagedraw.io/pages/1470 React = require 'react' createReactClass = require 'create-react-class' module.exports = Footer = createReactClass { displayName: 'Footer' render: -> <div className="footer-footer-0"> <style dangerouslySetInnerHTML={__html: """ @import url('https://fonts.googleapis.com/css?family=Lato:'); .footer-footer-0 { display: flex; flex-direction: column; flex-grow: 1; padding-top: 33px; padding-bottom: 17px; } .footer-0 { display: flex; flex-shrink: 0; padding-right: 2px; } .footer-hr-9 { width: 1118px; height: 1px; flex-shrink: 0; background: #E4E4E4; } .footer-1 { display: flex; flex-shrink: 0; margin-top: 12px; padding-left: 871px; padding-right: 6px; } .footer-1-0 { display: flex; flex-direction: column; padding-top: 29px; padding-bottom: 7px; } .footer-1-0-0 { display: flex; flex-shrink: 0; } .footer-text_2 { flex-shrink: 0; font-family: "Lato", sans-serif; color: rgba(16, 16, 16, 0.87); font-size: 12px; line-height: normal; letter-spacing: 0px; font-weight: normal; font-style: normal; text-decoration: none; text-align: right; word-wrap: break-word; padding-right: 0.171875px; } .footer-1-0-1 { display: flex; flex-shrink: 0; margin-top: 3px; padding-left: 115px; } .footer-text_22 { flex-shrink: 0; font-family: "Lato", sans-serif; color: rgb(37, 37, 37); font-size: 10px; line-height: normal; letter-spacing: 0px; font-weight: normal; font-style: normal; text-decoration: none; text-align: right; word-wrap: break-word; padding-right: 0.515625px; } .footer-image_4 { width: 49px; height: 66px; flex-shrink: 0; margin-left: 2px; border-width: 0px; } * { box-sizing: border-box; } body { margin: 0; } button:hover { cursor: pointer; } a { text-decoration: none; color: inherit; } .pd-onhover-parent >.pd-onhover { display: none; } .pd-onhover-parent:hover > * { display: none; } .pd-onhover-parent:hover > .pd-onhover { display: flex; } .pd-onactive-parent > .pd-onactive { display: none; } .pd-onactive-parent:active > * { display: none; } .pd-onactive-parent:active > .pd-onactive { display: flex; } .pd-onactive-parent.pd-onhover-parent:active > .pd-onhover { display: none; } """} /> <div className="footer-0"> <div className="footer-hr-9" /> </div> <div className="footer-1"> <div className="footer-1-0"> <div className="footer-1-0-0"> <div className="footer-text_2"> Making programming more powerful </div> </div> <div className="footer-1-0-1"> <div className="footer-text_22">{"©2018 Pagedraw"}</div> </div> </div> <img src="https://complex-houses.surge.sh/dcc8b8a1-72a3-4eeb-b397-cf0306fcf8fd/sit.png" className="footer-image_4" /> </div> </div> }
37875
# Generated by https://pagedraw.io/pages/1470 React = require 'react' createReactClass = require 'create-react-class' module.exports = Footer = createReactClass { displayName: 'Footer' render: -> <div className="footer-footer-0"> <style dangerouslySetInnerHTML={__html: """ @import url('https://fonts.googleapis.com/css?family=Lato:'); .footer-footer-0 { display: flex; flex-direction: column; flex-grow: 1; padding-top: 33px; padding-bottom: 17px; } .footer-0 { display: flex; flex-shrink: 0; padding-right: 2px; } .footer-hr-9 { width: 1118px; height: 1px; flex-shrink: 0; background: #E4E4E4; } .footer-1 { display: flex; flex-shrink: 0; margin-top: 12px; padding-left: 871px; padding-right: 6px; } .footer-1-0 { display: flex; flex-direction: column; padding-top: 29px; padding-bottom: 7px; } .footer-1-0-0 { display: flex; flex-shrink: 0; } .footer-text_2 { flex-shrink: 0; font-family: "Lato", sans-serif; color: rgba(16, 16, 16, 0.87); font-size: 12px; line-height: normal; letter-spacing: 0px; font-weight: normal; font-style: normal; text-decoration: none; text-align: right; word-wrap: break-word; padding-right: 0.171875px; } .footer-1-0-1 { display: flex; flex-shrink: 0; margin-top: 3px; padding-left: 115px; } .footer-text_22 { flex-shrink: 0; font-family: "Lato", sans-serif; color: rgb(37, 37, 37); font-size: 10px; line-height: normal; letter-spacing: 0px; font-weight: normal; font-style: normal; text-decoration: none; text-align: right; word-wrap: break-word; padding-right: 0.515625px; } .footer-image_4 { width: 49px; height: 66px; flex-shrink: 0; margin-left: 2px; border-width: 0px; } * { box-sizing: border-box; } body { margin: 0; } button:hover { cursor: pointer; } a { text-decoration: none; color: inherit; } .pd-onhover-parent >.pd-onhover { display: none; } .pd-onhover-parent:hover > * { display: none; } .pd-onhover-parent:hover > .pd-onhover { display: flex; } .pd-onactive-parent > .pd-onactive { display: none; } .pd-onactive-parent:active > * { display: none; } .pd-onactive-parent:active > .pd-onactive { display: flex; } .pd-onactive-parent.pd-onhover-parent:active > .pd-onhover { display: none; } """} /> <div className="footer-0"> <div className="footer-hr-9" /> </div> <div className="footer-1"> <div className="footer-1-0"> <div className="footer-1-0-0"> <div className="footer-text_2"> Making programming more powerful </div> </div> <div className="footer-1-0-1"> <div className="footer-text_22">{"©2018 <NAME>"}</div> </div> </div> <img src="https://complex-houses.surge.sh/dcc8b8a1-72a3-4eeb-b397-cf0306fcf8fd/sit.png" className="footer-image_4" /> </div> </div> }
true
# Generated by https://pagedraw.io/pages/1470 React = require 'react' createReactClass = require 'create-react-class' module.exports = Footer = createReactClass { displayName: 'Footer' render: -> <div className="footer-footer-0"> <style dangerouslySetInnerHTML={__html: """ @import url('https://fonts.googleapis.com/css?family=Lato:'); .footer-footer-0 { display: flex; flex-direction: column; flex-grow: 1; padding-top: 33px; padding-bottom: 17px; } .footer-0 { display: flex; flex-shrink: 0; padding-right: 2px; } .footer-hr-9 { width: 1118px; height: 1px; flex-shrink: 0; background: #E4E4E4; } .footer-1 { display: flex; flex-shrink: 0; margin-top: 12px; padding-left: 871px; padding-right: 6px; } .footer-1-0 { display: flex; flex-direction: column; padding-top: 29px; padding-bottom: 7px; } .footer-1-0-0 { display: flex; flex-shrink: 0; } .footer-text_2 { flex-shrink: 0; font-family: "Lato", sans-serif; color: rgba(16, 16, 16, 0.87); font-size: 12px; line-height: normal; letter-spacing: 0px; font-weight: normal; font-style: normal; text-decoration: none; text-align: right; word-wrap: break-word; padding-right: 0.171875px; } .footer-1-0-1 { display: flex; flex-shrink: 0; margin-top: 3px; padding-left: 115px; } .footer-text_22 { flex-shrink: 0; font-family: "Lato", sans-serif; color: rgb(37, 37, 37); font-size: 10px; line-height: normal; letter-spacing: 0px; font-weight: normal; font-style: normal; text-decoration: none; text-align: right; word-wrap: break-word; padding-right: 0.515625px; } .footer-image_4 { width: 49px; height: 66px; flex-shrink: 0; margin-left: 2px; border-width: 0px; } * { box-sizing: border-box; } body { margin: 0; } button:hover { cursor: pointer; } a { text-decoration: none; color: inherit; } .pd-onhover-parent >.pd-onhover { display: none; } .pd-onhover-parent:hover > * { display: none; } .pd-onhover-parent:hover > .pd-onhover { display: flex; } .pd-onactive-parent > .pd-onactive { display: none; } .pd-onactive-parent:active > * { display: none; } .pd-onactive-parent:active > .pd-onactive { display: flex; } .pd-onactive-parent.pd-onhover-parent:active > .pd-onhover { display: none; } """} /> <div className="footer-0"> <div className="footer-hr-9" /> </div> <div className="footer-1"> <div className="footer-1-0"> <div className="footer-1-0-0"> <div className="footer-text_2"> Making programming more powerful </div> </div> <div className="footer-1-0-1"> <div className="footer-text_22">{"©2018 PI:NAME:<NAME>END_PI"}</div> </div> </div> <img src="https://complex-houses.surge.sh/dcc8b8a1-72a3-4eeb-b397-cf0306fcf8fd/sit.png" className="footer-image_4" /> </div> </div> }
[ { "context": "\n@module joukou-api/authz\n@requires lodash\n@author Isaac Johnston <isaac.johnston@joukou.com>\n###\n\n###\n@apiDefinePe", "end": 657, "score": 0.9998738169670105, "start": 643, "tag": "NAME", "value": "Isaac Johnston" }, { "context": "pi/authz\n@requires lodash\n@author Isaac Johnston <isaac.johnston@joukou.com>\n###\n\n###\n@apiDefinePermission guest Unauthentica", "end": 684, "score": 0.9999346733093262, "start": 659, "tag": "EMAIL", "value": "isaac.johnston@joukou.com" }, { "context": "a) ->\n value = persona.getValue()\n key = agent.getKey()\n has = _.some(value.agents, (agent) ->\n ", "end": 2282, "score": 0.9574735760688782, "start": 2270, "tag": "KEY", "value": "agent.getKey" }, { "context": " ->\n value = graph.getValue()\n key = persona.getKey()\n has = _.some(value.personas, ( persona ) ", "end": 3767, "score": 0.9758613705635071, "start": 3751, "tag": "KEY", "value": "persona.getKey()" } ]
src/authz/index.coffee
joukou/joukou-api
0
"use strict" ###* Copyright 2014 Joukou Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### ### Authorization. @module joukou-api/authz @requires lodash @author Isaac Johnston <isaac.johnston@joukou.com> ### ### @apiDefinePermission guest Unauthenticated users have access. Anyone with access to the public internet may access these resources. ### ### @apiDefinePermission agent Agent access rights required. An *Agent* is authorized to act on behalf of a *Persona* (called the *Principal*). ### ### @apiDefinePermission operator Operator access rights required. An *Operator* is a person that is involved in providing the services of this Joukou platform installation. ### _ = require( 'lodash' ) Q = require( 'q' ) PersonaModel = require( '../persona/model' ) GraphModel = require( '../persona/graph/model' ) { UnauthorizedError } = require( 'restify' ) self = hasPermission: ( agent, permission ) -> throw new Error("Not implemented") getRoles: ( agent ) -> value = agent.getValue() return value.roles or [] hasRole: ( agent, role ) -> return self.getRoles( agent ).indexOf( role ) isnt -1 hasSomeRoles: ( agent, roles ) -> agentRoles = self.getRoles( agent ) return _.some( roles, ( role ) -> return agentRoles.indexOf( role ) isnt -1 ) hasPersona: ( agent, personaKey ) -> if ( not agent or not agent.getKey instanceof Function or typeof personaKey isnt 'string' ) process.nextTick( -> deferred.reject( new UnauthorizedError( 'Agent or persona key not valid' ) ) ) return deferred.promise deferred = Q.defer() PersonaModel.retrieve(personaKey) .then( (persona) -> value = persona.getValue() key = agent.getKey() has = _.some(value.agents, (agent) -> return agent.key is key ) if has deferred.resolve(persona) else deferred.reject( new UnauthorizedError( 'Persona does not have agent' ) ) ) .fail( -> deferred.reject( new UnauthorizedError( 'Failed to retrieve persona' ) ) ) return deferred.promise hasCircle: (agent, circleKey) -> deferred = Q.defer() PersonaModel.getForAgent(agent.getKey()) .then( ( personas ) -> CircleModel.retrieve(circleKey) .then( ( circle ) -> keys = _.map(personas, ( persona ) -> return persona.getKey() ) has = _.some( circle.personas, ( persona ) -> return keys.indexOf( persona.key ) isnt -1 ) if has deferred.resolve(circle) else deferred.reject( new UnauthorizedError( 'Cannot access circle' ) ) ) ) .fail( -> deferred.reject( new UnauthorizedError( 'Failed to retrieve personas' ) ) ) return deferred.promise hasGraph: (agent, graphKey, personaKey ) -> deferred = Q.defer() if typeof graphKey isnt 'string' process.nextTick( -> deferred.reject( new UnauthorizedError( 'Graph key is not a string' ) ) ) return deferred.promise self.hasPersona(agent, personaKey) .then( (persona) -> GraphModel.retrieve(graphKey) .then( (graph) -> value = graph.getValue() key = persona.getKey() has = _.some(value.personas, ( persona ) -> return persona.key is key ) if has deferred.resolve({ persona: persona graph: graph }) else deferred.reject( new UnauthorizedError( 'Graph does not have persona' ) ) ) .fail( -> deferred.reject( new UnauthorizedError( 'Failed to retrieve graph' ) ) ) ) .fail( -> deferred.reject( new UnauthorizedError( 'Cannot access persona' ) ) ) return deferred.promise module.exports = self
19702
"use strict" ###* Copyright 2014 Joukou Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### ### Authorization. @module joukou-api/authz @requires lodash @author <NAME> <<EMAIL>> ### ### @apiDefinePermission guest Unauthenticated users have access. Anyone with access to the public internet may access these resources. ### ### @apiDefinePermission agent Agent access rights required. An *Agent* is authorized to act on behalf of a *Persona* (called the *Principal*). ### ### @apiDefinePermission operator Operator access rights required. An *Operator* is a person that is involved in providing the services of this Joukou platform installation. ### _ = require( 'lodash' ) Q = require( 'q' ) PersonaModel = require( '../persona/model' ) GraphModel = require( '../persona/graph/model' ) { UnauthorizedError } = require( 'restify' ) self = hasPermission: ( agent, permission ) -> throw new Error("Not implemented") getRoles: ( agent ) -> value = agent.getValue() return value.roles or [] hasRole: ( agent, role ) -> return self.getRoles( agent ).indexOf( role ) isnt -1 hasSomeRoles: ( agent, roles ) -> agentRoles = self.getRoles( agent ) return _.some( roles, ( role ) -> return agentRoles.indexOf( role ) isnt -1 ) hasPersona: ( agent, personaKey ) -> if ( not agent or not agent.getKey instanceof Function or typeof personaKey isnt 'string' ) process.nextTick( -> deferred.reject( new UnauthorizedError( 'Agent or persona key not valid' ) ) ) return deferred.promise deferred = Q.defer() PersonaModel.retrieve(personaKey) .then( (persona) -> value = persona.getValue() key = <KEY>() has = _.some(value.agents, (agent) -> return agent.key is key ) if has deferred.resolve(persona) else deferred.reject( new UnauthorizedError( 'Persona does not have agent' ) ) ) .fail( -> deferred.reject( new UnauthorizedError( 'Failed to retrieve persona' ) ) ) return deferred.promise hasCircle: (agent, circleKey) -> deferred = Q.defer() PersonaModel.getForAgent(agent.getKey()) .then( ( personas ) -> CircleModel.retrieve(circleKey) .then( ( circle ) -> keys = _.map(personas, ( persona ) -> return persona.getKey() ) has = _.some( circle.personas, ( persona ) -> return keys.indexOf( persona.key ) isnt -1 ) if has deferred.resolve(circle) else deferred.reject( new UnauthorizedError( 'Cannot access circle' ) ) ) ) .fail( -> deferred.reject( new UnauthorizedError( 'Failed to retrieve personas' ) ) ) return deferred.promise hasGraph: (agent, graphKey, personaKey ) -> deferred = Q.defer() if typeof graphKey isnt 'string' process.nextTick( -> deferred.reject( new UnauthorizedError( 'Graph key is not a string' ) ) ) return deferred.promise self.hasPersona(agent, personaKey) .then( (persona) -> GraphModel.retrieve(graphKey) .then( (graph) -> value = graph.getValue() key = <KEY> has = _.some(value.personas, ( persona ) -> return persona.key is key ) if has deferred.resolve({ persona: persona graph: graph }) else deferred.reject( new UnauthorizedError( 'Graph does not have persona' ) ) ) .fail( -> deferred.reject( new UnauthorizedError( 'Failed to retrieve graph' ) ) ) ) .fail( -> deferred.reject( new UnauthorizedError( 'Cannot access persona' ) ) ) return deferred.promise module.exports = self
true
"use strict" ###* Copyright 2014 Joukou Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### ### Authorization. @module joukou-api/authz @requires lodash @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### ### @apiDefinePermission guest Unauthenticated users have access. Anyone with access to the public internet may access these resources. ### ### @apiDefinePermission agent Agent access rights required. An *Agent* is authorized to act on behalf of a *Persona* (called the *Principal*). ### ### @apiDefinePermission operator Operator access rights required. An *Operator* is a person that is involved in providing the services of this Joukou platform installation. ### _ = require( 'lodash' ) Q = require( 'q' ) PersonaModel = require( '../persona/model' ) GraphModel = require( '../persona/graph/model' ) { UnauthorizedError } = require( 'restify' ) self = hasPermission: ( agent, permission ) -> throw new Error("Not implemented") getRoles: ( agent ) -> value = agent.getValue() return value.roles or [] hasRole: ( agent, role ) -> return self.getRoles( agent ).indexOf( role ) isnt -1 hasSomeRoles: ( agent, roles ) -> agentRoles = self.getRoles( agent ) return _.some( roles, ( role ) -> return agentRoles.indexOf( role ) isnt -1 ) hasPersona: ( agent, personaKey ) -> if ( not agent or not agent.getKey instanceof Function or typeof personaKey isnt 'string' ) process.nextTick( -> deferred.reject( new UnauthorizedError( 'Agent or persona key not valid' ) ) ) return deferred.promise deferred = Q.defer() PersonaModel.retrieve(personaKey) .then( (persona) -> value = persona.getValue() key = PI:KEY:<KEY>END_PI() has = _.some(value.agents, (agent) -> return agent.key is key ) if has deferred.resolve(persona) else deferred.reject( new UnauthorizedError( 'Persona does not have agent' ) ) ) .fail( -> deferred.reject( new UnauthorizedError( 'Failed to retrieve persona' ) ) ) return deferred.promise hasCircle: (agent, circleKey) -> deferred = Q.defer() PersonaModel.getForAgent(agent.getKey()) .then( ( personas ) -> CircleModel.retrieve(circleKey) .then( ( circle ) -> keys = _.map(personas, ( persona ) -> return persona.getKey() ) has = _.some( circle.personas, ( persona ) -> return keys.indexOf( persona.key ) isnt -1 ) if has deferred.resolve(circle) else deferred.reject( new UnauthorizedError( 'Cannot access circle' ) ) ) ) .fail( -> deferred.reject( new UnauthorizedError( 'Failed to retrieve personas' ) ) ) return deferred.promise hasGraph: (agent, graphKey, personaKey ) -> deferred = Q.defer() if typeof graphKey isnt 'string' process.nextTick( -> deferred.reject( new UnauthorizedError( 'Graph key is not a string' ) ) ) return deferred.promise self.hasPersona(agent, personaKey) .then( (persona) -> GraphModel.retrieve(graphKey) .then( (graph) -> value = graph.getValue() key = PI:KEY:<KEY>END_PI has = _.some(value.personas, ( persona ) -> return persona.key is key ) if has deferred.resolve({ persona: persona graph: graph }) else deferred.reject( new UnauthorizedError( 'Graph does not have persona' ) ) ) .fail( -> deferred.reject( new UnauthorizedError( 'Failed to retrieve graph' ) ) ) ) .fail( -> deferred.reject( new UnauthorizedError( 'Cannot access persona' ) ) ) return deferred.promise module.exports = self
[ { "context": "# Description:\n# Gives wisdom from Jaden Smith\n#\n# Dependencies:\n# \"twit\": \"1.1.6\"\n# \"unders", "end": 48, "score": 0.701304018497467, "start": 37, "tag": "NAME", "value": "Jaden Smith" }, { "context": "one\n#\n# Commands:\n# hubot jaden me - Wisdom from Jaden Smith\n#\n# Author:\n# pcarn <https://github.com/pcarn>\n", "end": 199, "score": 0.8438124656677246, "start": 188, "tag": "NAME", "value": "Jaden Smith" }, { "context": "jaden me - Wisdom from Jaden Smith\n#\n# Author:\n# pcarn <https://github.com/pcarn>\n\n_ = require \"undersco", "end": 221, "score": 0.9996800422668457, "start": 216, "tag": "USERNAME", "value": "pcarn" }, { "context": "n Smith\n#\n# Author:\n# pcarn <https://github.com/pcarn>\n\n_ = require \"underscore\"\nTwit = require \"twit\"\n", "end": 247, "score": 0.9996641278266907, "start": 242, "tag": "USERNAME", "value": "pcarn" }, { "context": "atuses/user_timeline\",\n screen_name: escape(\"officialjaden\")\n count: 1\n include_rts: false\n e", "end": 7812, "score": 0.9782047271728516, "start": 7799, "tag": "USERNAME", "value": "officialjaden" } ]
src/jaden.coffee
pcarn/hubot-jaden
0
# Description: # Gives wisdom from Jaden Smith # # Dependencies: # "twit": "1.1.6" # "underscore": "1.4.4" # # Configuration: # None # # Commands: # hubot jaden me - Wisdom from Jaden Smith # # Author: # pcarn <https://github.com/pcarn> _ = require "underscore" Twit = require "twit" config = consumer_key: process.env.HUBOT_TWITTER_CONSUMER_KEY consumer_secret: process.env.HUBOT_TWITTER_CONSUMER_SECRET access_token: process.env.HUBOT_TWITTER_ACCESS_TOKEN access_token_secret: process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET wisdom = [ "I Hope It Doesn't Take For Me To Die For You To See What I Do For You", "I Watch Twilight Every Night", "Most Trees Are Blue", "People Use To Ask Me What Do You Wanna Be When You Get Older And I Would Say What A Stupid Question The Real Question Is What Am I Right Now", "How Can Mirrors Be Real If Our Eyes Aren't Real", "If Newborn Babies Could Speak They Would Be The Most Intelligent Beings On Planet Earth.", "I Only Apply To The Sixth Amendment", "I'm 13 This Is Ridiculous", "When I Die. Then You Will Realize", "I've Bin Drinking Distilled Water For So Long That When I Drink Normal Water It Feels Like I'm Swallowing Huge Chunks Of Aluminum.", "You Would Have To Eat 5 Apples Today To Get The Same Nutritional Value As An Apple From 1950.", "Dying Is MainStream #MONEY", "\"It's Your Birthday\" Mateo Said. I Didn't Respond. \"Are You Not Excited To Be 15\" He Asked. Reading My Book I Uttered \"I Turned 15 Long Ago\"", "I Will Always Give You The Truth I Will Never Lie To You In My music If You Cant Handle My Feelings And Emotions Please Unfollow Me", "Ill Never Forget The Blogs That Believed In Me Since The Begging.", "People Tell Me To Smile I Tell Them The Lack Of Emotion In My Face Doesn't Mean I'm Unhappy", "You Must Not Know Fashion", "If A Book Store Never Runs Out Of A Certain Book, Dose That Mean That Nobody Reads It, Or Everybody Reads It", "All The Rules In This World Were Made By Someone No Smarter Than You. So Make Your Own.", "School Is The Tool To Brainwash The Youth.", "Trees Are Never Sad Look At Them Every Once In Awhile They're Quite Beautiful", "We Need To Stop Teaching The Youth About The Past And Encourage Them To Change The Future", "There Is No Nutrients In Our Food Anymore Or In Our Soil OR IN OUR WATER", "You Think You Get It. YOU DONT YOU DONT YOU DONT!!!!!!!", "I Scare People Away", "Either I Lie To You Or We Cry Together", "If I Had A Nickel For Every Time I've Cried In The Back Of An Uber, I Would Have Another Pair Of Yeezy's.", "You Can Discover Everything You Need To Know About Everything By Looking At Your Hands", "When The First Animal Went Extinct That Should've Bin A Sign.", "If I Die In My Flannel Will You Write My Poems On Tyler's 5 Panels And Jesusus Sandals This Plane Is Just To Much To Handle.", "I Build Pyramids Constantly", "Anyone Born On This Planet Should Have A Planetary Citizenship Enabling Them To Freely Explore There Home", "I Don't Want You Guys To Think Because I Was Born In America That I Speak And Abide By English Grammar. I Speak Jaden, Indefinitely.", "You Taught Me How To Play The Piano But Have Never Heard Me.", "Don't Worry Bae I'll Talk To You About SpaceTime Over FaceTime.", "I Just Scrolled Through My Tweets And \"I\" Started Laughing.", "The Head Of The Sphinx Will Fall Off In The Near Future.", "HardWork Dedication Until There's Peace And Non Poverty In Every Nation, And I Isn't Patient. ||", "Every 7 Years Your Body Is Completely Replaced With Entirely New Cells So Just Because You Look The Same Doesn't Mean You Are.", "People Hate What They Don't Understand", "\"Hey Are You Jaden Can I Have A Picture With You\" No Cause I'm Super Sad But We Can Sit And Talk.", "Haters Are Just Pre Creators Who Need The Seed Of Greatness.", "If I Was Moses Where Would I Be", "If Everybody In The World Dropped Out Of School We Would Have A Much More Intelligent Society.", "I Should Just Stop Tweeting, The Human Consciousness Must Raise Before I Speak My Juvenile Philosophy.", "I Read \“The Ancient Secret of the Flower of Life\” And Ancient Texts. Things That Cant Be Pre-dated.", "When You Think About An Apple You Also Think About The Opposite Of An Apple", "You Never Learn Anything In School. Think About How Many Car Accidents Happen Every Day. Driver’s Ed? What’s Up? I Still Haven’t Been To Driver’s Ed Because If Everybody I Know Has Bin In An Accident, I Can’t See How Driver’s Ed Is Really Helping Them Out.", "This Cute Little Blonde Baby Just Looked At Me.", "Currently Going Through Customs Even Though I Was Born On This Planet.", "Gimme 12 months. You See What's Bin Started", "That's Art Ladies And Gentlemen", "Drake Is Tight.", "No Pain No Gain Young Kurt Cobain.", "Dear Everybody Who Can Rap Better Than Me. Please Show Me", "Dear The Internet Have Fun With That.", "Once All 100% Is Neglected You Have A Citizen. A Walking Zombie Who Criticizes Every Thing They See. Have Fun Its A Really Awesome Place.", "Hate Me Love Me Doesn't Matter I'm Still Occupying Time Inside Of Your Psyche.", "Teleport To Me.", "I Feel Like People Who Look Similar Act Similar.", "My Parents Are The Trillest People I Know", "If A Cup Cake Falls From A Tree How Far Away Will It Be From Down. #Jupiter", "To Kiss A Humming Bird...", "SPIDER MAN IS AMAZING OH MY GOD !!!!!! PLEASE GO WATCH IT", "Unawareness Is The Only Sin, And If You Were Aware You Would Know.", "People Think A RelationShip Makes You Whole, That It's Two 50%'s Coming Together To Make 100% When It Should Be Two 100%'s Making 200%", "Water In The Eyes And Alcohol In The Eyes Are Pretty Much The Same I Know This From First Hand Experience.", "Your Passion For Hating Me Is The Same Passion I Have For SacGeometry And MagLev Technology And Any Passion Is To Be Respected", "I'm Here If You Need A Fellow Insane Person To Talk To. But I'm Seriously Here Not Like One Of Those I'm Here For You's That Everybody Says.", "If Everybody Got To Meet Me In Real Life, 50% Of My Fans Would Hate Me And 50% of My Hatters Would Love Me.", "I'm Slowly Realizing I Need To Make A Trip Out To Norway", "I Don't Like To Tweet But The New Hunger Games Is Literally Amazing.", "The Current Population Of Earth Is 7,124,102,180", "I Encourage You All To Unfollow Me So I Can Be Left With The People Who Actually Appreciate Philosophy And Poetry. #CoolTapeVol2", "Why Is It Always 3 WHY IS IT ALWAYS 3!!!!!", "The Great Gatsby Is One Of The Greatest Movies Of All Time, Coachella.", "Lately People Call Me Scoop Life", "I Gave Justin His Cartier Then Went Home.", "I'm Really Lovin My Instagram Right Now", "Like I Can't Take Life Right Now", "Once You Go In You Always Come Out Alive", "Swear To God If Who Hacked My Instagram Is Who I Think Hacked My Instagram..........Good Luck", "I Cried When I Made This #StarryRoom" ] module.exports = (robot) -> twit = undefined robot.respond /jaden me/i, (msg) -> msg.send msg.random wisdom robot.respond /jaden latest/i, (msg) -> unless config.consumer_key msg.send "Please set the HUBOT_TWITTER_CONSUMER_KEY environment variable." return unless config.consumer_secret msg.send "Please set the HUBOT_TWITTER_CONSUMER_SECRET environment variable." return unless config.access_token msg.send "Please set the HUBOT_TWITTER_ACCESS_TOKEN environment variable." return unless config.access_token_secret msg.send "Please set the HUBOT_TWITTER_ACCESS_TOKEN_SECRET environment variable." return unless twit twit = new Twit config twit.get "statuses/user_timeline", screen_name: escape("officialjaden") count: 1 include_rts: false exclude_replies: true , (err, reply) -> return msg.send "Error" if err return msg.send _.unescape(_.last(reply)['text']) if reply[0]['text']
186415
# Description: # Gives wisdom from <NAME> # # Dependencies: # "twit": "1.1.6" # "underscore": "1.4.4" # # Configuration: # None # # Commands: # hubot jaden me - Wisdom from <NAME> # # Author: # pcarn <https://github.com/pcarn> _ = require "underscore" Twit = require "twit" config = consumer_key: process.env.HUBOT_TWITTER_CONSUMER_KEY consumer_secret: process.env.HUBOT_TWITTER_CONSUMER_SECRET access_token: process.env.HUBOT_TWITTER_ACCESS_TOKEN access_token_secret: process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET wisdom = [ "I Hope It Doesn't Take For Me To Die For You To See What I Do For You", "I Watch Twilight Every Night", "Most Trees Are Blue", "People Use To Ask Me What Do You Wanna Be When You Get Older And I Would Say What A Stupid Question The Real Question Is What Am I Right Now", "How Can Mirrors Be Real If Our Eyes Aren't Real", "If Newborn Babies Could Speak They Would Be The Most Intelligent Beings On Planet Earth.", "I Only Apply To The Sixth Amendment", "I'm 13 This Is Ridiculous", "When I Die. Then You Will Realize", "I've Bin Drinking Distilled Water For So Long That When I Drink Normal Water It Feels Like I'm Swallowing Huge Chunks Of Aluminum.", "You Would Have To Eat 5 Apples Today To Get The Same Nutritional Value As An Apple From 1950.", "Dying Is MainStream #MONEY", "\"It's Your Birthday\" Mateo Said. I Didn't Respond. \"Are You Not Excited To Be 15\" He Asked. Reading My Book I Uttered \"I Turned 15 Long Ago\"", "I Will Always Give You The Truth I Will Never Lie To You In My music If You Cant Handle My Feelings And Emotions Please Unfollow Me", "Ill Never Forget The Blogs That Believed In Me Since The Begging.", "People Tell Me To Smile I Tell Them The Lack Of Emotion In My Face Doesn't Mean I'm Unhappy", "You Must Not Know Fashion", "If A Book Store Never Runs Out Of A Certain Book, Dose That Mean That Nobody Reads It, Or Everybody Reads It", "All The Rules In This World Were Made By Someone No Smarter Than You. So Make Your Own.", "School Is The Tool To Brainwash The Youth.", "Trees Are Never Sad Look At Them Every Once In Awhile They're Quite Beautiful", "We Need To Stop Teaching The Youth About The Past And Encourage Them To Change The Future", "There Is No Nutrients In Our Food Anymore Or In Our Soil OR IN OUR WATER", "You Think You Get It. YOU DONT YOU DONT YOU DONT!!!!!!!", "I Scare People Away", "Either I Lie To You Or We Cry Together", "If I Had A Nickel For Every Time I've Cried In The Back Of An Uber, I Would Have Another Pair Of Yeezy's.", "You Can Discover Everything You Need To Know About Everything By Looking At Your Hands", "When The First Animal Went Extinct That Should've Bin A Sign.", "If I Die In My Flannel Will You Write My Poems On Tyler's 5 Panels And Jesusus Sandals This Plane Is Just To Much To Handle.", "I Build Pyramids Constantly", "Anyone Born On This Planet Should Have A Planetary Citizenship Enabling Them To Freely Explore There Home", "I Don't Want You Guys To Think Because I Was Born In America That I Speak And Abide By English Grammar. I Speak Jaden, Indefinitely.", "You Taught Me How To Play The Piano But Have Never Heard Me.", "Don't Worry Bae I'll Talk To You About SpaceTime Over FaceTime.", "I Just Scrolled Through My Tweets And \"I\" Started Laughing.", "The Head Of The Sphinx Will Fall Off In The Near Future.", "HardWork Dedication Until There's Peace And Non Poverty In Every Nation, And I Isn't Patient. ||", "Every 7 Years Your Body Is Completely Replaced With Entirely New Cells So Just Because You Look The Same Doesn't Mean You Are.", "People Hate What They Don't Understand", "\"Hey Are You Jaden Can I Have A Picture With You\" No Cause I'm Super Sad But We Can Sit And Talk.", "Haters Are Just Pre Creators Who Need The Seed Of Greatness.", "If I Was Moses Where Would I Be", "If Everybody In The World Dropped Out Of School We Would Have A Much More Intelligent Society.", "I Should Just Stop Tweeting, The Human Consciousness Must Raise Before I Speak My Juvenile Philosophy.", "I Read \“The Ancient Secret of the Flower of Life\” And Ancient Texts. Things That Cant Be Pre-dated.", "When You Think About An Apple You Also Think About The Opposite Of An Apple", "You Never Learn Anything In School. Think About How Many Car Accidents Happen Every Day. Driver’s Ed? What’s Up? I Still Haven’t Been To Driver’s Ed Because If Everybody I Know Has Bin In An Accident, I Can’t See How Driver’s Ed Is Really Helping Them Out.", "This Cute Little Blonde Baby Just Looked At Me.", "Currently Going Through Customs Even Though I Was Born On This Planet.", "Gimme 12 months. You See What's Bin Started", "That's Art Ladies And Gentlemen", "Drake Is Tight.", "No Pain No Gain Young Kurt Cobain.", "Dear Everybody Who Can Rap Better Than Me. Please Show Me", "Dear The Internet Have Fun With That.", "Once All 100% Is Neglected You Have A Citizen. A Walking Zombie Who Criticizes Every Thing They See. Have Fun Its A Really Awesome Place.", "Hate Me Love Me Doesn't Matter I'm Still Occupying Time Inside Of Your Psyche.", "Teleport To Me.", "I Feel Like People Who Look Similar Act Similar.", "My Parents Are The Trillest People I Know", "If A Cup Cake Falls From A Tree How Far Away Will It Be From Down. #Jupiter", "To Kiss A Humming Bird...", "SPIDER MAN IS AMAZING OH MY GOD !!!!!! PLEASE GO WATCH IT", "Unawareness Is The Only Sin, And If You Were Aware You Would Know.", "People Think A RelationShip Makes You Whole, That It's Two 50%'s Coming Together To Make 100% When It Should Be Two 100%'s Making 200%", "Water In The Eyes And Alcohol In The Eyes Are Pretty Much The Same I Know This From First Hand Experience.", "Your Passion For Hating Me Is The Same Passion I Have For SacGeometry And MagLev Technology And Any Passion Is To Be Respected", "I'm Here If You Need A Fellow Insane Person To Talk To. But I'm Seriously Here Not Like One Of Those I'm Here For You's That Everybody Says.", "If Everybody Got To Meet Me In Real Life, 50% Of My Fans Would Hate Me And 50% of My Hatters Would Love Me.", "I'm Slowly Realizing I Need To Make A Trip Out To Norway", "I Don't Like To Tweet But The New Hunger Games Is Literally Amazing.", "The Current Population Of Earth Is 7,124,102,180", "I Encourage You All To Unfollow Me So I Can Be Left With The People Who Actually Appreciate Philosophy And Poetry. #CoolTapeVol2", "Why Is It Always 3 WHY IS IT ALWAYS 3!!!!!", "The Great Gatsby Is One Of The Greatest Movies Of All Time, Coachella.", "Lately People Call Me Scoop Life", "I Gave Justin His Cartier Then Went Home.", "I'm Really Lovin My Instagram Right Now", "Like I Can't Take Life Right Now", "Once You Go In You Always Come Out Alive", "Swear To God If Who Hacked My Instagram Is Who I Think Hacked My Instagram..........Good Luck", "I Cried When I Made This #StarryRoom" ] module.exports = (robot) -> twit = undefined robot.respond /jaden me/i, (msg) -> msg.send msg.random wisdom robot.respond /jaden latest/i, (msg) -> unless config.consumer_key msg.send "Please set the HUBOT_TWITTER_CONSUMER_KEY environment variable." return unless config.consumer_secret msg.send "Please set the HUBOT_TWITTER_CONSUMER_SECRET environment variable." return unless config.access_token msg.send "Please set the HUBOT_TWITTER_ACCESS_TOKEN environment variable." return unless config.access_token_secret msg.send "Please set the HUBOT_TWITTER_ACCESS_TOKEN_SECRET environment variable." return unless twit twit = new Twit config twit.get "statuses/user_timeline", screen_name: escape("officialjaden") count: 1 include_rts: false exclude_replies: true , (err, reply) -> return msg.send "Error" if err return msg.send _.unescape(_.last(reply)['text']) if reply[0]['text']
true
# Description: # Gives wisdom from PI:NAME:<NAME>END_PI # # Dependencies: # "twit": "1.1.6" # "underscore": "1.4.4" # # Configuration: # None # # Commands: # hubot jaden me - Wisdom from PI:NAME:<NAME>END_PI # # Author: # pcarn <https://github.com/pcarn> _ = require "underscore" Twit = require "twit" config = consumer_key: process.env.HUBOT_TWITTER_CONSUMER_KEY consumer_secret: process.env.HUBOT_TWITTER_CONSUMER_SECRET access_token: process.env.HUBOT_TWITTER_ACCESS_TOKEN access_token_secret: process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET wisdom = [ "I Hope It Doesn't Take For Me To Die For You To See What I Do For You", "I Watch Twilight Every Night", "Most Trees Are Blue", "People Use To Ask Me What Do You Wanna Be When You Get Older And I Would Say What A Stupid Question The Real Question Is What Am I Right Now", "How Can Mirrors Be Real If Our Eyes Aren't Real", "If Newborn Babies Could Speak They Would Be The Most Intelligent Beings On Planet Earth.", "I Only Apply To The Sixth Amendment", "I'm 13 This Is Ridiculous", "When I Die. Then You Will Realize", "I've Bin Drinking Distilled Water For So Long That When I Drink Normal Water It Feels Like I'm Swallowing Huge Chunks Of Aluminum.", "You Would Have To Eat 5 Apples Today To Get The Same Nutritional Value As An Apple From 1950.", "Dying Is MainStream #MONEY", "\"It's Your Birthday\" Mateo Said. I Didn't Respond. \"Are You Not Excited To Be 15\" He Asked. Reading My Book I Uttered \"I Turned 15 Long Ago\"", "I Will Always Give You The Truth I Will Never Lie To You In My music If You Cant Handle My Feelings And Emotions Please Unfollow Me", "Ill Never Forget The Blogs That Believed In Me Since The Begging.", "People Tell Me To Smile I Tell Them The Lack Of Emotion In My Face Doesn't Mean I'm Unhappy", "You Must Not Know Fashion", "If A Book Store Never Runs Out Of A Certain Book, Dose That Mean That Nobody Reads It, Or Everybody Reads It", "All The Rules In This World Were Made By Someone No Smarter Than You. So Make Your Own.", "School Is The Tool To Brainwash The Youth.", "Trees Are Never Sad Look At Them Every Once In Awhile They're Quite Beautiful", "We Need To Stop Teaching The Youth About The Past And Encourage Them To Change The Future", "There Is No Nutrients In Our Food Anymore Or In Our Soil OR IN OUR WATER", "You Think You Get It. YOU DONT YOU DONT YOU DONT!!!!!!!", "I Scare People Away", "Either I Lie To You Or We Cry Together", "If I Had A Nickel For Every Time I've Cried In The Back Of An Uber, I Would Have Another Pair Of Yeezy's.", "You Can Discover Everything You Need To Know About Everything By Looking At Your Hands", "When The First Animal Went Extinct That Should've Bin A Sign.", "If I Die In My Flannel Will You Write My Poems On Tyler's 5 Panels And Jesusus Sandals This Plane Is Just To Much To Handle.", "I Build Pyramids Constantly", "Anyone Born On This Planet Should Have A Planetary Citizenship Enabling Them To Freely Explore There Home", "I Don't Want You Guys To Think Because I Was Born In America That I Speak And Abide By English Grammar. I Speak Jaden, Indefinitely.", "You Taught Me How To Play The Piano But Have Never Heard Me.", "Don't Worry Bae I'll Talk To You About SpaceTime Over FaceTime.", "I Just Scrolled Through My Tweets And \"I\" Started Laughing.", "The Head Of The Sphinx Will Fall Off In The Near Future.", "HardWork Dedication Until There's Peace And Non Poverty In Every Nation, And I Isn't Patient. ||", "Every 7 Years Your Body Is Completely Replaced With Entirely New Cells So Just Because You Look The Same Doesn't Mean You Are.", "People Hate What They Don't Understand", "\"Hey Are You Jaden Can I Have A Picture With You\" No Cause I'm Super Sad But We Can Sit And Talk.", "Haters Are Just Pre Creators Who Need The Seed Of Greatness.", "If I Was Moses Where Would I Be", "If Everybody In The World Dropped Out Of School We Would Have A Much More Intelligent Society.", "I Should Just Stop Tweeting, The Human Consciousness Must Raise Before I Speak My Juvenile Philosophy.", "I Read \“The Ancient Secret of the Flower of Life\” And Ancient Texts. Things That Cant Be Pre-dated.", "When You Think About An Apple You Also Think About The Opposite Of An Apple", "You Never Learn Anything In School. Think About How Many Car Accidents Happen Every Day. Driver’s Ed? What’s Up? I Still Haven’t Been To Driver’s Ed Because If Everybody I Know Has Bin In An Accident, I Can’t See How Driver’s Ed Is Really Helping Them Out.", "This Cute Little Blonde Baby Just Looked At Me.", "Currently Going Through Customs Even Though I Was Born On This Planet.", "Gimme 12 months. You See What's Bin Started", "That's Art Ladies And Gentlemen", "Drake Is Tight.", "No Pain No Gain Young Kurt Cobain.", "Dear Everybody Who Can Rap Better Than Me. Please Show Me", "Dear The Internet Have Fun With That.", "Once All 100% Is Neglected You Have A Citizen. A Walking Zombie Who Criticizes Every Thing They See. Have Fun Its A Really Awesome Place.", "Hate Me Love Me Doesn't Matter I'm Still Occupying Time Inside Of Your Psyche.", "Teleport To Me.", "I Feel Like People Who Look Similar Act Similar.", "My Parents Are The Trillest People I Know", "If A Cup Cake Falls From A Tree How Far Away Will It Be From Down. #Jupiter", "To Kiss A Humming Bird...", "SPIDER MAN IS AMAZING OH MY GOD !!!!!! PLEASE GO WATCH IT", "Unawareness Is The Only Sin, And If You Were Aware You Would Know.", "People Think A RelationShip Makes You Whole, That It's Two 50%'s Coming Together To Make 100% When It Should Be Two 100%'s Making 200%", "Water In The Eyes And Alcohol In The Eyes Are Pretty Much The Same I Know This From First Hand Experience.", "Your Passion For Hating Me Is The Same Passion I Have For SacGeometry And MagLev Technology And Any Passion Is To Be Respected", "I'm Here If You Need A Fellow Insane Person To Talk To. But I'm Seriously Here Not Like One Of Those I'm Here For You's That Everybody Says.", "If Everybody Got To Meet Me In Real Life, 50% Of My Fans Would Hate Me And 50% of My Hatters Would Love Me.", "I'm Slowly Realizing I Need To Make A Trip Out To Norway", "I Don't Like To Tweet But The New Hunger Games Is Literally Amazing.", "The Current Population Of Earth Is 7,124,102,180", "I Encourage You All To Unfollow Me So I Can Be Left With The People Who Actually Appreciate Philosophy And Poetry. #CoolTapeVol2", "Why Is It Always 3 WHY IS IT ALWAYS 3!!!!!", "The Great Gatsby Is One Of The Greatest Movies Of All Time, Coachella.", "Lately People Call Me Scoop Life", "I Gave Justin His Cartier Then Went Home.", "I'm Really Lovin My Instagram Right Now", "Like I Can't Take Life Right Now", "Once You Go In You Always Come Out Alive", "Swear To God If Who Hacked My Instagram Is Who I Think Hacked My Instagram..........Good Luck", "I Cried When I Made This #StarryRoom" ] module.exports = (robot) -> twit = undefined robot.respond /jaden me/i, (msg) -> msg.send msg.random wisdom robot.respond /jaden latest/i, (msg) -> unless config.consumer_key msg.send "Please set the HUBOT_TWITTER_CONSUMER_KEY environment variable." return unless config.consumer_secret msg.send "Please set the HUBOT_TWITTER_CONSUMER_SECRET environment variable." return unless config.access_token msg.send "Please set the HUBOT_TWITTER_ACCESS_TOKEN environment variable." return unless config.access_token_secret msg.send "Please set the HUBOT_TWITTER_ACCESS_TOKEN_SECRET environment variable." return unless twit twit = new Twit config twit.get "statuses/user_timeline", screen_name: escape("officialjaden") count: 1 include_rts: false exclude_replies: true , (err, reply) -> return msg.send "Error" if err return msg.send _.unescape(_.last(reply)['text']) if reply[0]['text']
[ { "context": "rs on tap from Encinitas Ale House\n#\n# Author:\n# @chrishepner\n\ncheerio = require(\"cheerio\")\n\nHUBOT_ALEHOUSE_URL", "end": 232, "score": 0.9996433854103088, "start": 220, "tag": "USERNAME", "value": "@chrishepner" }, { "context": "EHOUSE_URL = \"https://docs.google.com/document/d/1Xtc-2hL12566vrsPJRjcLrwre02w1lQJaTkbcKbwuiY/pub\"\nmodule.exports = (robot) ->\n\n robot.respond /be", "end": 369, "score": 0.8114504814147949, "start": 322, "tag": "KEY", "value": "Xtc-2hL12566vrsPJRjcLrwre02w1lQJaTkbcKbwuiY/pub" } ]
src/encinitas-ale-house.coffee
chrishepner/hubot-encinitas-ale-house
0
# Description: # Hubot script to fetch beers on tap from the Encinitas Ale House # # Dependencies: # 'cheerio': '^1.2' # # Commands: # hubot beer me - displays beers on tap from Encinitas Ale House # # Author: # @chrishepner cheerio = require("cheerio") HUBOT_ALEHOUSE_URL = "https://docs.google.com/document/d/1Xtc-2hL12566vrsPJRjcLrwre02w1lQJaTkbcKbwuiY/pub" module.exports = (robot) -> robot.respond /beer me/i, (msg) -> robot.http(HUBOT_ALEHOUSE_URL) .get() (err, res, body) -> if err msg.send("Encountered an error #{err}") return if res.statusCode isnt 200 msg.send("Request is non-HTTP 200") return $ = cheerio.load(body) $('style').remove() isHeader = false headerSeen = false outputLines = [] $('#contents > p').each (i, el) -> lineText = $(this).text().trim() if lineText == '' isHeader = true else if isHeader lineText = '*' + lineText + '*' headerSeen = true isHeader = false else lineText = ':beer: ' + lineText if headerSeen outputLines.push(lineText) msg.send(outputLines.join("\n"))
214675
# Description: # Hubot script to fetch beers on tap from the Encinitas Ale House # # Dependencies: # 'cheerio': '^1.2' # # Commands: # hubot beer me - displays beers on tap from Encinitas Ale House # # Author: # @chrishepner cheerio = require("cheerio") HUBOT_ALEHOUSE_URL = "https://docs.google.com/document/d/1<KEY>" module.exports = (robot) -> robot.respond /beer me/i, (msg) -> robot.http(HUBOT_ALEHOUSE_URL) .get() (err, res, body) -> if err msg.send("Encountered an error #{err}") return if res.statusCode isnt 200 msg.send("Request is non-HTTP 200") return $ = cheerio.load(body) $('style').remove() isHeader = false headerSeen = false outputLines = [] $('#contents > p').each (i, el) -> lineText = $(this).text().trim() if lineText == '' isHeader = true else if isHeader lineText = '*' + lineText + '*' headerSeen = true isHeader = false else lineText = ':beer: ' + lineText if headerSeen outputLines.push(lineText) msg.send(outputLines.join("\n"))
true
# Description: # Hubot script to fetch beers on tap from the Encinitas Ale House # # Dependencies: # 'cheerio': '^1.2' # # Commands: # hubot beer me - displays beers on tap from Encinitas Ale House # # Author: # @chrishepner cheerio = require("cheerio") HUBOT_ALEHOUSE_URL = "https://docs.google.com/document/d/1PI:KEY:<KEY>END_PI" module.exports = (robot) -> robot.respond /beer me/i, (msg) -> robot.http(HUBOT_ALEHOUSE_URL) .get() (err, res, body) -> if err msg.send("Encountered an error #{err}") return if res.statusCode isnt 200 msg.send("Request is non-HTTP 200") return $ = cheerio.load(body) $('style').remove() isHeader = false headerSeen = false outputLines = [] $('#contents > p').each (i, el) -> lineText = $(this).text().trim() if lineText == '' isHeader = true else if isHeader lineText = '*' + lineText + '*' headerSeen = true isHeader = false else lineText = ':beer: ' + lineText if headerSeen outputLines.push(lineText) msg.send(outputLines.join("\n"))
[ { "context": "ser =\n\t\t\t_id: @user_id = \"a_simple_id\"\n\t\t\temail: \"user@example.com\"\n\t\t\tfeatures: {}\n\t\t\tbetaProgram: false\n\t\t@req =\n\t", "end": 409, "score": 0.9999147653579712, "start": 393, "tag": "EMAIL", "value": "user@example.com" }, { "context": " false\n\t\t@req =\n\t\t\tquery: {}\n\t\t\tsession:\n\t\t\t\tuser: @user\n\t\t@BetaProgramController = SandboxedModule.re", "end": 492, "score": 0.8245125412940979, "start": 492, "tag": "USERNAME", "value": "" }, { "context": "er = {\n\t\t\t\tgetLoggedInUserId: sinon.stub().returns(@user._id)\n\t\t\t}\n\t\t@res =\n\t\t\tsend: sinon.stub()\n\t\t\tredir", "end": 1051, "score": 0.6383968591690063, "start": 1046, "tag": "USERNAME", "value": "@user" } ]
test/unit/coffee/BetaProgram/BetaProgramControllerTests.coffee
davidmehren/web-sharelatex
1
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/BetaProgram/BetaProgramController" expect = require("chai").expect describe "BetaProgramController", -> beforeEach -> @user = _id: @user_id = "a_simple_id" email: "user@example.com" features: {} betaProgram: false @req = query: {} session: user: @user @BetaProgramController = SandboxedModule.require modulePath, requires: "./BetaProgramHandler": @BetaProgramHandler = { optIn: sinon.stub() optOut: sinon.stub() }, "../User/UserGetter": @UserGetter = { getUser: sinon.stub() }, "settings-sharelatex": @settings = { languages: {} } "logger-sharelatex": @logger = { log: sinon.stub() err: sinon.stub() error: sinon.stub() } '../Authentication/AuthenticationController': @AuthenticationController = { getLoggedInUserId: sinon.stub().returns(@user._id) } @res = send: sinon.stub() redirect: sinon.stub() render: sinon.stub() @next = sinon.stub() describe "optIn", -> beforeEach -> @BetaProgramHandler.optIn.callsArgWith(1, null) it "should redirect to '/beta/participate'", () -> @BetaProgramController.optIn @req, @res, @next @res.redirect.callCount.should.equal 1 @res.redirect.firstCall.args[0].should.equal "/beta/participate" it "should not call next with an error", () -> @BetaProgramController.optIn @req, @res, @next @next.callCount.should.equal 0 it "should not call next with an error", () -> @BetaProgramController.optIn @req, @res, @next @next.callCount.should.equal 0 it "should call BetaProgramHandler.optIn", () -> @BetaProgramController.optIn @req, @res, @next @BetaProgramHandler.optIn.callCount.should.equal 1 describe "when BetaProgramHandler.opIn produces an error", -> beforeEach -> @BetaProgramHandler.optIn.callsArgWith(1, new Error('woops')) it "should not redirect to '/beta/participate'", () -> @BetaProgramController.optIn @req, @res, @next @res.redirect.callCount.should.equal 0 it "should produce an error", () -> @BetaProgramController.optIn @req, @res, @next @next.callCount.should.equal 1 @next.firstCall.args[0].should.be.instanceof Error describe "optOut", -> beforeEach -> @BetaProgramHandler.optOut.callsArgWith(1, null) it "should redirect to '/beta/participate'", () -> @BetaProgramController.optOut @req, @res, @next @res.redirect.callCount.should.equal 1 @res.redirect.firstCall.args[0].should.equal "/beta/participate" it "should not call next with an error", () -> @BetaProgramController.optOut @req, @res, @next @next.callCount.should.equal 0 it "should not call next with an error", () -> @BetaProgramController.optOut @req, @res, @next @next.callCount.should.equal 0 it "should call BetaProgramHandler.optOut", () -> @BetaProgramController.optOut @req, @res, @next @BetaProgramHandler.optOut.callCount.should.equal 1 describe "when BetaProgramHandler.optOut produces an error", -> beforeEach -> @BetaProgramHandler.optOut.callsArgWith(1, new Error('woops')) it "should not redirect to '/beta/participate'", () -> @BetaProgramController.optOut @req, @res, @next @res.redirect.callCount.should.equal 0 it "should produce an error", () -> @BetaProgramController.optOut @req, @res, @next @next.callCount.should.equal 1 @next.firstCall.args[0].should.be.instanceof Error describe "optInPage", -> beforeEach -> @UserGetter.getUser.callsArgWith(1, null, @user) it "should render the opt-in page", () -> @BetaProgramController.optInPage @req, @res, @next @res.render.callCount.should.equal 1 args = @res.render.firstCall.args args[0].should.equal 'beta_program/opt_in' describe "when UserGetter.getUser produces an error", -> beforeEach -> @UserGetter.getUser.callsArgWith(1, new Error('woops')) it "should not render the opt-in page", () -> @BetaProgramController.optInPage @req, @res, @next @res.render.callCount.should.equal 0 it "should produce an error", () -> @BetaProgramController.optInPage @req, @res, @next @next.callCount.should.equal 1 @next.firstCall.args[0].should.be.instanceof Error
218
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/BetaProgram/BetaProgramController" expect = require("chai").expect describe "BetaProgramController", -> beforeEach -> @user = _id: @user_id = "a_simple_id" email: "<EMAIL>" features: {} betaProgram: false @req = query: {} session: user: @user @BetaProgramController = SandboxedModule.require modulePath, requires: "./BetaProgramHandler": @BetaProgramHandler = { optIn: sinon.stub() optOut: sinon.stub() }, "../User/UserGetter": @UserGetter = { getUser: sinon.stub() }, "settings-sharelatex": @settings = { languages: {} } "logger-sharelatex": @logger = { log: sinon.stub() err: sinon.stub() error: sinon.stub() } '../Authentication/AuthenticationController': @AuthenticationController = { getLoggedInUserId: sinon.stub().returns(@user._id) } @res = send: sinon.stub() redirect: sinon.stub() render: sinon.stub() @next = sinon.stub() describe "optIn", -> beforeEach -> @BetaProgramHandler.optIn.callsArgWith(1, null) it "should redirect to '/beta/participate'", () -> @BetaProgramController.optIn @req, @res, @next @res.redirect.callCount.should.equal 1 @res.redirect.firstCall.args[0].should.equal "/beta/participate" it "should not call next with an error", () -> @BetaProgramController.optIn @req, @res, @next @next.callCount.should.equal 0 it "should not call next with an error", () -> @BetaProgramController.optIn @req, @res, @next @next.callCount.should.equal 0 it "should call BetaProgramHandler.optIn", () -> @BetaProgramController.optIn @req, @res, @next @BetaProgramHandler.optIn.callCount.should.equal 1 describe "when BetaProgramHandler.opIn produces an error", -> beforeEach -> @BetaProgramHandler.optIn.callsArgWith(1, new Error('woops')) it "should not redirect to '/beta/participate'", () -> @BetaProgramController.optIn @req, @res, @next @res.redirect.callCount.should.equal 0 it "should produce an error", () -> @BetaProgramController.optIn @req, @res, @next @next.callCount.should.equal 1 @next.firstCall.args[0].should.be.instanceof Error describe "optOut", -> beforeEach -> @BetaProgramHandler.optOut.callsArgWith(1, null) it "should redirect to '/beta/participate'", () -> @BetaProgramController.optOut @req, @res, @next @res.redirect.callCount.should.equal 1 @res.redirect.firstCall.args[0].should.equal "/beta/participate" it "should not call next with an error", () -> @BetaProgramController.optOut @req, @res, @next @next.callCount.should.equal 0 it "should not call next with an error", () -> @BetaProgramController.optOut @req, @res, @next @next.callCount.should.equal 0 it "should call BetaProgramHandler.optOut", () -> @BetaProgramController.optOut @req, @res, @next @BetaProgramHandler.optOut.callCount.should.equal 1 describe "when BetaProgramHandler.optOut produces an error", -> beforeEach -> @BetaProgramHandler.optOut.callsArgWith(1, new Error('woops')) it "should not redirect to '/beta/participate'", () -> @BetaProgramController.optOut @req, @res, @next @res.redirect.callCount.should.equal 0 it "should produce an error", () -> @BetaProgramController.optOut @req, @res, @next @next.callCount.should.equal 1 @next.firstCall.args[0].should.be.instanceof Error describe "optInPage", -> beforeEach -> @UserGetter.getUser.callsArgWith(1, null, @user) it "should render the opt-in page", () -> @BetaProgramController.optInPage @req, @res, @next @res.render.callCount.should.equal 1 args = @res.render.firstCall.args args[0].should.equal 'beta_program/opt_in' describe "when UserGetter.getUser produces an error", -> beforeEach -> @UserGetter.getUser.callsArgWith(1, new Error('woops')) it "should not render the opt-in page", () -> @BetaProgramController.optInPage @req, @res, @next @res.render.callCount.should.equal 0 it "should produce an error", () -> @BetaProgramController.optInPage @req, @res, @next @next.callCount.should.equal 1 @next.firstCall.args[0].should.be.instanceof Error
true
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/BetaProgram/BetaProgramController" expect = require("chai").expect describe "BetaProgramController", -> beforeEach -> @user = _id: @user_id = "a_simple_id" email: "PI:EMAIL:<EMAIL>END_PI" features: {} betaProgram: false @req = query: {} session: user: @user @BetaProgramController = SandboxedModule.require modulePath, requires: "./BetaProgramHandler": @BetaProgramHandler = { optIn: sinon.stub() optOut: sinon.stub() }, "../User/UserGetter": @UserGetter = { getUser: sinon.stub() }, "settings-sharelatex": @settings = { languages: {} } "logger-sharelatex": @logger = { log: sinon.stub() err: sinon.stub() error: sinon.stub() } '../Authentication/AuthenticationController': @AuthenticationController = { getLoggedInUserId: sinon.stub().returns(@user._id) } @res = send: sinon.stub() redirect: sinon.stub() render: sinon.stub() @next = sinon.stub() describe "optIn", -> beforeEach -> @BetaProgramHandler.optIn.callsArgWith(1, null) it "should redirect to '/beta/participate'", () -> @BetaProgramController.optIn @req, @res, @next @res.redirect.callCount.should.equal 1 @res.redirect.firstCall.args[0].should.equal "/beta/participate" it "should not call next with an error", () -> @BetaProgramController.optIn @req, @res, @next @next.callCount.should.equal 0 it "should not call next with an error", () -> @BetaProgramController.optIn @req, @res, @next @next.callCount.should.equal 0 it "should call BetaProgramHandler.optIn", () -> @BetaProgramController.optIn @req, @res, @next @BetaProgramHandler.optIn.callCount.should.equal 1 describe "when BetaProgramHandler.opIn produces an error", -> beforeEach -> @BetaProgramHandler.optIn.callsArgWith(1, new Error('woops')) it "should not redirect to '/beta/participate'", () -> @BetaProgramController.optIn @req, @res, @next @res.redirect.callCount.should.equal 0 it "should produce an error", () -> @BetaProgramController.optIn @req, @res, @next @next.callCount.should.equal 1 @next.firstCall.args[0].should.be.instanceof Error describe "optOut", -> beforeEach -> @BetaProgramHandler.optOut.callsArgWith(1, null) it "should redirect to '/beta/participate'", () -> @BetaProgramController.optOut @req, @res, @next @res.redirect.callCount.should.equal 1 @res.redirect.firstCall.args[0].should.equal "/beta/participate" it "should not call next with an error", () -> @BetaProgramController.optOut @req, @res, @next @next.callCount.should.equal 0 it "should not call next with an error", () -> @BetaProgramController.optOut @req, @res, @next @next.callCount.should.equal 0 it "should call BetaProgramHandler.optOut", () -> @BetaProgramController.optOut @req, @res, @next @BetaProgramHandler.optOut.callCount.should.equal 1 describe "when BetaProgramHandler.optOut produces an error", -> beforeEach -> @BetaProgramHandler.optOut.callsArgWith(1, new Error('woops')) it "should not redirect to '/beta/participate'", () -> @BetaProgramController.optOut @req, @res, @next @res.redirect.callCount.should.equal 0 it "should produce an error", () -> @BetaProgramController.optOut @req, @res, @next @next.callCount.should.equal 1 @next.firstCall.args[0].should.be.instanceof Error describe "optInPage", -> beforeEach -> @UserGetter.getUser.callsArgWith(1, null, @user) it "should render the opt-in page", () -> @BetaProgramController.optInPage @req, @res, @next @res.render.callCount.should.equal 1 args = @res.render.firstCall.args args[0].should.equal 'beta_program/opt_in' describe "when UserGetter.getUser produces an error", -> beforeEach -> @UserGetter.getUser.callsArgWith(1, new Error('woops')) it "should not render the opt-in page", () -> @BetaProgramController.optInPage @req, @res, @next @res.render.callCount.should.equal 0 it "should produce an error", () -> @BetaProgramController.optInPage @req, @res, @next @next.callCount.should.equal 1 @next.firstCall.args[0].should.be.instanceof Error
[ { "context": "###!\n LegoMushroom @legomushroom http://legomushroom.com\n MIT Licen", "end": 19, "score": 0.9968811273574829, "start": 7, "tag": "NAME", "value": "LegoMushroom" }, { "context": "###!\n LegoMushroom @legomushroom http://legomushroom.com\n MIT License 2014\n###\n\n#", "end": 33, "score": 0.9995555877685547, "start": 20, "tag": "USERNAME", "value": "@legomushroom" }, { "context": "it was covered in its own repo https://github.com/legomushroom/resize\n class Main\n constructor:(@o={})->\n ", "end": 246, "score": 0.9994328022003174, "start": 234, "tag": "USERNAME", "value": "legomushroom" } ]
js/vendor/resize.coffee
LukasDrgon/mojs
24
###! LegoMushroom @legomushroom http://legomushroom.com MIT License 2014 ### ### istanbul ignore next ### do -> # IIF for istanbul to ignore the whole resize event polyfill # it was covered in its own repo https://github.com/legomushroom/resize class Main constructor:(@o={})-> return if window.isAnyResizeEventInited @vars() @redefineProto() vars:-> window.isAnyResizeEventInited = true @allowedProtos = [ HTMLDivElement, HTMLFormElement, HTMLLinkElement, HTMLBodyElement, HTMLParagraphElement, HTMLFieldSetElement, HTMLLegendElement, HTMLLabelElement, HTMLButtonElement, HTMLUListElement, HTMLOListElement, HTMLLIElement, HTMLHeadingElement, HTMLQuoteElement, HTMLPreElement, HTMLBRElement, HTMLFontElement, HTMLHRElement, HTMLModElement, HTMLParamElement, HTMLMapElement, HTMLTableElement, HTMLTableCaptionElement, HTMLImageElement, HTMLTableCellElement, HTMLSelectElement, HTMLInputElement, HTMLTextAreaElement, HTMLAnchorElement, HTMLObjectElement, HTMLTableColElement, HTMLTableSectionElement, HTMLTableRowElement ] @timerElements = img: 1 textarea: 1 input: 1 embed: 1 object: 1 svg: 1 canvas: 1 tr: 1 tbody: 1 thead: 1 tfoot: 1 a: 1 select: 1 option: 1 optgroup: 1 dl: 1 dt: 1 br: 1 basefont: 1 font: 1 col: 1 iframe: 1 redefineProto:-> it = @ t = for proto, i in @allowedProtos if !proto::? then continue do (proto)-> listener = proto::addEventListener or proto::attachEvent do (listener)-> wrappedListener = -> if @ isnt window or @ isnt document option = arguments[0] is 'onresize' and !@isAnyResizeEventInited option and it.handleResize args:arguments that:@ listener.apply(@,arguments) if proto::addEventListener proto::addEventListener = wrappedListener else if proto::attachEvent proto::attachEvent = wrappedListener remover = proto::removeEventListener or proto::detachEvent do (remover)-> wrappedRemover = -> @isAnyResizeEventInited = false @iframe and @removeChild @iframe remover.apply(@,arguments) if proto::removeEventListener proto::removeEventListener = wrappedRemover else if proto::detachEvent proto::detachEvent = wrappedListener handleResize:(args)-> el = args.that if !@timerElements[el.tagName.toLowerCase()] iframe = document.createElement 'iframe' el.appendChild iframe iframe.style.width = '100%' iframe.style.height = '100%' iframe.style.position = 'absolute' iframe.style.zIndex = -999 iframe.style.opacity = 0 iframe.style.top = 0 iframe.style.left = 0 computedStyle = if window.getComputedStyle getComputedStyle(el) else el.currentStyle isNoPos = el.style.position is '' isStatic = computedStyle.position is 'static' and isNoPos isEmpty = computedStyle.position is '' and el.style.position is '' if isStatic or isEmpty el.style.position = 'relative' iframe.contentWindow?.onresize = (e)=> @dispatchEvent el el.iframe = iframe else @initTimer(el) el.isAnyResizeEventInited = true initTimer:(el)-> width = 0 height = 0 @interval = setInterval => newWidth = el.offsetWidth newHeight = el.offsetHeight if newWidth isnt width or newHeight isnt height @dispatchEvent el width = newWidth height = newHeight , @o.interval or 62.5 dispatchEvent:(el)-> if document.createEvent e = document.createEvent 'HTMLEvents' e.initEvent 'onresize', false, false el.dispatchEvent e else if document.createEventObject e = document.createEventObject() el.fireEvent 'onresize', e else return false destroy:-> clearInterval @interval @interval = null window.isAnyResizeEventInited = false it = @ for proto, i in @allowedProtos if !proto::? then continue do (proto)-> listener = proto::addEventListener or proto::attachEvent if proto::addEventListener proto::addEventListener = Element::addEventListener else if proto::attachEvent proto::attachEvent = Element::attachEvent if proto::removeEventListener proto::removeEventListener = Element::removeEventListener else if proto::detachEvent proto::detachEvent = Element::detachEvent if (typeof define is "function") and define.amd define "any-resize-event", [], -> new Main else if (typeof module is "object") and (typeof module.exports is "object") module.exports = new Main else window?.AnyResizeEvent = Main window?.anyResizeEvent = new Main
165566
###! <NAME> @legomushroom http://legomushroom.com MIT License 2014 ### ### istanbul ignore next ### do -> # IIF for istanbul to ignore the whole resize event polyfill # it was covered in its own repo https://github.com/legomushroom/resize class Main constructor:(@o={})-> return if window.isAnyResizeEventInited @vars() @redefineProto() vars:-> window.isAnyResizeEventInited = true @allowedProtos = [ HTMLDivElement, HTMLFormElement, HTMLLinkElement, HTMLBodyElement, HTMLParagraphElement, HTMLFieldSetElement, HTMLLegendElement, HTMLLabelElement, HTMLButtonElement, HTMLUListElement, HTMLOListElement, HTMLLIElement, HTMLHeadingElement, HTMLQuoteElement, HTMLPreElement, HTMLBRElement, HTMLFontElement, HTMLHRElement, HTMLModElement, HTMLParamElement, HTMLMapElement, HTMLTableElement, HTMLTableCaptionElement, HTMLImageElement, HTMLTableCellElement, HTMLSelectElement, HTMLInputElement, HTMLTextAreaElement, HTMLAnchorElement, HTMLObjectElement, HTMLTableColElement, HTMLTableSectionElement, HTMLTableRowElement ] @timerElements = img: 1 textarea: 1 input: 1 embed: 1 object: 1 svg: 1 canvas: 1 tr: 1 tbody: 1 thead: 1 tfoot: 1 a: 1 select: 1 option: 1 optgroup: 1 dl: 1 dt: 1 br: 1 basefont: 1 font: 1 col: 1 iframe: 1 redefineProto:-> it = @ t = for proto, i in @allowedProtos if !proto::? then continue do (proto)-> listener = proto::addEventListener or proto::attachEvent do (listener)-> wrappedListener = -> if @ isnt window or @ isnt document option = arguments[0] is 'onresize' and !@isAnyResizeEventInited option and it.handleResize args:arguments that:@ listener.apply(@,arguments) if proto::addEventListener proto::addEventListener = wrappedListener else if proto::attachEvent proto::attachEvent = wrappedListener remover = proto::removeEventListener or proto::detachEvent do (remover)-> wrappedRemover = -> @isAnyResizeEventInited = false @iframe and @removeChild @iframe remover.apply(@,arguments) if proto::removeEventListener proto::removeEventListener = wrappedRemover else if proto::detachEvent proto::detachEvent = wrappedListener handleResize:(args)-> el = args.that if !@timerElements[el.tagName.toLowerCase()] iframe = document.createElement 'iframe' el.appendChild iframe iframe.style.width = '100%' iframe.style.height = '100%' iframe.style.position = 'absolute' iframe.style.zIndex = -999 iframe.style.opacity = 0 iframe.style.top = 0 iframe.style.left = 0 computedStyle = if window.getComputedStyle getComputedStyle(el) else el.currentStyle isNoPos = el.style.position is '' isStatic = computedStyle.position is 'static' and isNoPos isEmpty = computedStyle.position is '' and el.style.position is '' if isStatic or isEmpty el.style.position = 'relative' iframe.contentWindow?.onresize = (e)=> @dispatchEvent el el.iframe = iframe else @initTimer(el) el.isAnyResizeEventInited = true initTimer:(el)-> width = 0 height = 0 @interval = setInterval => newWidth = el.offsetWidth newHeight = el.offsetHeight if newWidth isnt width or newHeight isnt height @dispatchEvent el width = newWidth height = newHeight , @o.interval or 62.5 dispatchEvent:(el)-> if document.createEvent e = document.createEvent 'HTMLEvents' e.initEvent 'onresize', false, false el.dispatchEvent e else if document.createEventObject e = document.createEventObject() el.fireEvent 'onresize', e else return false destroy:-> clearInterval @interval @interval = null window.isAnyResizeEventInited = false it = @ for proto, i in @allowedProtos if !proto::? then continue do (proto)-> listener = proto::addEventListener or proto::attachEvent if proto::addEventListener proto::addEventListener = Element::addEventListener else if proto::attachEvent proto::attachEvent = Element::attachEvent if proto::removeEventListener proto::removeEventListener = Element::removeEventListener else if proto::detachEvent proto::detachEvent = Element::detachEvent if (typeof define is "function") and define.amd define "any-resize-event", [], -> new Main else if (typeof module is "object") and (typeof module.exports is "object") module.exports = new Main else window?.AnyResizeEvent = Main window?.anyResizeEvent = new Main
true
###! PI:NAME:<NAME>END_PI @legomushroom http://legomushroom.com MIT License 2014 ### ### istanbul ignore next ### do -> # IIF for istanbul to ignore the whole resize event polyfill # it was covered in its own repo https://github.com/legomushroom/resize class Main constructor:(@o={})-> return if window.isAnyResizeEventInited @vars() @redefineProto() vars:-> window.isAnyResizeEventInited = true @allowedProtos = [ HTMLDivElement, HTMLFormElement, HTMLLinkElement, HTMLBodyElement, HTMLParagraphElement, HTMLFieldSetElement, HTMLLegendElement, HTMLLabelElement, HTMLButtonElement, HTMLUListElement, HTMLOListElement, HTMLLIElement, HTMLHeadingElement, HTMLQuoteElement, HTMLPreElement, HTMLBRElement, HTMLFontElement, HTMLHRElement, HTMLModElement, HTMLParamElement, HTMLMapElement, HTMLTableElement, HTMLTableCaptionElement, HTMLImageElement, HTMLTableCellElement, HTMLSelectElement, HTMLInputElement, HTMLTextAreaElement, HTMLAnchorElement, HTMLObjectElement, HTMLTableColElement, HTMLTableSectionElement, HTMLTableRowElement ] @timerElements = img: 1 textarea: 1 input: 1 embed: 1 object: 1 svg: 1 canvas: 1 tr: 1 tbody: 1 thead: 1 tfoot: 1 a: 1 select: 1 option: 1 optgroup: 1 dl: 1 dt: 1 br: 1 basefont: 1 font: 1 col: 1 iframe: 1 redefineProto:-> it = @ t = for proto, i in @allowedProtos if !proto::? then continue do (proto)-> listener = proto::addEventListener or proto::attachEvent do (listener)-> wrappedListener = -> if @ isnt window or @ isnt document option = arguments[0] is 'onresize' and !@isAnyResizeEventInited option and it.handleResize args:arguments that:@ listener.apply(@,arguments) if proto::addEventListener proto::addEventListener = wrappedListener else if proto::attachEvent proto::attachEvent = wrappedListener remover = proto::removeEventListener or proto::detachEvent do (remover)-> wrappedRemover = -> @isAnyResizeEventInited = false @iframe and @removeChild @iframe remover.apply(@,arguments) if proto::removeEventListener proto::removeEventListener = wrappedRemover else if proto::detachEvent proto::detachEvent = wrappedListener handleResize:(args)-> el = args.that if !@timerElements[el.tagName.toLowerCase()] iframe = document.createElement 'iframe' el.appendChild iframe iframe.style.width = '100%' iframe.style.height = '100%' iframe.style.position = 'absolute' iframe.style.zIndex = -999 iframe.style.opacity = 0 iframe.style.top = 0 iframe.style.left = 0 computedStyle = if window.getComputedStyle getComputedStyle(el) else el.currentStyle isNoPos = el.style.position is '' isStatic = computedStyle.position is 'static' and isNoPos isEmpty = computedStyle.position is '' and el.style.position is '' if isStatic or isEmpty el.style.position = 'relative' iframe.contentWindow?.onresize = (e)=> @dispatchEvent el el.iframe = iframe else @initTimer(el) el.isAnyResizeEventInited = true initTimer:(el)-> width = 0 height = 0 @interval = setInterval => newWidth = el.offsetWidth newHeight = el.offsetHeight if newWidth isnt width or newHeight isnt height @dispatchEvent el width = newWidth height = newHeight , @o.interval or 62.5 dispatchEvent:(el)-> if document.createEvent e = document.createEvent 'HTMLEvents' e.initEvent 'onresize', false, false el.dispatchEvent e else if document.createEventObject e = document.createEventObject() el.fireEvent 'onresize', e else return false destroy:-> clearInterval @interval @interval = null window.isAnyResizeEventInited = false it = @ for proto, i in @allowedProtos if !proto::? then continue do (proto)-> listener = proto::addEventListener or proto::attachEvent if proto::addEventListener proto::addEventListener = Element::addEventListener else if proto::attachEvent proto::attachEvent = Element::attachEvent if proto::removeEventListener proto::removeEventListener = Element::removeEventListener else if proto::detachEvent proto::detachEvent = Element::detachEvent if (typeof define is "function") and define.amd define "any-resize-event", [], -> new Main else if (typeof module is "object") and (typeof module.exports is "object") module.exports = new Main else window?.AnyResizeEvent = Main window?.anyResizeEvent = new Main
[ { "context": "se strict\"\n\n#\n#* ProjectName: yourLibrary\n#* Name: Christopher EnyTC\n#* Email: chrisenytc@gmail.com\n#* Username: chris", "end": 70, "score": 0.9998993873596191, "start": 53, "tag": "NAME", "value": "Christopher EnyTC" }, { "context": ": yourLibrary\n#* Name: Christopher EnyTC\n#* Email: chrisenytc@gmail.com\n#* Username: chrisenytc\n#* Site: http://chris.eny", "end": 101, "score": 0.999932050704956, "start": 81, "tag": "EMAIL", "value": "chrisenytc@gmail.com" }, { "context": " EnyTC\n#* Email: chrisenytc@gmail.com\n#* Username: chrisenytc\n#* Site: http://chris.enytc.com\n#* Github: https:", "end": 125, "score": 0.9995806813240051, "start": 115, "tag": "USERNAME", "value": "chrisenytc" }, { "context": "p://chris.enytc.com\n#* Github: https://github.com/chrisenytc/generator-library\n#* Twitter: @chrisenytc\n#\nwindo", "end": 198, "score": 0.9974765777587891, "start": 188, "tag": "USERNAME", "value": "chrisenytc" }, { "context": "ithub.com/chrisenytc/generator-library\n#* Twitter: @chrisenytc\n#\nwindow.yourLibrary = (() ->\n\n #Private Functio", "end": 240, "score": 0.9928855895996094, "start": 229, "tag": "USERNAME", "value": "@chrisenytc" } ]
app/templates/src/coffee/yourLibrary.coffee
chrisenytc/generator-library
2
"use strict" # #* ProjectName: yourLibrary #* Name: Christopher EnyTC #* Email: chrisenytc@gmail.com #* Username: chrisenytc #* Site: http://chris.enytc.com #* Github: https://github.com/chrisenytc/generator-library #* Twitter: @chrisenytc # window.yourLibrary = (() -> #Private Functions # # * # * Function to return a version of yourLibrary # * # version = "0.1.0" # # * # * Function to say hello world # * # helloWorld = () -> console.error "Hello World JS!" #Return version: version hello: helloWorld )()
112319
"use strict" # #* ProjectName: yourLibrary #* Name: <NAME> #* Email: <EMAIL> #* Username: chrisenytc #* Site: http://chris.enytc.com #* Github: https://github.com/chrisenytc/generator-library #* Twitter: @chrisenytc # window.yourLibrary = (() -> #Private Functions # # * # * Function to return a version of yourLibrary # * # version = "0.1.0" # # * # * Function to say hello world # * # helloWorld = () -> console.error "Hello World JS!" #Return version: version hello: helloWorld )()
true
"use strict" # #* ProjectName: yourLibrary #* Name: PI:NAME:<NAME>END_PI #* Email: PI:EMAIL:<EMAIL>END_PI #* Username: chrisenytc #* Site: http://chris.enytc.com #* Github: https://github.com/chrisenytc/generator-library #* Twitter: @chrisenytc # window.yourLibrary = (() -> #Private Functions # # * # * Function to return a version of yourLibrary # * # version = "0.1.0" # # * # * Function to say hello world # * # helloWorld = () -> console.error "Hello World JS!" #Return version: version hello: helloWorld )()
[ { "context": "cument.querySelector(\"#login-info img\").src = \"/#{@app.user.nick}.png?v=#{Date.now()}\"\n document.querySelecto", "end": 10595, "score": 0.982893705368042, "start": 10581, "tag": "EMAIL", "value": "@app.user.nick" }, { "context": "ctor(\"#usersettings-profile-image img\").src = \"/#{@app.user.nick}.png?v=#{Date.now()}\"\n document.querySelecto", "end": 10775, "score": 0.991893470287323, "start": 10761, "tag": "EMAIL", "value": "@app.user.nick" } ]
static/js/user/usersettings.coffee
HomineLudens/microstudio
511
class @UserSettings constructor:(@app)-> document.getElementById("resend-validation-email").addEventListener "click",()=>@resendValidationEMail() #document.getElementById("change-password").addEventListener "click",()=>@changePassword() document.getElementById("subscribe-newsletter").addEventListener "change",()=>@newsletterChange() document.getElementById("experimental-features").addEventListener "change",()=>@experimentalChange() document.getElementById("usersetting-email").addEventListener "input",()=>@emailChange() document.getElementById("open-translation-app").addEventListener "click",()=>@openTranslationApp() document.getElementById("translation-app-back-button").addEventListener "click",()=>@closeTranslationApp() @nick_validator = new InputValidator document.getElementById("usersetting-nick"), document.getElementById("usersetting-nick-button"), document.getElementById("usersetting-nick-error"), (value)=> nick = value[0] @app.client.sendRequest { name: "change_nick" nick: nick },(msg)=> if msg.name == "error" and msg.value? @nick_validator.reset() @nick_validator.showError(@app.translator.get(msg.value)) else @nick_validator.set(nick) @app.user.nick = nick document.getElementById("user-nick").innerText = nick @nickUpdated() @nick_validator.regex = RegexLib.nick @email_validator = new InputValidator document.getElementById("usersetting-email"), document.getElementById("usersetting-email-button"), document.getElementById("usersetting-email-error"), (value)=> email = value[0] @app.client.sendRequest { name: "change_email" email: email },(msg)=> if msg.name == "error" and msg.value? @email_validator.reset() @email_validator.showError(@app.translator.get(msg.value)) else @email_validator.set(email) @app.user.email = email @email_validator.regex = RegexLib.email @sections = ["settings","profile","progress"] @initSections() document.getElementById("usersettings-profile").addEventListener "dragover",(event)=> event.preventDefault() document.querySelector("#usersettings-profile-image .fa-user-circle").classList.add "dragover" #console.info event document.getElementById("usersettings-profile").addEventListener "dragleave",(event)=> event.preventDefault() document.querySelector("#usersettings-profile-image .fa-user-circle").classList.remove "dragover" #console.info event document.getElementById("usersettings-profile").addEventListener "drop",(event)=> event.preventDefault() document.querySelector("#usersettings-profile-image .fa-user-circle").classList.remove "dragover" try list = [] for i in event.dataTransfer.items list.push i.getAsFile() if list.length>0 file = list[0] @profileImageDropped(file) catch err console.error err document.querySelector("#usersettings-profile-image").addEventListener "click",()=> input = document.createElement "input" input.type = "file" input.addEventListener "change",(event)=> files = event.target.files if files.length>=1 f = files[0] @profileImageDropped f input.click() document.querySelector("#usersettings-profile .fa-times-circle").addEventListener "click",()=> @removeProfileImage() document.getElementById("usersettings-profile-description").addEventListener "input",()=> @profileDescriptionChanged() if window.ms_standalone document.getElementById("usersettings-menu-profile").style.display = "none" initSections:()-> for s in @sections do (s)=> document.getElementById("usersettings-menu-#{s}").addEventListener "click",()=> switch s when "settings" then @app.openUserSettings() when "profile" then @app.openUserProfile() when "progress" then @app.openUserProgress() setSection:(section)-> @current = section for s in @sections if s == section document.getElementById("usersettings-menu-#{s}").classList.add "selected" document.getElementById("usersettings-#{s}").style.display = "block" else document.getElementById("usersettings-menu-#{s}").classList.remove "selected" document.getElementById("usersettings-#{s}").style.display = "none" if @current == "progress" @app.user_progress.updateStatsPage() return update:()-> document.getElementById("subscribe-newsletter").checked = @app.user.flags["newsletter"] == true document.getElementById("experimental-features").checked = @app.user.flags["experimental"] == true document.getElementById("experimental-features-setting").style.display = if @app.user.flags.validated then "block" else "none" if @app.user.flags["validated"] == true document.getElementById("email-not-validated").style.display = "none" else document.getElementById("email-not-validated").style.display = "block" @nick_validator.set(@app.user.nick) @email_validator.set(@app.user.email) translator = false for key,value of @app.user.flags if key.startsWith("translator_") and value translator = true document.getElementById("open-translation-app").style.display = if translator then "inline-block" else "none" @nickUpdated() account_type = "Standard" if @app.user.flags.guest account_type = @app.translator.get "Guest" else account_type = @app.getTierName @app.user.flags.tier if @app.user.flags.tier icon = new Image icon.src = location.origin+"/microstudio/patreon/badges/sprites/#{@app.user.flags.tier}.png" icon.classList.add "pixelated" icon.style = "width: 32px; height: 32px; vertical-align: middle ; margin-right: 5px" div = document.getElementById("usersettings-account-type") div.innerHTML = "" div.appendChild icon span = document.createElement "span" span.innerText = account_type div.appendChild span else document.getElementById("usersettings-account-type").innerText = account_type @updateStorage() @updateProfileImage() document.getElementById("usersettings-profile-description").value = @app.user.info.description updateStorage:()-> percent = Math.floor(@app.user.info.size/@app.user.info.max_storage*100) str = @app.translator.get "[STORAGE] used of [MAX_STORAGE] ([PERCENT] %)" str = str.replace("[STORAGE]",@app.appui.displayByteSize(@app.user.info.size)) str = str.replace("[MAX_STORAGE]",@app.appui.displayByteSize(@app.user.info.max_storage)) str = str.replace("[PERCENT]",percent) document.getElementById("usersettings-storage").innerText = str nickUpdated:()-> document.getElementById("user-public-page").href = location.origin.replace(".dev",".io")+"/#{@app.user.nick}/" document.getElementById("user-public-page").innerHTML = location.host.replace(".dev",".io")+"/#{@app.user.nick} <i class='fa fa-external-link-alt'></i>" resendValidationEMail:()-> @app.client.sendRequest { name: "send_validation_mail" },(msg)-> document.getElementById("resend-validation-email").style.display = "none" document.getElementById("validation-email-resent").style.display = "block" changePassword:()-> newsletterChange:()-> checked = document.getElementById("subscribe-newsletter").checked @app.user.flags.newsletter = checked @app.client.sendRequest name: "change_newsletter" newsletter: checked experimentalChange:()-> checked = document.getElementById("experimental-features").checked @app.user.flags.experimental = checked @app.client.sendRequest name: "change_experimental" experimental: checked nickChange:()-> emailChange:()-> openTranslationApp:()-> document.getElementById("usersettings").style.display = "none" document.getElementById("translation-app").style.display = "block" if @translation_app? @translation_app.update() else @translation_app = new TranslationApp(@app) closeTranslationApp:()-> document.getElementById("usersettings").style.display = "block" document.getElementById("translation-app").style.display = "none" profileImageDropped:(file)-> reader = new FileReader() img = new Image reader.addEventListener "load",()=> img.src = reader.result reader.readAsDataURL(file) #url = "data:application/javascript;base64,"+btoa(Audio.processor) img.onload = ()=> if img.complete and img.width>0 and img.height>0 canvas = document.createElement "canvas" canvas.width = 128 canvas.height = 128 context = canvas.getContext "2d" if img.width<128 and img.height<128 context.imageSmoothingEnabled = false w = img.width h = img.height r = Math.max(128/w,128/h) w *= r h *= r context.drawImage img,64-w/2,64-h/2,w,h document.querySelector("#usersettings-profile-image img").src = canvas.toDataURL() document.querySelector("#usersettings-profile-image img").style.display = "block" @app.client.sendRequest { name: "set_user_profile" image: canvas.toDataURL().split(",")[1] },()=> @app.user.flags.profile_image = true @updateProfileImage() removeProfileImage:()-> @app.client.sendRequest { name: "set_user_profile" image: 0 },(msg)=> @app.user.flags.profile_image = false document.querySelector("#usersettings-profile-image img").style.display = "none" document.querySelector("#usersettings-profile-image img").src = "" @updateProfileImage() profileDescriptionChanged:()-> if @description_timeout? clearTimeout @description_timeout @description_timeout = setTimeout (()=>@saveProfileDescription()),2000 saveProfileDescription:()-> @app.client.sendRequest { name: "set_user_profile" description: document.getElementById("usersettings-profile-description").value },(msg)=> updateProfileImage:()-> if @app.user.flags.profile_image document.querySelector("#login-info img").style.display = "inline-block" document.querySelector("#login-info img").src = "/#{@app.user.nick}.png?v=#{Date.now()}" document.querySelector("#login-info i").style.display = "none" document.querySelector("#usersettings-profile-image img").src = "/#{@app.user.nick}.png?v=#{Date.now()}" document.querySelector("#usersettings-profile-image img").style.display = "block" document.querySelector("#usersettings-profile-image .fa-times-circle").style.display = "block" else document.querySelector("#login-info img").style.display = "none" document.querySelector("#login-info i").style.display = "inline-block" document.querySelector("#usersettings-profile-image .fa-times-circle").style.display = "none"
36314
class @UserSettings constructor:(@app)-> document.getElementById("resend-validation-email").addEventListener "click",()=>@resendValidationEMail() #document.getElementById("change-password").addEventListener "click",()=>@changePassword() document.getElementById("subscribe-newsletter").addEventListener "change",()=>@newsletterChange() document.getElementById("experimental-features").addEventListener "change",()=>@experimentalChange() document.getElementById("usersetting-email").addEventListener "input",()=>@emailChange() document.getElementById("open-translation-app").addEventListener "click",()=>@openTranslationApp() document.getElementById("translation-app-back-button").addEventListener "click",()=>@closeTranslationApp() @nick_validator = new InputValidator document.getElementById("usersetting-nick"), document.getElementById("usersetting-nick-button"), document.getElementById("usersetting-nick-error"), (value)=> nick = value[0] @app.client.sendRequest { name: "change_nick" nick: nick },(msg)=> if msg.name == "error" and msg.value? @nick_validator.reset() @nick_validator.showError(@app.translator.get(msg.value)) else @nick_validator.set(nick) @app.user.nick = nick document.getElementById("user-nick").innerText = nick @nickUpdated() @nick_validator.regex = RegexLib.nick @email_validator = new InputValidator document.getElementById("usersetting-email"), document.getElementById("usersetting-email-button"), document.getElementById("usersetting-email-error"), (value)=> email = value[0] @app.client.sendRequest { name: "change_email" email: email },(msg)=> if msg.name == "error" and msg.value? @email_validator.reset() @email_validator.showError(@app.translator.get(msg.value)) else @email_validator.set(email) @app.user.email = email @email_validator.regex = RegexLib.email @sections = ["settings","profile","progress"] @initSections() document.getElementById("usersettings-profile").addEventListener "dragover",(event)=> event.preventDefault() document.querySelector("#usersettings-profile-image .fa-user-circle").classList.add "dragover" #console.info event document.getElementById("usersettings-profile").addEventListener "dragleave",(event)=> event.preventDefault() document.querySelector("#usersettings-profile-image .fa-user-circle").classList.remove "dragover" #console.info event document.getElementById("usersettings-profile").addEventListener "drop",(event)=> event.preventDefault() document.querySelector("#usersettings-profile-image .fa-user-circle").classList.remove "dragover" try list = [] for i in event.dataTransfer.items list.push i.getAsFile() if list.length>0 file = list[0] @profileImageDropped(file) catch err console.error err document.querySelector("#usersettings-profile-image").addEventListener "click",()=> input = document.createElement "input" input.type = "file" input.addEventListener "change",(event)=> files = event.target.files if files.length>=1 f = files[0] @profileImageDropped f input.click() document.querySelector("#usersettings-profile .fa-times-circle").addEventListener "click",()=> @removeProfileImage() document.getElementById("usersettings-profile-description").addEventListener "input",()=> @profileDescriptionChanged() if window.ms_standalone document.getElementById("usersettings-menu-profile").style.display = "none" initSections:()-> for s in @sections do (s)=> document.getElementById("usersettings-menu-#{s}").addEventListener "click",()=> switch s when "settings" then @app.openUserSettings() when "profile" then @app.openUserProfile() when "progress" then @app.openUserProgress() setSection:(section)-> @current = section for s in @sections if s == section document.getElementById("usersettings-menu-#{s}").classList.add "selected" document.getElementById("usersettings-#{s}").style.display = "block" else document.getElementById("usersettings-menu-#{s}").classList.remove "selected" document.getElementById("usersettings-#{s}").style.display = "none" if @current == "progress" @app.user_progress.updateStatsPage() return update:()-> document.getElementById("subscribe-newsletter").checked = @app.user.flags["newsletter"] == true document.getElementById("experimental-features").checked = @app.user.flags["experimental"] == true document.getElementById("experimental-features-setting").style.display = if @app.user.flags.validated then "block" else "none" if @app.user.flags["validated"] == true document.getElementById("email-not-validated").style.display = "none" else document.getElementById("email-not-validated").style.display = "block" @nick_validator.set(@app.user.nick) @email_validator.set(@app.user.email) translator = false for key,value of @app.user.flags if key.startsWith("translator_") and value translator = true document.getElementById("open-translation-app").style.display = if translator then "inline-block" else "none" @nickUpdated() account_type = "Standard" if @app.user.flags.guest account_type = @app.translator.get "Guest" else account_type = @app.getTierName @app.user.flags.tier if @app.user.flags.tier icon = new Image icon.src = location.origin+"/microstudio/patreon/badges/sprites/#{@app.user.flags.tier}.png" icon.classList.add "pixelated" icon.style = "width: 32px; height: 32px; vertical-align: middle ; margin-right: 5px" div = document.getElementById("usersettings-account-type") div.innerHTML = "" div.appendChild icon span = document.createElement "span" span.innerText = account_type div.appendChild span else document.getElementById("usersettings-account-type").innerText = account_type @updateStorage() @updateProfileImage() document.getElementById("usersettings-profile-description").value = @app.user.info.description updateStorage:()-> percent = Math.floor(@app.user.info.size/@app.user.info.max_storage*100) str = @app.translator.get "[STORAGE] used of [MAX_STORAGE] ([PERCENT] %)" str = str.replace("[STORAGE]",@app.appui.displayByteSize(@app.user.info.size)) str = str.replace("[MAX_STORAGE]",@app.appui.displayByteSize(@app.user.info.max_storage)) str = str.replace("[PERCENT]",percent) document.getElementById("usersettings-storage").innerText = str nickUpdated:()-> document.getElementById("user-public-page").href = location.origin.replace(".dev",".io")+"/#{@app.user.nick}/" document.getElementById("user-public-page").innerHTML = location.host.replace(".dev",".io")+"/#{@app.user.nick} <i class='fa fa-external-link-alt'></i>" resendValidationEMail:()-> @app.client.sendRequest { name: "send_validation_mail" },(msg)-> document.getElementById("resend-validation-email").style.display = "none" document.getElementById("validation-email-resent").style.display = "block" changePassword:()-> newsletterChange:()-> checked = document.getElementById("subscribe-newsletter").checked @app.user.flags.newsletter = checked @app.client.sendRequest name: "change_newsletter" newsletter: checked experimentalChange:()-> checked = document.getElementById("experimental-features").checked @app.user.flags.experimental = checked @app.client.sendRequest name: "change_experimental" experimental: checked nickChange:()-> emailChange:()-> openTranslationApp:()-> document.getElementById("usersettings").style.display = "none" document.getElementById("translation-app").style.display = "block" if @translation_app? @translation_app.update() else @translation_app = new TranslationApp(@app) closeTranslationApp:()-> document.getElementById("usersettings").style.display = "block" document.getElementById("translation-app").style.display = "none" profileImageDropped:(file)-> reader = new FileReader() img = new Image reader.addEventListener "load",()=> img.src = reader.result reader.readAsDataURL(file) #url = "data:application/javascript;base64,"+btoa(Audio.processor) img.onload = ()=> if img.complete and img.width>0 and img.height>0 canvas = document.createElement "canvas" canvas.width = 128 canvas.height = 128 context = canvas.getContext "2d" if img.width<128 and img.height<128 context.imageSmoothingEnabled = false w = img.width h = img.height r = Math.max(128/w,128/h) w *= r h *= r context.drawImage img,64-w/2,64-h/2,w,h document.querySelector("#usersettings-profile-image img").src = canvas.toDataURL() document.querySelector("#usersettings-profile-image img").style.display = "block" @app.client.sendRequest { name: "set_user_profile" image: canvas.toDataURL().split(",")[1] },()=> @app.user.flags.profile_image = true @updateProfileImage() removeProfileImage:()-> @app.client.sendRequest { name: "set_user_profile" image: 0 },(msg)=> @app.user.flags.profile_image = false document.querySelector("#usersettings-profile-image img").style.display = "none" document.querySelector("#usersettings-profile-image img").src = "" @updateProfileImage() profileDescriptionChanged:()-> if @description_timeout? clearTimeout @description_timeout @description_timeout = setTimeout (()=>@saveProfileDescription()),2000 saveProfileDescription:()-> @app.client.sendRequest { name: "set_user_profile" description: document.getElementById("usersettings-profile-description").value },(msg)=> updateProfileImage:()-> if @app.user.flags.profile_image document.querySelector("#login-info img").style.display = "inline-block" document.querySelector("#login-info img").src = "/#{<EMAIL>}.png?v=#{Date.now()}" document.querySelector("#login-info i").style.display = "none" document.querySelector("#usersettings-profile-image img").src = "/#{<EMAIL>}.png?v=#{Date.now()}" document.querySelector("#usersettings-profile-image img").style.display = "block" document.querySelector("#usersettings-profile-image .fa-times-circle").style.display = "block" else document.querySelector("#login-info img").style.display = "none" document.querySelector("#login-info i").style.display = "inline-block" document.querySelector("#usersettings-profile-image .fa-times-circle").style.display = "none"
true
class @UserSettings constructor:(@app)-> document.getElementById("resend-validation-email").addEventListener "click",()=>@resendValidationEMail() #document.getElementById("change-password").addEventListener "click",()=>@changePassword() document.getElementById("subscribe-newsletter").addEventListener "change",()=>@newsletterChange() document.getElementById("experimental-features").addEventListener "change",()=>@experimentalChange() document.getElementById("usersetting-email").addEventListener "input",()=>@emailChange() document.getElementById("open-translation-app").addEventListener "click",()=>@openTranslationApp() document.getElementById("translation-app-back-button").addEventListener "click",()=>@closeTranslationApp() @nick_validator = new InputValidator document.getElementById("usersetting-nick"), document.getElementById("usersetting-nick-button"), document.getElementById("usersetting-nick-error"), (value)=> nick = value[0] @app.client.sendRequest { name: "change_nick" nick: nick },(msg)=> if msg.name == "error" and msg.value? @nick_validator.reset() @nick_validator.showError(@app.translator.get(msg.value)) else @nick_validator.set(nick) @app.user.nick = nick document.getElementById("user-nick").innerText = nick @nickUpdated() @nick_validator.regex = RegexLib.nick @email_validator = new InputValidator document.getElementById("usersetting-email"), document.getElementById("usersetting-email-button"), document.getElementById("usersetting-email-error"), (value)=> email = value[0] @app.client.sendRequest { name: "change_email" email: email },(msg)=> if msg.name == "error" and msg.value? @email_validator.reset() @email_validator.showError(@app.translator.get(msg.value)) else @email_validator.set(email) @app.user.email = email @email_validator.regex = RegexLib.email @sections = ["settings","profile","progress"] @initSections() document.getElementById("usersettings-profile").addEventListener "dragover",(event)=> event.preventDefault() document.querySelector("#usersettings-profile-image .fa-user-circle").classList.add "dragover" #console.info event document.getElementById("usersettings-profile").addEventListener "dragleave",(event)=> event.preventDefault() document.querySelector("#usersettings-profile-image .fa-user-circle").classList.remove "dragover" #console.info event document.getElementById("usersettings-profile").addEventListener "drop",(event)=> event.preventDefault() document.querySelector("#usersettings-profile-image .fa-user-circle").classList.remove "dragover" try list = [] for i in event.dataTransfer.items list.push i.getAsFile() if list.length>0 file = list[0] @profileImageDropped(file) catch err console.error err document.querySelector("#usersettings-profile-image").addEventListener "click",()=> input = document.createElement "input" input.type = "file" input.addEventListener "change",(event)=> files = event.target.files if files.length>=1 f = files[0] @profileImageDropped f input.click() document.querySelector("#usersettings-profile .fa-times-circle").addEventListener "click",()=> @removeProfileImage() document.getElementById("usersettings-profile-description").addEventListener "input",()=> @profileDescriptionChanged() if window.ms_standalone document.getElementById("usersettings-menu-profile").style.display = "none" initSections:()-> for s in @sections do (s)=> document.getElementById("usersettings-menu-#{s}").addEventListener "click",()=> switch s when "settings" then @app.openUserSettings() when "profile" then @app.openUserProfile() when "progress" then @app.openUserProgress() setSection:(section)-> @current = section for s in @sections if s == section document.getElementById("usersettings-menu-#{s}").classList.add "selected" document.getElementById("usersettings-#{s}").style.display = "block" else document.getElementById("usersettings-menu-#{s}").classList.remove "selected" document.getElementById("usersettings-#{s}").style.display = "none" if @current == "progress" @app.user_progress.updateStatsPage() return update:()-> document.getElementById("subscribe-newsletter").checked = @app.user.flags["newsletter"] == true document.getElementById("experimental-features").checked = @app.user.flags["experimental"] == true document.getElementById("experimental-features-setting").style.display = if @app.user.flags.validated then "block" else "none" if @app.user.flags["validated"] == true document.getElementById("email-not-validated").style.display = "none" else document.getElementById("email-not-validated").style.display = "block" @nick_validator.set(@app.user.nick) @email_validator.set(@app.user.email) translator = false for key,value of @app.user.flags if key.startsWith("translator_") and value translator = true document.getElementById("open-translation-app").style.display = if translator then "inline-block" else "none" @nickUpdated() account_type = "Standard" if @app.user.flags.guest account_type = @app.translator.get "Guest" else account_type = @app.getTierName @app.user.flags.tier if @app.user.flags.tier icon = new Image icon.src = location.origin+"/microstudio/patreon/badges/sprites/#{@app.user.flags.tier}.png" icon.classList.add "pixelated" icon.style = "width: 32px; height: 32px; vertical-align: middle ; margin-right: 5px" div = document.getElementById("usersettings-account-type") div.innerHTML = "" div.appendChild icon span = document.createElement "span" span.innerText = account_type div.appendChild span else document.getElementById("usersettings-account-type").innerText = account_type @updateStorage() @updateProfileImage() document.getElementById("usersettings-profile-description").value = @app.user.info.description updateStorage:()-> percent = Math.floor(@app.user.info.size/@app.user.info.max_storage*100) str = @app.translator.get "[STORAGE] used of [MAX_STORAGE] ([PERCENT] %)" str = str.replace("[STORAGE]",@app.appui.displayByteSize(@app.user.info.size)) str = str.replace("[MAX_STORAGE]",@app.appui.displayByteSize(@app.user.info.max_storage)) str = str.replace("[PERCENT]",percent) document.getElementById("usersettings-storage").innerText = str nickUpdated:()-> document.getElementById("user-public-page").href = location.origin.replace(".dev",".io")+"/#{@app.user.nick}/" document.getElementById("user-public-page").innerHTML = location.host.replace(".dev",".io")+"/#{@app.user.nick} <i class='fa fa-external-link-alt'></i>" resendValidationEMail:()-> @app.client.sendRequest { name: "send_validation_mail" },(msg)-> document.getElementById("resend-validation-email").style.display = "none" document.getElementById("validation-email-resent").style.display = "block" changePassword:()-> newsletterChange:()-> checked = document.getElementById("subscribe-newsletter").checked @app.user.flags.newsletter = checked @app.client.sendRequest name: "change_newsletter" newsletter: checked experimentalChange:()-> checked = document.getElementById("experimental-features").checked @app.user.flags.experimental = checked @app.client.sendRequest name: "change_experimental" experimental: checked nickChange:()-> emailChange:()-> openTranslationApp:()-> document.getElementById("usersettings").style.display = "none" document.getElementById("translation-app").style.display = "block" if @translation_app? @translation_app.update() else @translation_app = new TranslationApp(@app) closeTranslationApp:()-> document.getElementById("usersettings").style.display = "block" document.getElementById("translation-app").style.display = "none" profileImageDropped:(file)-> reader = new FileReader() img = new Image reader.addEventListener "load",()=> img.src = reader.result reader.readAsDataURL(file) #url = "data:application/javascript;base64,"+btoa(Audio.processor) img.onload = ()=> if img.complete and img.width>0 and img.height>0 canvas = document.createElement "canvas" canvas.width = 128 canvas.height = 128 context = canvas.getContext "2d" if img.width<128 and img.height<128 context.imageSmoothingEnabled = false w = img.width h = img.height r = Math.max(128/w,128/h) w *= r h *= r context.drawImage img,64-w/2,64-h/2,w,h document.querySelector("#usersettings-profile-image img").src = canvas.toDataURL() document.querySelector("#usersettings-profile-image img").style.display = "block" @app.client.sendRequest { name: "set_user_profile" image: canvas.toDataURL().split(",")[1] },()=> @app.user.flags.profile_image = true @updateProfileImage() removeProfileImage:()-> @app.client.sendRequest { name: "set_user_profile" image: 0 },(msg)=> @app.user.flags.profile_image = false document.querySelector("#usersettings-profile-image img").style.display = "none" document.querySelector("#usersettings-profile-image img").src = "" @updateProfileImage() profileDescriptionChanged:()-> if @description_timeout? clearTimeout @description_timeout @description_timeout = setTimeout (()=>@saveProfileDescription()),2000 saveProfileDescription:()-> @app.client.sendRequest { name: "set_user_profile" description: document.getElementById("usersettings-profile-description").value },(msg)=> updateProfileImage:()-> if @app.user.flags.profile_image document.querySelector("#login-info img").style.display = "inline-block" document.querySelector("#login-info img").src = "/#{PI:EMAIL:<EMAIL>END_PI}.png?v=#{Date.now()}" document.querySelector("#login-info i").style.display = "none" document.querySelector("#usersettings-profile-image img").src = "/#{PI:EMAIL:<EMAIL>END_PI}.png?v=#{Date.now()}" document.querySelector("#usersettings-profile-image img").style.display = "block" document.querySelector("#usersettings-profile-image .fa-times-circle").style.display = "block" else document.querySelector("#login-info img").style.display = "none" document.querySelector("#login-info i").style.display = "inline-block" document.querySelector("#usersettings-profile-image .fa-times-circle").style.display = "none"
[ { "context": "isbn: '0553560735'\n title: 'Red Mars'\n author: 'Kim Stanley Robinson'\n description: 'For centuries, the barren, desol", "end": 89, "score": 0.9993829727172852, "start": 69, "tag": "NAME", "value": "Kim Stanley Robinson" } ]
data/books.coffee
rachel-carvalho/next-sample
0
export default [ isbn: '0553560735' title: 'Red Mars' author: 'Kim Stanley Robinson' description: 'For centuries, the barren, desolate landscape of the red planet has beckoned to humankind. Now a group of one hundred colonists begins a mission whose ultimate goal is to transform Mars into a more Earthlike planet. They will place giant satellite mirrors in Martian orbit to reflect light to the surface. Black dust sprinkled on the polar caps will capture warmth and melt the ice. And massive tunnels drilled into the mantle will create stupendous vents of hot gases. But despite these ambitious goals, there are some who would fight to the death to prevent Mars from ever being changed.' ]
110730
export default [ isbn: '0553560735' title: 'Red Mars' author: '<NAME>' description: 'For centuries, the barren, desolate landscape of the red planet has beckoned to humankind. Now a group of one hundred colonists begins a mission whose ultimate goal is to transform Mars into a more Earthlike planet. They will place giant satellite mirrors in Martian orbit to reflect light to the surface. Black dust sprinkled on the polar caps will capture warmth and melt the ice. And massive tunnels drilled into the mantle will create stupendous vents of hot gases. But despite these ambitious goals, there are some who would fight to the death to prevent Mars from ever being changed.' ]
true
export default [ isbn: '0553560735' title: 'Red Mars' author: 'PI:NAME:<NAME>END_PI' description: 'For centuries, the barren, desolate landscape of the red planet has beckoned to humankind. Now a group of one hundred colonists begins a mission whose ultimate goal is to transform Mars into a more Earthlike planet. They will place giant satellite mirrors in Martian orbit to reflect light to the surface. Black dust sprinkled on the polar caps will capture warmth and melt the ice. And massive tunnels drilled into the mantle will create stupendous vents of hot gases. But despite these ambitious goals, there are some who would fight to the death to prevent Mars from ever being changed.' ]
[ { "context": "{services[\"cloud_foundry_api-uaa-client-secret\"].b64}\"\n site: \"https://#{services[\"cloud_foundry_", "end": 345, "score": 0.6418544054031372, "start": 343, "tag": "KEY", "value": "64" } ]
routes/uaaAdminOauth.coffee
MonsantoCo/cf-users
14
Promise = require 'promise' services = require "./serviceBindings" uao = {} uao.initOauth2 = ()-> new Promise (resolve,reject) -> # Set the client credentials and the OAuth2 server credentials = clientID: "#{services["cloud_foundry_api-uaa-client-id"].b64}" clientSecret: "#{services["cloud_foundry_api-uaa-client-secret"].b64}" site: "https://#{services["cloud_foundry_api-uaa-domain"].value}" authorizationPath: '/oauth/authorize' tokenPath: '/oauth/token' revocationPath: '/oauth/oauth/revoke' # Initialize the OAuth2 Library oauth2 = require('simple-oauth2')(credentials) tokenConfig = {} console.log("Initializing UAA Admin Access Token") uao.token = null; # Save the access token oauth2.client.getToken tokenConfig, (error, result) -> if (error) console.log 'UAA Access Token Error', JSON.stringify(error,0,2) reject("error fetching UAA access token") else uao.token = oauth2.accessToken.create(result); # console.log("UAA Admin Access Token",uao) console.log("UAA Oauth2 initialized") resolve(uao.token) uao.refreshToken = ( method ) -> if uao.token?.expired() uao.token.refresh (error, result) -> if (error) console.log 'UAA Access Token Error', JSON.stringify(error,0,2) uao.initOauth2().then method, ()-> method(uao.token) else uao.token = result; # console.log("UAA Admin Access Token",uao) method(uao.token) else method(uao.token) module.exports = uao
80881
Promise = require 'promise' services = require "./serviceBindings" uao = {} uao.initOauth2 = ()-> new Promise (resolve,reject) -> # Set the client credentials and the OAuth2 server credentials = clientID: "#{services["cloud_foundry_api-uaa-client-id"].b64}" clientSecret: "#{services["cloud_foundry_api-uaa-client-secret"].b<KEY>}" site: "https://#{services["cloud_foundry_api-uaa-domain"].value}" authorizationPath: '/oauth/authorize' tokenPath: '/oauth/token' revocationPath: '/oauth/oauth/revoke' # Initialize the OAuth2 Library oauth2 = require('simple-oauth2')(credentials) tokenConfig = {} console.log("Initializing UAA Admin Access Token") uao.token = null; # Save the access token oauth2.client.getToken tokenConfig, (error, result) -> if (error) console.log 'UAA Access Token Error', JSON.stringify(error,0,2) reject("error fetching UAA access token") else uao.token = oauth2.accessToken.create(result); # console.log("UAA Admin Access Token",uao) console.log("UAA Oauth2 initialized") resolve(uao.token) uao.refreshToken = ( method ) -> if uao.token?.expired() uao.token.refresh (error, result) -> if (error) console.log 'UAA Access Token Error', JSON.stringify(error,0,2) uao.initOauth2().then method, ()-> method(uao.token) else uao.token = result; # console.log("UAA Admin Access Token",uao) method(uao.token) else method(uao.token) module.exports = uao
true
Promise = require 'promise' services = require "./serviceBindings" uao = {} uao.initOauth2 = ()-> new Promise (resolve,reject) -> # Set the client credentials and the OAuth2 server credentials = clientID: "#{services["cloud_foundry_api-uaa-client-id"].b64}" clientSecret: "#{services["cloud_foundry_api-uaa-client-secret"].bPI:KEY:<KEY>END_PI}" site: "https://#{services["cloud_foundry_api-uaa-domain"].value}" authorizationPath: '/oauth/authorize' tokenPath: '/oauth/token' revocationPath: '/oauth/oauth/revoke' # Initialize the OAuth2 Library oauth2 = require('simple-oauth2')(credentials) tokenConfig = {} console.log("Initializing UAA Admin Access Token") uao.token = null; # Save the access token oauth2.client.getToken tokenConfig, (error, result) -> if (error) console.log 'UAA Access Token Error', JSON.stringify(error,0,2) reject("error fetching UAA access token") else uao.token = oauth2.accessToken.create(result); # console.log("UAA Admin Access Token",uao) console.log("UAA Oauth2 initialized") resolve(uao.token) uao.refreshToken = ( method ) -> if uao.token?.expired() uao.token.refresh (error, result) -> if (error) console.log 'UAA Access Token Error', JSON.stringify(error,0,2) uao.initOauth2().then method, ()-> method(uao.token) else uao.token = result; # console.log("UAA Admin Access Token",uao) method(uao.token) else method(uao.token) module.exports = uao
[ { "context": " user = robot.brain.userForId '1',\n name: 'sammy'\n room: '#stamp'\n adapter = robot.ada", "end": 561, "score": 0.9510841369628906, "start": 556, "tag": "NAME", "value": "sammy" } ]
test/stamp_spec.coffee
osamunmun/Hubot
0
# Hubot classes Robot = require("hubot/src/robot") TextMessage = require("hubot/src/message").TextMessage # Load assertion methods to this scope chai = require 'chai' expect = chai.expect describe 'stamp', -> robot = null user = null adapter = null process.env.HUBOT_STAMPS = "{\"doki\": \"dokidoki\", \"pon\": \"ponpon\"}" beforeEach (done) -> robot = new Robot(null, 'mock-adapter', false, 'hubot') robot.adapter.on 'connected', -> require('../scripts/stamp')(robot) user = robot.brain.userForId '1', name: 'sammy' room: '#stamp' adapter = robot.adapter done() robot.run() afterEach -> robot.shutdown() it 'responds "stp doki"', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.equal('dokidoki') done() adapter.receive(new TextMessage(user, 'stp doki')) it 'responds "stamp pon"', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.equal('ponpon') done() adapter.receive(new TextMessage(user, 'stamp pon')) it 'responds "stp list"', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.equal('doki,pon') done() adapter.receive(new TextMessage(user, 'stp list')) it 'responds "stamp list"', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.equal('doki,pon') done() adapter.receive(new TextMessage(user, 'stamp list')) it 'responds "Nothing keyword"', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.equal('No stamp for Nothing') done() adapter.receive(new TextMessage(user, 'stp Nothing'))
165994
# Hubot classes Robot = require("hubot/src/robot") TextMessage = require("hubot/src/message").TextMessage # Load assertion methods to this scope chai = require 'chai' expect = chai.expect describe 'stamp', -> robot = null user = null adapter = null process.env.HUBOT_STAMPS = "{\"doki\": \"dokidoki\", \"pon\": \"ponpon\"}" beforeEach (done) -> robot = new Robot(null, 'mock-adapter', false, 'hubot') robot.adapter.on 'connected', -> require('../scripts/stamp')(robot) user = robot.brain.userForId '1', name: '<NAME>' room: '#stamp' adapter = robot.adapter done() robot.run() afterEach -> robot.shutdown() it 'responds "stp doki"', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.equal('dokidoki') done() adapter.receive(new TextMessage(user, 'stp doki')) it 'responds "stamp pon"', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.equal('ponpon') done() adapter.receive(new TextMessage(user, 'stamp pon')) it 'responds "stp list"', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.equal('doki,pon') done() adapter.receive(new TextMessage(user, 'stp list')) it 'responds "stamp list"', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.equal('doki,pon') done() adapter.receive(new TextMessage(user, 'stamp list')) it 'responds "Nothing keyword"', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.equal('No stamp for Nothing') done() adapter.receive(new TextMessage(user, 'stp Nothing'))
true
# Hubot classes Robot = require("hubot/src/robot") TextMessage = require("hubot/src/message").TextMessage # Load assertion methods to this scope chai = require 'chai' expect = chai.expect describe 'stamp', -> robot = null user = null adapter = null process.env.HUBOT_STAMPS = "{\"doki\": \"dokidoki\", \"pon\": \"ponpon\"}" beforeEach (done) -> robot = new Robot(null, 'mock-adapter', false, 'hubot') robot.adapter.on 'connected', -> require('../scripts/stamp')(robot) user = robot.brain.userForId '1', name: 'PI:NAME:<NAME>END_PI' room: '#stamp' adapter = robot.adapter done() robot.run() afterEach -> robot.shutdown() it 'responds "stp doki"', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.equal('dokidoki') done() adapter.receive(new TextMessage(user, 'stp doki')) it 'responds "stamp pon"', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.equal('ponpon') done() adapter.receive(new TextMessage(user, 'stamp pon')) it 'responds "stp list"', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.equal('doki,pon') done() adapter.receive(new TextMessage(user, 'stp list')) it 'responds "stamp list"', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.equal('doki,pon') done() adapter.receive(new TextMessage(user, 'stamp list')) it 'responds "Nothing keyword"', (done) -> adapter.on 'send', (envelope, strings) -> expect(strings[0]).to.equal('No stamp for Nothing') done() adapter.receive(new TextMessage(user, 'stp Nothing'))
[ { "context": "kbone-Forms validators 1.0.1\n\n Copyright (c) 2016 Tomasz Jakub Rup\n\n https://github.com/tomi77/backbone-forms-valid", "end": 76, "score": 0.9998704791069031, "start": 60, "tag": "NAME", "value": "Tomasz Jakub Rup" }, { "context": "t (c) 2016 Tomasz Jakub Rup\n\n https://github.com/tomi77/backbone-forms-validators\n\n Released under the M", "end": 105, "score": 0.9996328353881836, "start": 99, "tag": "USERNAME", "value": "tomi77" } ]
src/bbf-validators.coffee
tomi77/backbone-forms-validators
0
### Backbone-Forms validators 1.0.1 Copyright (c) 2016 Tomasz Jakub Rup https://github.com/tomi77/backbone-forms-validators Released under the MIT license ### ((root, factory) -> ### istanbul ignore next ### switch when typeof define is 'function' and define.amd define ['underscore', 'backbone-forms'], factory when typeof exports is 'object' factory require('underscore'), require('backbone-forms') else factory root._, root.Backbone.Form return ) @, (_, Form) -> Form.validators.multiple = (options) -> options = _.extend separator: ';' , options base_validator = Form.validators[options.base_type] options (value) -> value = null if value.trim() is '' # Don't check empty values (add a 'required' validator for this) unless value? then return options.value = value value = value.split(options.separator).map (email) -> email.trim() out = _.compact _.map value, base_validator if out.length > 0 type: options.base_type message: options.message or out[0].message Form.validators.errMessages.phone = 'Incorrect phone number' Form.validators.phone = (options) -> options = _.extend type: 'phone' message: Form.validators.errMessages.phone regexp: /// ^ (?: (?: \(? (?: 00 | \+ ) (?: [1-4]\d{2} | [1-9]\d? ) \)? )? [\-\.\ \\\/]? )? (?: \(? \d+ \)? [\-\.\ \\\/]? )+ (?: [\-\.\ \\\/]? (?: \# | ext\.? | extension | x ) [\-\.\ \\\/]? \d+ )? $ /// , options Form.validators.regexp options Form.validators.errMessages.minlength = _.template 'The minimum length is <%= minlength %> characters', null, Form.templateSettings Form.validators.minlength = (options) -> options = _.extend type: 'minlength' maxlength: 0 message: Form.validators.errMessages.minlength , options options.regexp = new RegExp "^.{#{ options.minlength },}$" Form.validators.regexp options Form.validators.errMessages.maxlength = _.template 'The maximum length is <%= maxlength %> characters', null, Form.templateSettings Form.validators.maxlength = (options) -> options = _.extend type: 'maxlength' maxlength: 0 message: Form.validators.errMessages.maxlength , options options.regexp = new RegExp "^.{0,#{ options.maxlength }}$" Form.validators.regexp options Form.validators.errMessages.table_weights = 'Invalid control code' Form.validators.table_weights = (options) -> options = _.extend type: 'table_weights' message: Form.validators.errMessages.table_weights , options unless options.lengths? throw new Error 'Option "lengths" is required' options.lengths = [options.lengths] unless _.isArray options.lengths unless options.weights? throw new Error 'Option "weights" is required' unless options.modulo_values? and _.isArray options.modulo_values throw new Error 'Option "modulo_values" is required' if _.isArray options.weights if options.lengths.length is 1 options.weights = _.object [options.lengths[0]], [options.weights] else throw new Error 'Incorrect options weights and lengths' options.excepts = [options.excepts] unless _.isArray options.excepts (value) -> value = null if value.trim() is '' # Don't check empty values (add a 'required' validator for this) unless value? then return options.value = value err = type: options.type, message: options.message value = value.replace /[\s-]/g, '' if value in options.excepts then return err value = value.split '' unless value.length in options.lengths then return err control = value.pop() sum = _.reduce _.zip(value, options.weights[value.length + 1]), (memo, val) -> memo + val[1] * parseInt val[0], 10 , 0 value = '' + options.modulo_values[sum % options.modulo_values.length] unless value is control then err return
140303
### Backbone-Forms validators 1.0.1 Copyright (c) 2016 <NAME> https://github.com/tomi77/backbone-forms-validators Released under the MIT license ### ((root, factory) -> ### istanbul ignore next ### switch when typeof define is 'function' and define.amd define ['underscore', 'backbone-forms'], factory when typeof exports is 'object' factory require('underscore'), require('backbone-forms') else factory root._, root.Backbone.Form return ) @, (_, Form) -> Form.validators.multiple = (options) -> options = _.extend separator: ';' , options base_validator = Form.validators[options.base_type] options (value) -> value = null if value.trim() is '' # Don't check empty values (add a 'required' validator for this) unless value? then return options.value = value value = value.split(options.separator).map (email) -> email.trim() out = _.compact _.map value, base_validator if out.length > 0 type: options.base_type message: options.message or out[0].message Form.validators.errMessages.phone = 'Incorrect phone number' Form.validators.phone = (options) -> options = _.extend type: 'phone' message: Form.validators.errMessages.phone regexp: /// ^ (?: (?: \(? (?: 00 | \+ ) (?: [1-4]\d{2} | [1-9]\d? ) \)? )? [\-\.\ \\\/]? )? (?: \(? \d+ \)? [\-\.\ \\\/]? )+ (?: [\-\.\ \\\/]? (?: \# | ext\.? | extension | x ) [\-\.\ \\\/]? \d+ )? $ /// , options Form.validators.regexp options Form.validators.errMessages.minlength = _.template 'The minimum length is <%= minlength %> characters', null, Form.templateSettings Form.validators.minlength = (options) -> options = _.extend type: 'minlength' maxlength: 0 message: Form.validators.errMessages.minlength , options options.regexp = new RegExp "^.{#{ options.minlength },}$" Form.validators.regexp options Form.validators.errMessages.maxlength = _.template 'The maximum length is <%= maxlength %> characters', null, Form.templateSettings Form.validators.maxlength = (options) -> options = _.extend type: 'maxlength' maxlength: 0 message: Form.validators.errMessages.maxlength , options options.regexp = new RegExp "^.{0,#{ options.maxlength }}$" Form.validators.regexp options Form.validators.errMessages.table_weights = 'Invalid control code' Form.validators.table_weights = (options) -> options = _.extend type: 'table_weights' message: Form.validators.errMessages.table_weights , options unless options.lengths? throw new Error 'Option "lengths" is required' options.lengths = [options.lengths] unless _.isArray options.lengths unless options.weights? throw new Error 'Option "weights" is required' unless options.modulo_values? and _.isArray options.modulo_values throw new Error 'Option "modulo_values" is required' if _.isArray options.weights if options.lengths.length is 1 options.weights = _.object [options.lengths[0]], [options.weights] else throw new Error 'Incorrect options weights and lengths' options.excepts = [options.excepts] unless _.isArray options.excepts (value) -> value = null if value.trim() is '' # Don't check empty values (add a 'required' validator for this) unless value? then return options.value = value err = type: options.type, message: options.message value = value.replace /[\s-]/g, '' if value in options.excepts then return err value = value.split '' unless value.length in options.lengths then return err control = value.pop() sum = _.reduce _.zip(value, options.weights[value.length + 1]), (memo, val) -> memo + val[1] * parseInt val[0], 10 , 0 value = '' + options.modulo_values[sum % options.modulo_values.length] unless value is control then err return
true
### Backbone-Forms validators 1.0.1 Copyright (c) 2016 PI:NAME:<NAME>END_PI https://github.com/tomi77/backbone-forms-validators Released under the MIT license ### ((root, factory) -> ### istanbul ignore next ### switch when typeof define is 'function' and define.amd define ['underscore', 'backbone-forms'], factory when typeof exports is 'object' factory require('underscore'), require('backbone-forms') else factory root._, root.Backbone.Form return ) @, (_, Form) -> Form.validators.multiple = (options) -> options = _.extend separator: ';' , options base_validator = Form.validators[options.base_type] options (value) -> value = null if value.trim() is '' # Don't check empty values (add a 'required' validator for this) unless value? then return options.value = value value = value.split(options.separator).map (email) -> email.trim() out = _.compact _.map value, base_validator if out.length > 0 type: options.base_type message: options.message or out[0].message Form.validators.errMessages.phone = 'Incorrect phone number' Form.validators.phone = (options) -> options = _.extend type: 'phone' message: Form.validators.errMessages.phone regexp: /// ^ (?: (?: \(? (?: 00 | \+ ) (?: [1-4]\d{2} | [1-9]\d? ) \)? )? [\-\.\ \\\/]? )? (?: \(? \d+ \)? [\-\.\ \\\/]? )+ (?: [\-\.\ \\\/]? (?: \# | ext\.? | extension | x ) [\-\.\ \\\/]? \d+ )? $ /// , options Form.validators.regexp options Form.validators.errMessages.minlength = _.template 'The minimum length is <%= minlength %> characters', null, Form.templateSettings Form.validators.minlength = (options) -> options = _.extend type: 'minlength' maxlength: 0 message: Form.validators.errMessages.minlength , options options.regexp = new RegExp "^.{#{ options.minlength },}$" Form.validators.regexp options Form.validators.errMessages.maxlength = _.template 'The maximum length is <%= maxlength %> characters', null, Form.templateSettings Form.validators.maxlength = (options) -> options = _.extend type: 'maxlength' maxlength: 0 message: Form.validators.errMessages.maxlength , options options.regexp = new RegExp "^.{0,#{ options.maxlength }}$" Form.validators.regexp options Form.validators.errMessages.table_weights = 'Invalid control code' Form.validators.table_weights = (options) -> options = _.extend type: 'table_weights' message: Form.validators.errMessages.table_weights , options unless options.lengths? throw new Error 'Option "lengths" is required' options.lengths = [options.lengths] unless _.isArray options.lengths unless options.weights? throw new Error 'Option "weights" is required' unless options.modulo_values? and _.isArray options.modulo_values throw new Error 'Option "modulo_values" is required' if _.isArray options.weights if options.lengths.length is 1 options.weights = _.object [options.lengths[0]], [options.weights] else throw new Error 'Incorrect options weights and lengths' options.excepts = [options.excepts] unless _.isArray options.excepts (value) -> value = null if value.trim() is '' # Don't check empty values (add a 'required' validator for this) unless value? then return options.value = value err = type: options.type, message: options.message value = value.replace /[\s-]/g, '' if value in options.excepts then return err value = value.split '' unless value.length in options.lengths then return err control = value.pop() sum = _.reduce _.zip(value, options.weights[value.length + 1]), (memo, val) -> memo + val[1] * parseInt val[0], 10 , 0 value = '' + options.modulo_values[sum % options.modulo_values.length] unless value is control then err return
[ { "context": "Config:\n uuid: 'some-uuid'\n token: 'some-token'\n hostname: 'localhost'\n protocol: ", "end": 440, "score": 0.6018934845924377, "start": 430, "tag": "PASSWORD", "value": "some-token" } ]
test/simple-meshblu-message-as-spec.coffee
octoblu/simple-meshblu-message-as
0
{describe,beforeEach,afterEach,it,expect} = global enableDestroy = require 'server-destroy' shmock = require '@octoblu/shmock' SimpleMeshbluMessageAs = require '../' describe 'SimpleMeshbluMessageAs', -> beforeEach -> @meshblu = shmock() enableDestroy(@meshblu) @meshbluPort = @meshblu.address().port @sut = new SimpleMeshbluMessageAs { meshbluConfig: uuid: 'some-uuid' token: 'some-token' hostname: 'localhost' protocol: 'http' port: @meshbluPort } afterEach -> @meshblu.destroy() describe '->send', -> describe 'when called with a message and an as', -> beforeEach (done) -> userAuth = new Buffer('some-uuid:some-token').toString('base64') messageAuth = new Buffer('send-as-me:some-new-token').toString('base64') message = devices: ['*'] topic: 'test' @generateToken = @meshblu.post '/devices/send-as-me/tokens' .set 'Authorization', "Basic #{userAuth}" .reply 201, { token: 'some-new-token' } @sendMessage = @meshblu.post '/messages' .set 'Authorization', "Basic #{messageAuth}" .send message .reply 204 @revokeToken = @meshblu.delete '/devices/send-as-me/tokens/some-new-token' .set 'Authorization', "Basic #{userAuth}" .reply 204 @sut.send { message, as: 'send-as-me' }, done it 'should send the message', -> @sendMessage.done() it 'should generate a token', -> @generateToken.done() it 'should revoke the token', -> @revokeToken.done() describe 'when called without a message', -> beforeEach (done) -> @sut.send { as: 'send-as-me' }, (@error) => done() it 'should have an error', -> expect(@error).to.exist expect(@error.message).to.equal 'SimpleMeshbluMessageAs: send requires message' describe 'when called without as', -> beforeEach (done) -> @sut.send { message: 'some-message', }, (@error) => done() it 'should have an error', -> expect(@error).to.exist expect(@error.message).to.equal 'SimpleMeshbluMessageAs: send requires as' describe '->sendWith', -> describe 'when called with a message and a uuid / token', -> beforeEach (done) -> messageAuth = new Buffer('send-as-me:some-other-token').toString('base64') message = devices: ['*'] topic: 'test' @sendMessage = @meshblu.post '/messages' .set 'Authorization', "Basic #{messageAuth}" .send message .reply 204 @sut.sendWith { message, uuid: 'send-as-me', token: 'some-other-token' }, done it 'should send the message', -> @sendMessage.done() describe 'when called without a message', -> beforeEach (done) -> @sut.sendWith { uuid: 'send-as-me', token: 'some-other-token' }, (@error) => done() it 'should have an error', -> expect(@error).to.exist expect(@error.message).to.equal 'SimpleMeshbluMessageAs: sendWith requires message' describe 'when called without uuid', -> beforeEach (done) -> @sut.sendWith { message: 'some-message', token: 'some-other-token' }, (@error) => done() it 'should have an error', -> expect(@error).to.exist expect(@error.message).to.equal 'SimpleMeshbluMessageAs: sendWith requires uuid' describe 'when called without token', -> beforeEach (done) -> @sut.sendWith { message: 'some-message', uuid: 'send-as-me' }, (@error) => done() it 'should have an error', -> expect(@error).to.exist expect(@error.message).to.equal 'SimpleMeshbluMessageAs: sendWith requires token'
4272
{describe,beforeEach,afterEach,it,expect} = global enableDestroy = require 'server-destroy' shmock = require '@octoblu/shmock' SimpleMeshbluMessageAs = require '../' describe 'SimpleMeshbluMessageAs', -> beforeEach -> @meshblu = shmock() enableDestroy(@meshblu) @meshbluPort = @meshblu.address().port @sut = new SimpleMeshbluMessageAs { meshbluConfig: uuid: 'some-uuid' token: '<PASSWORD>' hostname: 'localhost' protocol: 'http' port: @meshbluPort } afterEach -> @meshblu.destroy() describe '->send', -> describe 'when called with a message and an as', -> beforeEach (done) -> userAuth = new Buffer('some-uuid:some-token').toString('base64') messageAuth = new Buffer('send-as-me:some-new-token').toString('base64') message = devices: ['*'] topic: 'test' @generateToken = @meshblu.post '/devices/send-as-me/tokens' .set 'Authorization', "Basic #{userAuth}" .reply 201, { token: 'some-new-token' } @sendMessage = @meshblu.post '/messages' .set 'Authorization', "Basic #{messageAuth}" .send message .reply 204 @revokeToken = @meshblu.delete '/devices/send-as-me/tokens/some-new-token' .set 'Authorization', "Basic #{userAuth}" .reply 204 @sut.send { message, as: 'send-as-me' }, done it 'should send the message', -> @sendMessage.done() it 'should generate a token', -> @generateToken.done() it 'should revoke the token', -> @revokeToken.done() describe 'when called without a message', -> beforeEach (done) -> @sut.send { as: 'send-as-me' }, (@error) => done() it 'should have an error', -> expect(@error).to.exist expect(@error.message).to.equal 'SimpleMeshbluMessageAs: send requires message' describe 'when called without as', -> beforeEach (done) -> @sut.send { message: 'some-message', }, (@error) => done() it 'should have an error', -> expect(@error).to.exist expect(@error.message).to.equal 'SimpleMeshbluMessageAs: send requires as' describe '->sendWith', -> describe 'when called with a message and a uuid / token', -> beforeEach (done) -> messageAuth = new Buffer('send-as-me:some-other-token').toString('base64') message = devices: ['*'] topic: 'test' @sendMessage = @meshblu.post '/messages' .set 'Authorization', "Basic #{messageAuth}" .send message .reply 204 @sut.sendWith { message, uuid: 'send-as-me', token: 'some-other-token' }, done it 'should send the message', -> @sendMessage.done() describe 'when called without a message', -> beforeEach (done) -> @sut.sendWith { uuid: 'send-as-me', token: 'some-other-token' }, (@error) => done() it 'should have an error', -> expect(@error).to.exist expect(@error.message).to.equal 'SimpleMeshbluMessageAs: sendWith requires message' describe 'when called without uuid', -> beforeEach (done) -> @sut.sendWith { message: 'some-message', token: 'some-other-token' }, (@error) => done() it 'should have an error', -> expect(@error).to.exist expect(@error.message).to.equal 'SimpleMeshbluMessageAs: sendWith requires uuid' describe 'when called without token', -> beforeEach (done) -> @sut.sendWith { message: 'some-message', uuid: 'send-as-me' }, (@error) => done() it 'should have an error', -> expect(@error).to.exist expect(@error.message).to.equal 'SimpleMeshbluMessageAs: sendWith requires token'
true
{describe,beforeEach,afterEach,it,expect} = global enableDestroy = require 'server-destroy' shmock = require '@octoblu/shmock' SimpleMeshbluMessageAs = require '../' describe 'SimpleMeshbluMessageAs', -> beforeEach -> @meshblu = shmock() enableDestroy(@meshblu) @meshbluPort = @meshblu.address().port @sut = new SimpleMeshbluMessageAs { meshbluConfig: uuid: 'some-uuid' token: 'PI:PASSWORD:<PASSWORD>END_PI' hostname: 'localhost' protocol: 'http' port: @meshbluPort } afterEach -> @meshblu.destroy() describe '->send', -> describe 'when called with a message and an as', -> beforeEach (done) -> userAuth = new Buffer('some-uuid:some-token').toString('base64') messageAuth = new Buffer('send-as-me:some-new-token').toString('base64') message = devices: ['*'] topic: 'test' @generateToken = @meshblu.post '/devices/send-as-me/tokens' .set 'Authorization', "Basic #{userAuth}" .reply 201, { token: 'some-new-token' } @sendMessage = @meshblu.post '/messages' .set 'Authorization', "Basic #{messageAuth}" .send message .reply 204 @revokeToken = @meshblu.delete '/devices/send-as-me/tokens/some-new-token' .set 'Authorization', "Basic #{userAuth}" .reply 204 @sut.send { message, as: 'send-as-me' }, done it 'should send the message', -> @sendMessage.done() it 'should generate a token', -> @generateToken.done() it 'should revoke the token', -> @revokeToken.done() describe 'when called without a message', -> beforeEach (done) -> @sut.send { as: 'send-as-me' }, (@error) => done() it 'should have an error', -> expect(@error).to.exist expect(@error.message).to.equal 'SimpleMeshbluMessageAs: send requires message' describe 'when called without as', -> beforeEach (done) -> @sut.send { message: 'some-message', }, (@error) => done() it 'should have an error', -> expect(@error).to.exist expect(@error.message).to.equal 'SimpleMeshbluMessageAs: send requires as' describe '->sendWith', -> describe 'when called with a message and a uuid / token', -> beforeEach (done) -> messageAuth = new Buffer('send-as-me:some-other-token').toString('base64') message = devices: ['*'] topic: 'test' @sendMessage = @meshblu.post '/messages' .set 'Authorization', "Basic #{messageAuth}" .send message .reply 204 @sut.sendWith { message, uuid: 'send-as-me', token: 'some-other-token' }, done it 'should send the message', -> @sendMessage.done() describe 'when called without a message', -> beforeEach (done) -> @sut.sendWith { uuid: 'send-as-me', token: 'some-other-token' }, (@error) => done() it 'should have an error', -> expect(@error).to.exist expect(@error.message).to.equal 'SimpleMeshbluMessageAs: sendWith requires message' describe 'when called without uuid', -> beforeEach (done) -> @sut.sendWith { message: 'some-message', token: 'some-other-token' }, (@error) => done() it 'should have an error', -> expect(@error).to.exist expect(@error.message).to.equal 'SimpleMeshbluMessageAs: sendWith requires uuid' describe 'when called without token', -> beforeEach (done) -> @sut.sendWith { message: 'some-message', uuid: 'send-as-me' }, (@error) => done() it 'should have an error', -> expect(@error).to.exist expect(@error.message).to.equal 'SimpleMeshbluMessageAs: sendWith requires token'
[ { "context": "get \"local_couchdb_admin_username\"\n password: Coconut.config.get \"local_couchdb_admin_password\"\n success: ->\n", "end": 7871, "score": 0.9882168173789978, "start": 7853, "tag": "PASSWORD", "value": "Coconut.config.get" } ]
_attachments/models/Sync.coffee
ICTatRTI/coconut-cloud
2
class Sync extends Backbone.Model initialize: -> @set _id: "SyncLog" url: "/sync" target: -> Coconut.config.cloud_url() last_send: => return @get("last_send_result") was_last_send_successful: => return false if @get("last_send_error") is true # even if last_send_error was false need to check log last_send_data = @last_send() return false unless last_send_data? return true if last_send_data.no_changes? and last_send_data.no_changes is true return (last_send_data.docs_read is last_send_data.docs_written) and last_send_data.doc_write_failures is 0 last_send_time: => result = @get("last_send_time") if result return moment(@get("last_send_time")).fromNow() else return "never" was_last_get_successful: => return @get "last_get_success" last_get_time: => result = @get("last_get_time") if result return moment(@get("last_get_time")).fromNow() else return "never" sendToCloud: (options) -> @fetch error: (error) => @log "Unable to fetch Sync doc: #{JSON.stringify(error)}" success: => @log "Checking for internet. (Is #{Coconut.config.cloud_url()} is reachable?) Please wait." $.ajax dataType: "jsonp" url: Coconut.config.cloud_url() error: (error) => @log "ERROR! #{Coconut.config.cloud_url()} is not reachable. Do you have enough airtime? Are you on WIFI? Either the internet is not working or the site is down: #{JSON.stringify(error)}" options.error() @save last_send_error: true success: => @log "#{Coconut.config.cloud_url()} is reachable, so internet is available." @log "Creating list of all results on the tablet. Please wait." $.couch.db(Coconut.config.database_name()).view "#{Coconut.config.design_doc_name()}/results", include_docs: false error: (result) => @log "Could not retrieve list of results: #{JSON.stringify(error)}" options.error() @save last_send_error: true success: (result) => @log "Synchronizing #{result.rows.length} results. Please wait." resultIDs = _.pluck result.rows, "id" $.couch.db(Coconut.config.database_name()).saveDoc collection: "log" action: "sendToCloud" user: User.currentUser.id time: moment().format(Coconut.config.get "date_format") , error: (error) => @log "Could not create log file: #{JSON.stringify(error)}" success: => $.couch.replicate( Coconut.config.database_name(), Coconut.config.cloud_url_with_credentials(), success: (result) => @log "Send data finished: created, updated or deleted #{result.docs_written} results on the server." @save last_send_result: result last_send_error: false last_send_time: new Date().getTime() @sendLogMessagesToCloud success: -> options.success() error: (error) -> @save last_send_error: true options.error(error) , doc_ids: resultIDs ) Coconut.menuView.checkReplicationStatus() log: (message) => Coconut.debug message # @save # last_get_log: @get("last_get_log") + message sendLogMessagesToCloud: (options) -> @fetch error: (error) => @log "Unable to fetch Sync doc: #{JSON.stringify(error)}" success: => $.couch.db(Coconut.config.database_name()).view "#{Coconut.config.design_doc_name()}/byCollection", key: "log" include_docs: false error: (error) => @log "Could not retrieve list of log entries: #{JSON.stringify(error)}" options.error(error) @save last_send_error: true success: (result) => @log "Sending #{result.rows.length} log entries. Please wait." logIDs = _.pluck result.rows, "id" $.couch.replicate( Coconut.config.database_name(), Coconut.config.cloud_url_with_credentials(), success: (result) => @save last_send_result: result last_send_error: false last_send_time: new Date().getTime() @log "Successfully sent #{result.docs_written} log messages to the server." options.success() error: (error) => @log "Could not send log messages to the server: #{JSON.stringify(error)}" @save last_send_error: true options.error?(error) , doc_ids: logIDs ) Coconut.menuView.checkReplicationStatus() getFromCloud: (options) => @fetch error: (error) => @log "Unable to fetch Sync doc: #{JSON.stringify(error)}" success: => @log "Checking that #{Coconut.config.cloud_url()} is reachable. Please wait." $.ajax dataType: "jsonp" url: Coconut.config.cloud_url() error: (error) => @log "ERROR! #{Coconut.config.cloud_url()} is not reachable. Do you have enough airtime? Are you on WIFI? Either the internet is not working or the site is down: #{JSON.stringify(error)}" options.error?(error) success: => @log "#{Coconut.config.cloud_url()} is reachable, so internet is available." @fetch success: => @log "Updating users, forms and the design document. Please wait." @replicateApplicationDocs error: (error) => $.couch.logout() @log "ERROR updating application: #{JSON.stringify(error)}" @save last_get_success: false options?.error?(error) success: => $.couch.logout() $.couch.db(Coconut.config.database_name()).saveDoc collection: "log" action: "getFromCloud" user: User.currentUser.id time: moment().format(Coconut.config.get "date_format") , error: (error) => @log "Could not create log file #{JSON.stringify(error)}" success: => @log "Sending log messages to cloud." @sendLogMessagesToCloud success: => @log "Finished, refreshing app in 5 seconds..." @fetch error: (error) => @log "Unable to fetch Sync doc: #{JSON.stringify(error)}" success: => @save last_get_success: true last_get_time: new Date().getTime() options?.success?() _.delay -> document.location.reload() , 5000 replicate: (options) -> $.couch.login name: Coconut.config.get "local_couchdb_admin_username" password: Coconut.config.get "local_couchdb_admin_password" success: -> $.couch.replicate( Coconut.config.cloud_url_with_credentials(), Coconut.config.database_name(), success: -> options.success() error: -> options.error() , options.replicationArguments ) Coconut.menuView.checkReplicationStatus() error: -> console.log "Unable to login as local admin for replicating the design document (main application)" replicateApplicationDocs: (options) => # Updating design_doc, users & forms $.ajax dataType: "jsonp" # version file is missing url: "#{Coconut.config.cloud_url_with_credentials()}/_design/#{Coconut.config.design_doc_name()}/_view/docIDsForUpdating" include_docs: false error: (a,b,error) => options.error?(error) success: (result) => doc_ids = _.pluck result.rows, "id" # Not needed since design_doc has option to index itself and is marked as applicationDoc doc_ids.push "_design/#{Coconut.config.design_doc_name()}" @log "Updating #{doc_ids.length} docs (users, forms and the design document). Please wait." @replicate _.extend options, replicationArguments: doc_ids: doc_ids
31124
class Sync extends Backbone.Model initialize: -> @set _id: "SyncLog" url: "/sync" target: -> Coconut.config.cloud_url() last_send: => return @get("last_send_result") was_last_send_successful: => return false if @get("last_send_error") is true # even if last_send_error was false need to check log last_send_data = @last_send() return false unless last_send_data? return true if last_send_data.no_changes? and last_send_data.no_changes is true return (last_send_data.docs_read is last_send_data.docs_written) and last_send_data.doc_write_failures is 0 last_send_time: => result = @get("last_send_time") if result return moment(@get("last_send_time")).fromNow() else return "never" was_last_get_successful: => return @get "last_get_success" last_get_time: => result = @get("last_get_time") if result return moment(@get("last_get_time")).fromNow() else return "never" sendToCloud: (options) -> @fetch error: (error) => @log "Unable to fetch Sync doc: #{JSON.stringify(error)}" success: => @log "Checking for internet. (Is #{Coconut.config.cloud_url()} is reachable?) Please wait." $.ajax dataType: "jsonp" url: Coconut.config.cloud_url() error: (error) => @log "ERROR! #{Coconut.config.cloud_url()} is not reachable. Do you have enough airtime? Are you on WIFI? Either the internet is not working or the site is down: #{JSON.stringify(error)}" options.error() @save last_send_error: true success: => @log "#{Coconut.config.cloud_url()} is reachable, so internet is available." @log "Creating list of all results on the tablet. Please wait." $.couch.db(Coconut.config.database_name()).view "#{Coconut.config.design_doc_name()}/results", include_docs: false error: (result) => @log "Could not retrieve list of results: #{JSON.stringify(error)}" options.error() @save last_send_error: true success: (result) => @log "Synchronizing #{result.rows.length} results. Please wait." resultIDs = _.pluck result.rows, "id" $.couch.db(Coconut.config.database_name()).saveDoc collection: "log" action: "sendToCloud" user: User.currentUser.id time: moment().format(Coconut.config.get "date_format") , error: (error) => @log "Could not create log file: #{JSON.stringify(error)}" success: => $.couch.replicate( Coconut.config.database_name(), Coconut.config.cloud_url_with_credentials(), success: (result) => @log "Send data finished: created, updated or deleted #{result.docs_written} results on the server." @save last_send_result: result last_send_error: false last_send_time: new Date().getTime() @sendLogMessagesToCloud success: -> options.success() error: (error) -> @save last_send_error: true options.error(error) , doc_ids: resultIDs ) Coconut.menuView.checkReplicationStatus() log: (message) => Coconut.debug message # @save # last_get_log: @get("last_get_log") + message sendLogMessagesToCloud: (options) -> @fetch error: (error) => @log "Unable to fetch Sync doc: #{JSON.stringify(error)}" success: => $.couch.db(Coconut.config.database_name()).view "#{Coconut.config.design_doc_name()}/byCollection", key: "log" include_docs: false error: (error) => @log "Could not retrieve list of log entries: #{JSON.stringify(error)}" options.error(error) @save last_send_error: true success: (result) => @log "Sending #{result.rows.length} log entries. Please wait." logIDs = _.pluck result.rows, "id" $.couch.replicate( Coconut.config.database_name(), Coconut.config.cloud_url_with_credentials(), success: (result) => @save last_send_result: result last_send_error: false last_send_time: new Date().getTime() @log "Successfully sent #{result.docs_written} log messages to the server." options.success() error: (error) => @log "Could not send log messages to the server: #{JSON.stringify(error)}" @save last_send_error: true options.error?(error) , doc_ids: logIDs ) Coconut.menuView.checkReplicationStatus() getFromCloud: (options) => @fetch error: (error) => @log "Unable to fetch Sync doc: #{JSON.stringify(error)}" success: => @log "Checking that #{Coconut.config.cloud_url()} is reachable. Please wait." $.ajax dataType: "jsonp" url: Coconut.config.cloud_url() error: (error) => @log "ERROR! #{Coconut.config.cloud_url()} is not reachable. Do you have enough airtime? Are you on WIFI? Either the internet is not working or the site is down: #{JSON.stringify(error)}" options.error?(error) success: => @log "#{Coconut.config.cloud_url()} is reachable, so internet is available." @fetch success: => @log "Updating users, forms and the design document. Please wait." @replicateApplicationDocs error: (error) => $.couch.logout() @log "ERROR updating application: #{JSON.stringify(error)}" @save last_get_success: false options?.error?(error) success: => $.couch.logout() $.couch.db(Coconut.config.database_name()).saveDoc collection: "log" action: "getFromCloud" user: User.currentUser.id time: moment().format(Coconut.config.get "date_format") , error: (error) => @log "Could not create log file #{JSON.stringify(error)}" success: => @log "Sending log messages to cloud." @sendLogMessagesToCloud success: => @log "Finished, refreshing app in 5 seconds..." @fetch error: (error) => @log "Unable to fetch Sync doc: #{JSON.stringify(error)}" success: => @save last_get_success: true last_get_time: new Date().getTime() options?.success?() _.delay -> document.location.reload() , 5000 replicate: (options) -> $.couch.login name: Coconut.config.get "local_couchdb_admin_username" password: <PASSWORD> "local_couchdb_admin_password" success: -> $.couch.replicate( Coconut.config.cloud_url_with_credentials(), Coconut.config.database_name(), success: -> options.success() error: -> options.error() , options.replicationArguments ) Coconut.menuView.checkReplicationStatus() error: -> console.log "Unable to login as local admin for replicating the design document (main application)" replicateApplicationDocs: (options) => # Updating design_doc, users & forms $.ajax dataType: "jsonp" # version file is missing url: "#{Coconut.config.cloud_url_with_credentials()}/_design/#{Coconut.config.design_doc_name()}/_view/docIDsForUpdating" include_docs: false error: (a,b,error) => options.error?(error) success: (result) => doc_ids = _.pluck result.rows, "id" # Not needed since design_doc has option to index itself and is marked as applicationDoc doc_ids.push "_design/#{Coconut.config.design_doc_name()}" @log "Updating #{doc_ids.length} docs (users, forms and the design document). Please wait." @replicate _.extend options, replicationArguments: doc_ids: doc_ids
true
class Sync extends Backbone.Model initialize: -> @set _id: "SyncLog" url: "/sync" target: -> Coconut.config.cloud_url() last_send: => return @get("last_send_result") was_last_send_successful: => return false if @get("last_send_error") is true # even if last_send_error was false need to check log last_send_data = @last_send() return false unless last_send_data? return true if last_send_data.no_changes? and last_send_data.no_changes is true return (last_send_data.docs_read is last_send_data.docs_written) and last_send_data.doc_write_failures is 0 last_send_time: => result = @get("last_send_time") if result return moment(@get("last_send_time")).fromNow() else return "never" was_last_get_successful: => return @get "last_get_success" last_get_time: => result = @get("last_get_time") if result return moment(@get("last_get_time")).fromNow() else return "never" sendToCloud: (options) -> @fetch error: (error) => @log "Unable to fetch Sync doc: #{JSON.stringify(error)}" success: => @log "Checking for internet. (Is #{Coconut.config.cloud_url()} is reachable?) Please wait." $.ajax dataType: "jsonp" url: Coconut.config.cloud_url() error: (error) => @log "ERROR! #{Coconut.config.cloud_url()} is not reachable. Do you have enough airtime? Are you on WIFI? Either the internet is not working or the site is down: #{JSON.stringify(error)}" options.error() @save last_send_error: true success: => @log "#{Coconut.config.cloud_url()} is reachable, so internet is available." @log "Creating list of all results on the tablet. Please wait." $.couch.db(Coconut.config.database_name()).view "#{Coconut.config.design_doc_name()}/results", include_docs: false error: (result) => @log "Could not retrieve list of results: #{JSON.stringify(error)}" options.error() @save last_send_error: true success: (result) => @log "Synchronizing #{result.rows.length} results. Please wait." resultIDs = _.pluck result.rows, "id" $.couch.db(Coconut.config.database_name()).saveDoc collection: "log" action: "sendToCloud" user: User.currentUser.id time: moment().format(Coconut.config.get "date_format") , error: (error) => @log "Could not create log file: #{JSON.stringify(error)}" success: => $.couch.replicate( Coconut.config.database_name(), Coconut.config.cloud_url_with_credentials(), success: (result) => @log "Send data finished: created, updated or deleted #{result.docs_written} results on the server." @save last_send_result: result last_send_error: false last_send_time: new Date().getTime() @sendLogMessagesToCloud success: -> options.success() error: (error) -> @save last_send_error: true options.error(error) , doc_ids: resultIDs ) Coconut.menuView.checkReplicationStatus() log: (message) => Coconut.debug message # @save # last_get_log: @get("last_get_log") + message sendLogMessagesToCloud: (options) -> @fetch error: (error) => @log "Unable to fetch Sync doc: #{JSON.stringify(error)}" success: => $.couch.db(Coconut.config.database_name()).view "#{Coconut.config.design_doc_name()}/byCollection", key: "log" include_docs: false error: (error) => @log "Could not retrieve list of log entries: #{JSON.stringify(error)}" options.error(error) @save last_send_error: true success: (result) => @log "Sending #{result.rows.length} log entries. Please wait." logIDs = _.pluck result.rows, "id" $.couch.replicate( Coconut.config.database_name(), Coconut.config.cloud_url_with_credentials(), success: (result) => @save last_send_result: result last_send_error: false last_send_time: new Date().getTime() @log "Successfully sent #{result.docs_written} log messages to the server." options.success() error: (error) => @log "Could not send log messages to the server: #{JSON.stringify(error)}" @save last_send_error: true options.error?(error) , doc_ids: logIDs ) Coconut.menuView.checkReplicationStatus() getFromCloud: (options) => @fetch error: (error) => @log "Unable to fetch Sync doc: #{JSON.stringify(error)}" success: => @log "Checking that #{Coconut.config.cloud_url()} is reachable. Please wait." $.ajax dataType: "jsonp" url: Coconut.config.cloud_url() error: (error) => @log "ERROR! #{Coconut.config.cloud_url()} is not reachable. Do you have enough airtime? Are you on WIFI? Either the internet is not working or the site is down: #{JSON.stringify(error)}" options.error?(error) success: => @log "#{Coconut.config.cloud_url()} is reachable, so internet is available." @fetch success: => @log "Updating users, forms and the design document. Please wait." @replicateApplicationDocs error: (error) => $.couch.logout() @log "ERROR updating application: #{JSON.stringify(error)}" @save last_get_success: false options?.error?(error) success: => $.couch.logout() $.couch.db(Coconut.config.database_name()).saveDoc collection: "log" action: "getFromCloud" user: User.currentUser.id time: moment().format(Coconut.config.get "date_format") , error: (error) => @log "Could not create log file #{JSON.stringify(error)}" success: => @log "Sending log messages to cloud." @sendLogMessagesToCloud success: => @log "Finished, refreshing app in 5 seconds..." @fetch error: (error) => @log "Unable to fetch Sync doc: #{JSON.stringify(error)}" success: => @save last_get_success: true last_get_time: new Date().getTime() options?.success?() _.delay -> document.location.reload() , 5000 replicate: (options) -> $.couch.login name: Coconut.config.get "local_couchdb_admin_username" password: PI:PASSWORD:<PASSWORD>END_PI "local_couchdb_admin_password" success: -> $.couch.replicate( Coconut.config.cloud_url_with_credentials(), Coconut.config.database_name(), success: -> options.success() error: -> options.error() , options.replicationArguments ) Coconut.menuView.checkReplicationStatus() error: -> console.log "Unable to login as local admin for replicating the design document (main application)" replicateApplicationDocs: (options) => # Updating design_doc, users & forms $.ajax dataType: "jsonp" # version file is missing url: "#{Coconut.config.cloud_url_with_credentials()}/_design/#{Coconut.config.design_doc_name()}/_view/docIDsForUpdating" include_docs: false error: (a,b,error) => options.error?(error) success: (result) => doc_ids = _.pluck result.rows, "id" # Not needed since design_doc has option to index itself and is marked as applicationDoc doc_ids.push "_design/#{Coconut.config.design_doc_name()}" @log "Updating #{doc_ids.length} docs (users, forms and the design document). Please wait." @replicate _.extend options, replicationArguments: doc_ids: doc_ids
[ { "context": "\n links = [{bucket: \"users\", tag: \"owner\", key: \"anton\"}, {bucket: \"users\", tag: \"modifier\", key: \"andre", "end": 144, "score": 0.7361683249473572, "start": 139, "tag": "USERNAME", "value": "anton" }, { "context": "anton\"}, {bucket: \"users\", tag: \"modifier\", key: \"andrew\"}]\n it \"should find link for correct parameter\",", "end": 195, "score": 0.7905713319778442, "start": 189, "tag": "NAME", "value": "andrew" }, { "context": " should.equal utils.getLink(links, \"modifier\"), \"andrew\"\n should.equal utils.getLink(links, \"owner\"), ", "end": 307, "score": 0.9775809049606323, "start": 301, "tag": "NAME", "value": "andrew" }, { "context": "links = [{bucket: \"users\", tag: \"modifier\", key: \"peter\"},{bucket: \"users\", tag: \"owner\", key: \"anton\"}, ", "end": 568, "score": 0.8340733051300049, "start": 563, "tag": "USERNAME", "value": "peter" }, { "context": "y: \"peter\"},{bucket: \"users\", tag: \"owner\", key: \"anton\"}, {bucket: \"users\", tag: \"modifier\", key: \"and", "end": 612, "score": 0.9452729821205139, "start": 609, "tag": "USERNAME", "value": "ant" }, { "context": "\"peter\"},{bucket: \"users\", tag: \"owner\", key: \"anton\"}, {bucket: \"users\", tag: \"modifier\", key: \"andre", "end": 614, "score": 0.5380170941352844, "start": 612, "tag": "KEY", "value": "on" }, { "context": "anton\"}, {bucket: \"users\", tag: \"modifier\", key: \"andrew\"}]\n it \"should return array of links for correct", "end": 665, "score": 0.6237075328826904, "start": 659, "tag": "NAME", "value": "andrew" }, { "context": "utils.getLinks(links, \"modifier\").should.contain \"peter\"\n utils.getLinks(links, \"modifier\").should.con", "end": 851, "score": 0.9124528169631958, "start": 846, "tag": "NAME", "value": "peter" }, { "context": "utils.getLinks(links, \"modifier\").should.contain \"andrew\"\n it \"should return empty array for incorrect pa", "end": 913, "score": 0.8972891569137573, "start": 907, "tag": "NAME", "value": "andrew" }, { "context": "\", \"users\")\n link.should.have.property(\"key\", \"anton\")\n link.should.have.property(\"tag\", \"owner\")\n\n", "end": 1265, "score": 0.9915364980697632, "start": 1260, "tag": "KEY", "value": "anton" } ]
test/utils.coffee
circuithub/riak-entity
1
should = require "should" utils = require "../lib/utils" describe "utils#getLink()", -> links = [{bucket: "users", tag: "owner", key: "anton"}, {bucket: "users", tag: "modifier", key: "andrew"}] it "should find link for correct parameter", -> should.equal utils.getLink(links, "modifier"), "andrew" should.equal utils.getLink(links, "owner"), "anton" it "should return nothing for incorrect parameter", -> should.not.exist utils.getLink links, "contributor" describe "utils#getLinks()", -> links = [{bucket: "users", tag: "modifier", key: "peter"},{bucket: "users", tag: "owner", key: "anton"}, {bucket: "users", tag: "modifier", key: "andrew"}] it "should return array of links for correct parameters", -> utils.getLinks(links, "modifier").should.have.length(2) utils.getLinks(links, "modifier").should.contain "peter" utils.getLinks(links, "modifier").should.contain "andrew" it "should return empty array for incorrect parameters", -> utils.getLinks(links, "contributor").should.be.empty describe "utils#buildLink()", -> link = utils.buildLink "users", "anton", "owner" it "should return link with correct properties", -> link.should.have.property("bucket", "users") link.should.have.property("key", "anton") link.should.have.property("tag", "owner")
15522
should = require "should" utils = require "../lib/utils" describe "utils#getLink()", -> links = [{bucket: "users", tag: "owner", key: "anton"}, {bucket: "users", tag: "modifier", key: "<NAME>"}] it "should find link for correct parameter", -> should.equal utils.getLink(links, "modifier"), "<NAME>" should.equal utils.getLink(links, "owner"), "anton" it "should return nothing for incorrect parameter", -> should.not.exist utils.getLink links, "contributor" describe "utils#getLinks()", -> links = [{bucket: "users", tag: "modifier", key: "peter"},{bucket: "users", tag: "owner", key: "ant<KEY>"}, {bucket: "users", tag: "modifier", key: "<NAME>"}] it "should return array of links for correct parameters", -> utils.getLinks(links, "modifier").should.have.length(2) utils.getLinks(links, "modifier").should.contain "<NAME>" utils.getLinks(links, "modifier").should.contain "<NAME>" it "should return empty array for incorrect parameters", -> utils.getLinks(links, "contributor").should.be.empty describe "utils#buildLink()", -> link = utils.buildLink "users", "anton", "owner" it "should return link with correct properties", -> link.should.have.property("bucket", "users") link.should.have.property("key", "<KEY>") link.should.have.property("tag", "owner")
true
should = require "should" utils = require "../lib/utils" describe "utils#getLink()", -> links = [{bucket: "users", tag: "owner", key: "anton"}, {bucket: "users", tag: "modifier", key: "PI:NAME:<NAME>END_PI"}] it "should find link for correct parameter", -> should.equal utils.getLink(links, "modifier"), "PI:NAME:<NAME>END_PI" should.equal utils.getLink(links, "owner"), "anton" it "should return nothing for incorrect parameter", -> should.not.exist utils.getLink links, "contributor" describe "utils#getLinks()", -> links = [{bucket: "users", tag: "modifier", key: "peter"},{bucket: "users", tag: "owner", key: "antPI:KEY:<KEY>END_PI"}, {bucket: "users", tag: "modifier", key: "PI:NAME:<NAME>END_PI"}] it "should return array of links for correct parameters", -> utils.getLinks(links, "modifier").should.have.length(2) utils.getLinks(links, "modifier").should.contain "PI:NAME:<NAME>END_PI" utils.getLinks(links, "modifier").should.contain "PI:NAME:<NAME>END_PI" it "should return empty array for incorrect parameters", -> utils.getLinks(links, "contributor").should.be.empty describe "utils#buildLink()", -> link = utils.buildLink "users", "anton", "owner" it "should return link with correct properties", -> link.should.have.property("bucket", "users") link.should.have.property("key", "PI:KEY:<KEY>END_PI") link.should.have.property("tag", "owner")
[ { "context": "e, [x,y,z], [sp.sw,sp.sh],study['hsv'], 1.0, @fontPrac, 0x000000 )\n pracGroup.add( studyCube.", "end": 6607, "score": 0.9428519010543823, "start": 6603, "tag": "USERNAME", "value": "Prac" }, { "context": "lsHeight,sp.colsDepth],practice['hsv'], 0.6, @fontPrac )\n pracGroup = new THREE.Group()\n pracG", "end": 7449, "score": 0.9044179916381836, "start": 7445, "tag": "USERNAME", "value": "Prac" }, { "context": "e, col.name, [x,y,z], [sp.cw,sp.ch], [0,0,0], 0.0, @fontPrac, 0xFFFFFF )\n pracGroup.add( studyCube.mesh", "end": 7793, "score": 0.9993559718132019, "start": 7784, "tag": "USERNAME", "value": "@fontPrac" }, { "context": " z = plane.z\n studyCube = new Rect( 'Prin', 'Dim', col.name, key, [x,y,z], [sp.cw,sp.ch],st", "end": 8041, "score": 0.9579969644546509, "start": 8037, "tag": "NAME", "value": "Prin" }, { "context": "me, key, [x,y,z], [sp.cw,sp.ch],study['hsv'], 1.0, @fontPrac, 0x000000 )\n pracGroup.add( studyCube.me", "end": 8117, "score": 0.9994993209838867, "start": 8108, "tag": "USERNAME", "value": "@fontPrac" }, { "context": "name, name, [col.x,row.y,plane.z], [w,h],hsv, 0.7, @fontPrac, 0xFFFFFF )\n group.add( rect.mesh )\n ", "end": 9155, "score": 0.9974195957183838, "start": 9146, "tag": "USERNAME", "value": "@fontPrac" }, { "context": "name, name, [col.x,row.y,plane.z], [w,h],hsv, 0.7, @fontPrac, 0xFFFFFF )\n group.add( rect.mesh )\n ", "end": 9905, "score": 0.9972560405731201, "start": 9896, "tag": "USERNAME", "value": "@fontPrac" } ]
src/vizu/cube/CubeTh.coffee
axiom6/aug
0
import {vis} from '../../../lib/pub/draw/Vis.js' import Access from '../../../lib/pub/util/Access.js' import Build from '../../../lib/pub/util/Build.js' import Cube3D from './Cube3D.js' import Rect from './Rect.js' import * as THREE from 'three' import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js' class CubeTh @init:( batch ) -> vis.ready -> build = new Build( batch ) th = new CubeTh( build, 'CubeTh', false ) th.animate() return @load:() -> Access.local = "http://localhost:63342/aug/app/data/" Access.hosted = "https://ui-48413.firebaseapp.com/" CubeTh.FontUrl = "../../css/font/helvetiker_regular.typeface.json" CubeTh.Batch = Info: { url:'muse/Info.json', data:null, type:'Pack' } Know: { url:'muse/Know.json', data:null, type:'Pack' } Wise: { url:'muse/Wise.json', data:null, type:'Pack' } Font: { url:CubeTh.FontUrl, data:null, type:'Spec' } Access.batchRead( CubeTh.Batch, CubeTh["init"] ) return constructor:( @build, @parElem, @guiFlag ) -> @needsRender = true @stream = null # Set by subscribe() elems = @createElems( @parElem, @guiFlag ) @ikwElem = elems[0] @guiElem = elems[1] @scene = new THREE.Scene() @renderer = new THREE.WebGLRenderer( { antialias:true } ) @ikwElem.appendChild( @renderer.domElement ) [@screenWidth,@screenHeight,@aspectRatio] = @resizeScreen() # Accesses @ikwElem @renderer.setSize( @screenWidth, @screenHeight ) @renderer.setClearColor( 0x000000, 1) # 0x333F47, 1 @renderer.shadowMap.enabled = true @renderer.shadowMapSoft = true @camera = new THREE.PerspectiveCamera( 45, @aspectRatio, 1, 10000 ) @camera.position.set( 0, 6, 1500 ) @camera.lookAt( @scene.position ) @scene.add(@camera) @axes = new THREE.AxesHelper( 2 ) @scene.add( @axes ) @fontPrac = new THREE.Font( @build.batch.Font.data ) @group = @ikw() @lights() [@gui,@act] = @ui( @group, @guiElem ) if @guiFlag @controls = new OrbitControls( @camera, @renderer.domElement ) @controls.addEventListener( 'change', () => @needsRender = true ) window.addEventListener( 'resize', @resizeScreen, false ) subscribe:( stream ) -> @stream = stream @act = @createAct( @group ) @traversals = @createTraversals( @act ) @stream.subscribe( 'Select', 'Cube', (topic) => @onSelect(topic) ) return onSelect:( topic ) => # console.log( 'CubeTh.onCube()', name ) switch topic.name when 'Cube' then vis.noop() when 'Planes' then vis.noop() when 'Information' then @traversals.info() when 'Knowledge' then @traversals.know() when 'Wisdom' then @traversals.wise() when 'Dimensions' then vis.noop() when 'Embrace' then @traversals.embrace() when 'Innovate' then @traversals.innovate() when 'Encourage' then @traversals.encourage() when 'Perspectives' then vis.noop() when 'Learn' then @traversals.learn() when 'Do' then @traversals.doDo() when 'Share' then @traversals.share() else console.error( 'CubeTh.onSelect()', topic ) return deg2rad:( degree ) -> degree*(Math.PI/180) resizeScreen:() => @screenWidth = @ikwElem.clientWidth # window.innerWidth @screenHeight = @ikwElem.clientHeight # window.innerHeight @aspectRatio = @screenWidth / @screenHeight if @camera? and @renderer? @camera.aspect = @aspectRatio @camera.updateProjectionMatrix(); @renderer.setSize( @screenWidth, @screenHeight ) #console.log( "resizeScreen", { width:@screenWidth, height:@screenHeight } ) [@screenWidth,@screenHeight,@aspectRatio] space:() -> sp = {} sp.modelRatio = @aspectRatio / 2 sp.cubeSize = 144 sp.cubeWidth = sp.cubeSize * 2.0 sp.cubeHeight = sp.cubeSize * sp.modelRatio * 0.8 sp.colsHeight = sp.cubeSize * sp.modelRatio * 0.5 sp.cubeDepth = sp.cubeSize sp.cubeHalf = sp.cubeSize / 2 sp.horzSpace = sp.cubeSize * 2 / 3 sp.vertSpace = sp.horzSpace * sp.modelRatio sp.zzzzSpace = sp.horzSpace sp.colsDepth = sp.cubeSize * 3 + sp.zzzzSpace * 2 sp.x1 = sp.cubeWidth + sp.horzSpace sp.x2 = 0 sp.x3 = -sp.cubeWidth - sp.horzSpace sp.yc = sp.cubeHeight + sp.vertSpace * 2.2 sp.y1 = sp.cubeHeight + sp.vertSpace sp.y2 = 0 sp.y3 = -sp.cubeHeight - sp.vertSpace sp.z1 = sp.cubeDepth + sp.zzzzSpace sp.z2 = 0 sp.z3 = -sp.cubeDepth - sp.zzzzSpace sp.zc = 0 sp.studyWidth = sp.cubeWidth / 3 sp.studyHeight = sp.cubeHeight / 3 sp.sw = sp.studyWidth sp.sh = sp.studyHeight sp.cw = sp.studyWidth sp.ch = sp.studyHeight * 0.5 sp.sx = { center:0, west:-sp.sw, north:0, east:sp.sw, south:0 } sp.sy = { center:0, west:0, north:sp.sh, east:0, south:-sp.sh } sp.cx = { center:0, west:-sp.sw, north:0, east:sp.sw, south:0 } sp.cy = { center:0, west:0, north:sp.sh*0.5, east:0, south:-sp.sh*0.5 } sp ikw: () -> sp = @space() group = new THREE.Group() for plane in [ { name:'Info', z:sp.z1 }, { name:'Know', z:sp.z2 }, { name:'Wise', z:sp.z3 } ] for row in [ { name:'Learn', y:sp.y1 }, { name:'Do', y:sp.y2 }, { name:'Share', y:sp.y3 } ] for col in [ { name:'Embrace', x:sp.x3 }, { name:'Innovate', x:sp.x2 }, { name:'Encourage', x:sp.x1 } ] practice = @build.getPractice( row.name, col.name, plane.name ) # console.log( 'Cube.ikw()', practice.name, row.name, col.name, plane.name ) pracCube = new Cube3D( plane.name, row.name, col.name, practice.name, [col.x,row.y,plane.z], [sp.cubeWidth,sp.cubeHeight,sp.cubeDepth],practice['hsv'], 0.6, @fontPrac ) pracGroup = new THREE.Group() pracGroup.add( pracCube.mesh ) for key, study of practice when vis.isChild(key) x = col.x + sp.sx[study.dir] y = row.y + sp.sy[study.dir] z = plane.z studyCube = new Rect( plane.name, row.name, col.name, study.name, [x,y,z], [sp.sw,sp.sh],study['hsv'], 1.0, @fontPrac, 0x000000 ) pracGroup.add( studyCube.mesh ) group.add( pracGroup ) group.add( @prin() ) @convey( sp, group ) @flow( sp, group ) @conduit( sp, group ) group.material = new THREE.MeshLambertMaterial( { color:0x888888, transparent:true, opacity:0.5, side:THREE.DoubleSide } ) group.rotation.set( 0, 0, 0 ) group.position.set( 0, 0, 0 ) group.scale.set( 1, 1, 1 ) @scene.add( group ) group prin: () -> sp = @space() group = new THREE.Group() for col in [ { name:'Embrace', x:sp.x3 }, { name:'Innovate', x:sp.x2 }, { name:'Encourage', x:sp.x1 } ] practice = @build.getCol( col.name ) pracCube = new Cube3D( 'Prin', 'Dim', col.name, col.name, [col.x,sp.yc,sp.zc], [sp.cubeWidth,sp.colsHeight,sp.colsDepth],practice['hsv'], 0.6, @fontPrac ) pracGroup = new THREE.Group() pracGroup.add( pracCube.mesh ) for plane in [ { name:'Info', z:sp.z1 }, { name:'Know', z:sp.z2 }, { name:'Wise', z:sp.z3 } ] x = col.x y = sp.yc z = plane.z studyCube = new Rect( plane, 'Dim', col.name, col.name, [x,y,z], [sp.cw,sp.ch], [0,0,0], 0.0, @fontPrac, 0xFFFFFF ) pracGroup.add( studyCube.mesh ) for key, study of practice when vis.isChild(key) x = col.x + sp.cx[study.dir] y = sp.yc + sp.cy[study.dir] z = plane.z studyCube = new Rect( 'Prin', 'Dim', col.name, key, [x,y,z], [sp.cw,sp.ch],study['hsv'], 1.0, @fontPrac, 0x000000 ) pracGroup.add( studyCube.mesh ) group.add( pracGroup ) group.material = new THREE.MeshLambertMaterial( { color:0x888888, transparent:true, opacity:0.5, side:THREE.DoubleSide } ) group.rotation.set( 0, 0, 0 ) group.position.set( 0, 0, 0 ) group.scale.set( 1, 1, 1 ) @scene.add( group ) group convey:( sp, group ) -> hsv = [0,50,50] w = sp.horzSpace h = sp.studyHeight x = ( sp.cubeWidth + w ) / 2 for plane in [ { name:'Info', z:sp.z1 }, { name:'Know', z:sp.z2 }, { name:'Wise', z:sp.z3 } ] for row in [ { name:'Learn', y:sp.y1 }, { name:'Do', y:sp.y2 }, { name:'Share', y:sp.y3 } ] for col in [ { name:'Embrace', x:sp.x3+x }, { name:'Innovate', x:sp.x2+x } ] practice = @build.getPractice( row.name, col.name, plane.name ) name = @build.connectName( practice, 'east', false ) rect = new Rect( plane.name, row.name, col.name, name, [col.x,row.y,plane.z], [w,h],hsv, 0.7, @fontPrac, 0xFFFFFF ) group.add( rect.mesh ) return flow:( sp, group ) -> hsv = [0,50,50] w = sp.studyWidth h = sp.vertSpace y = ( sp.cubeHeight + h ) / 2 for plane in [ { name:'Info', z:sp.z1 }, { name:'Know', z:sp.z2 }, { name:'Wise', z:sp.z3 } ] for row in [ { name:'Learn', y:sp.y1-y}, { name:'Do', y:sp.y2-y } ] for col in [ { name:'Embrace', x:sp.x3}, { name:'Innovate', x:sp.x2 }, { name:'Encourage', x:sp.x1 } ] practice = @build.getPractice( row.name, col.name, plane.name ) name = @build.connectName( practice, 'south', false ) rect = new Rect( plane.name, row.name, col.name, name, [col.x,row.y,plane.z], [w,h],hsv, 0.7, @fontPrac, 0xFFFFFF ) group.add( rect.mesh ) return conduit:( sp, group ) -> hsv = [0,50,50] w = sp.studyWidth h = sp.zzzzSpace z = ( sp.cubeDepth + h ) / 2 for plane in [ { name:'Info', z:sp.z1-z }, { name:'Know', z:sp.z2-z } ] for row in [ { name:'Learn', y:sp.y1 }, { name:'Do', y:sp.y2 }, { name:'Share', y:sp.y3 } ] for col in [ { name:'Embrace', x:sp.x3 }, { name:'Innovate', x:sp.x2 }, { name:'Encourage',x:sp.x1 } ] practice = @build.getPractice( row.name, col.name, plane.name ) name = @build.connectName( practice, 'next', true ) rect = new Rect( plane.name, row.name, col.name, name, [0,0,0], [w,h],hsv, 0.7, @fontPrac, 0xFFFFFF ) rect.mesh.rotation.x = -Math.PI / 2 rect.mesh.position.x = col.x rect.mesh.position.y = row.y rect.mesh.position.z = plane.z group.add( rect.mesh ) return lights:() -> object3d = new THREE.DirectionalLight( 'white', 0.15 ) object3d.position.set(6,3,9) object3d.name = 'Back light' @scene.add(object3d) object3d = new THREE.DirectionalLight( 'white', 0.35 ); object3d.position.set(-6, -3, 0) object3d.name = 'Key light' @scene.add(object3d) object3d = new THREE.DirectionalLight( 'white', 0.55 ) object3d.position.set(9, 9, 6) object3d.name = 'Fill light' @scene.add(object3d) spotLight = new THREE.SpotLight( 0xffffff ) spotLight.position.set( 3, 30, 3 ) spotLight.castShadow = true spotLight.shadow.mapSize.width = 2048 spotLight.shadow.mapSize.height = 2048 spotLight.shadow.camera.near = 1 spotLight.shadow.camera.far = 4000 spotLight.shadow.camera.fov = 45 @scene.add( spotLight ) return createElems:( parElem, guiFlag ) -> return [parElem,null] if not guiFlag ikwElem = document.createElement( 'div' ) guiElem = document.createElement( 'div' ) parElem.appendChild( ikwElem ) parElem.appendChild( guiElem ) ikwStyle = document.createAttribute('style') guiStyle = document.createAttribute('style') ikwStyle.value = "position:absolute; left: 0; top:0; width:80%; height:100%;" guiStyle.value = "position:absolute; left:80%; top:0; width:20%; height:100%; background-color:black;" ikwElem.setAttributeNode( ikwStyle ) guiElem.setAttributeNode( guiStyle ) [ikwElem,guiElem] traverse:( prop, name, act ) => act[name] = not act[name] if @stream? # console.log( 'CubeTh.traverse()', { prop:prop, name:name, visible:act[name] } ) reveal = (child) => # console.log( 'CubeTh.traverse.beg', { name:child.name, tprop:prop, cprop:child[prop], value:value, visible:child.visible } ) if child[prop]? and child[prop] is name child.visible = act[name] # console.log( 'CubeTh.traverse.end', { name:child.name, geom:child.geom, prop:prop, value:value, visible:child.visible } ) @group.traverse( reveal ) if @group? return createAct:( group ) -> { Info : true, Know : true, Wise : true, Learn : true, Do : true, Share : true, Embrace : true, Innovate : true, Encourage : true, Opacity:group.material.opacity, Color:group.material.color, RotationX:group.rotation.x, RotationY:group.rotation.y, RotationZ:group.rotation.z, PositionX:0, PositionY:0, PositionZ:0, ScaleX:1, ScaleY:1, ScaleZ:1 } createTraversals:( act ) -> { info: () => @traverse( 'plane', 'Info', act ) know: () => @traverse( 'plane', 'Know', act ) wise: () => @traverse( 'plane', 'Wise', act ) learn: () => @traverse( 'row', 'Learn', act ) doDo: () => @traverse( 'row', 'Do', act ) share: () => @traverse( 'row', 'Share', act ) embrace: () => @traverse( 'col', 'Embrace', act ) innovate: () => @traverse( 'col', 'Innovate', act ) encourage: () => @traverse( 'col', 'Encourage', act ) } ui:( group, guiElem ) -> act = @createAct( group ) traverals = @createTraversals( act ) dat = vis.getGlobal('dat') gui = dat.GUI( { autoPlace: false } ) guiElem.appendChild( gui.domElement ) f1 = gui.addFolder('Planes') f1.add( act, 'Info' ).onChange( traverals.info ) f1.add( act, 'Know' ).onChange( traverals.know ) f1.add( act, 'Wise' ).onChange( traverals.wise ) f2 = gui.addFolder('Rows') f2.add( act, 'Learn' ).onChange( traverals.learn ) f2.add( act, 'Do' ).onChange( traverals.doDo ) f2.add( act, 'Share' ).onChange( traverals.share ) f3 = gui.addFolder('Prin') f3.add( act, 'Embrace' ).onChange( traverals.embrace ) f3.add( act, 'Innovate' ).onChange( traverals.innovate ) f3.add( act, 'Encourage' ).onChange( traverals.encourage ) f4 = gui.addFolder('Rotation') f4.add( act, 'RotationX', -180, 180 ).onChange( () => group.rotation.x = @deg2rad(act.RotationX) ) f4.add( act, 'RotationY', -180, 180 ).onChange( () => group.rotation.y = @deg2rad(act.RotationY) ) f4.add( act, 'RotationZ', -180, 180 ).onChange( () => group.rotation.z = @deg2rad(act.RotationZ) ) f5 = gui.addFolder('Position'); f5.add( act, 'PositionX', -500, 500 ).onChange( () -> group.position.x = act.PositionX ) f5.add( act, 'PositionY', -500, 500 ).onChange( () -> group.position.y = act.PositionY ) f5.add( act, 'PositionZ', -500, 500 ).onChange( () -> group.position.z = act.PositionZ ) f6 = gui.addFolder('Scale') f6.add( act, 'ScaleX', 0.1, 5 ).onChange( () -> group.scale.x = act.ScaleX ) f6.add( act, 'ScaleY', 0.1, 5 ).onChange( () -> group.scale.y = act.ScaleY ) f6.add( act, 'ScaleZ', 0.1, 5 ).onChange( () -> group.scale.z = act.ScaleZ ) [gui,act] animate:() => requestAnimationFrame( @animate ) @controls.update(); @renderScene() return renderScene:() -> if @needsRender @renderer.render( @scene, @camera ) @needsRender = false return geom:() -> color = 0x888888 # Guess geometry = new THREE.BoxGeometry( 2, 2, 2 ) material = new THREE.MeshLambertMaterial({ color:color, transparent:true } ) mesh = new THREE.Mesh(geometry, material) mesh.position.set(0, 0, 0) mesh.rotation.set(0, 0, 0) mesh.rotation.y = @deg2rad(-90) mesh.scale.set(1, 1, 1) mesh.doubleSided = true mesh.castShadow = true @scene.add(mesh) geometry2 = new THREE.BoxGeometry( 1, 1, 1 ) material2 = new THREE.MeshLambertMaterial({ color:color, transparent:true } ) mesh2 = new THREE.Mesh(geometry2, material2) @scene.add(mesh2) return export default CubeTh
171736
import {vis} from '../../../lib/pub/draw/Vis.js' import Access from '../../../lib/pub/util/Access.js' import Build from '../../../lib/pub/util/Build.js' import Cube3D from './Cube3D.js' import Rect from './Rect.js' import * as THREE from 'three' import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js' class CubeTh @init:( batch ) -> vis.ready -> build = new Build( batch ) th = new CubeTh( build, 'CubeTh', false ) th.animate() return @load:() -> Access.local = "http://localhost:63342/aug/app/data/" Access.hosted = "https://ui-48413.firebaseapp.com/" CubeTh.FontUrl = "../../css/font/helvetiker_regular.typeface.json" CubeTh.Batch = Info: { url:'muse/Info.json', data:null, type:'Pack' } Know: { url:'muse/Know.json', data:null, type:'Pack' } Wise: { url:'muse/Wise.json', data:null, type:'Pack' } Font: { url:CubeTh.FontUrl, data:null, type:'Spec' } Access.batchRead( CubeTh.Batch, CubeTh["init"] ) return constructor:( @build, @parElem, @guiFlag ) -> @needsRender = true @stream = null # Set by subscribe() elems = @createElems( @parElem, @guiFlag ) @ikwElem = elems[0] @guiElem = elems[1] @scene = new THREE.Scene() @renderer = new THREE.WebGLRenderer( { antialias:true } ) @ikwElem.appendChild( @renderer.domElement ) [@screenWidth,@screenHeight,@aspectRatio] = @resizeScreen() # Accesses @ikwElem @renderer.setSize( @screenWidth, @screenHeight ) @renderer.setClearColor( 0x000000, 1) # 0x333F47, 1 @renderer.shadowMap.enabled = true @renderer.shadowMapSoft = true @camera = new THREE.PerspectiveCamera( 45, @aspectRatio, 1, 10000 ) @camera.position.set( 0, 6, 1500 ) @camera.lookAt( @scene.position ) @scene.add(@camera) @axes = new THREE.AxesHelper( 2 ) @scene.add( @axes ) @fontPrac = new THREE.Font( @build.batch.Font.data ) @group = @ikw() @lights() [@gui,@act] = @ui( @group, @guiElem ) if @guiFlag @controls = new OrbitControls( @camera, @renderer.domElement ) @controls.addEventListener( 'change', () => @needsRender = true ) window.addEventListener( 'resize', @resizeScreen, false ) subscribe:( stream ) -> @stream = stream @act = @createAct( @group ) @traversals = @createTraversals( @act ) @stream.subscribe( 'Select', 'Cube', (topic) => @onSelect(topic) ) return onSelect:( topic ) => # console.log( 'CubeTh.onCube()', name ) switch topic.name when 'Cube' then vis.noop() when 'Planes' then vis.noop() when 'Information' then @traversals.info() when 'Knowledge' then @traversals.know() when 'Wisdom' then @traversals.wise() when 'Dimensions' then vis.noop() when 'Embrace' then @traversals.embrace() when 'Innovate' then @traversals.innovate() when 'Encourage' then @traversals.encourage() when 'Perspectives' then vis.noop() when 'Learn' then @traversals.learn() when 'Do' then @traversals.doDo() when 'Share' then @traversals.share() else console.error( 'CubeTh.onSelect()', topic ) return deg2rad:( degree ) -> degree*(Math.PI/180) resizeScreen:() => @screenWidth = @ikwElem.clientWidth # window.innerWidth @screenHeight = @ikwElem.clientHeight # window.innerHeight @aspectRatio = @screenWidth / @screenHeight if @camera? and @renderer? @camera.aspect = @aspectRatio @camera.updateProjectionMatrix(); @renderer.setSize( @screenWidth, @screenHeight ) #console.log( "resizeScreen", { width:@screenWidth, height:@screenHeight } ) [@screenWidth,@screenHeight,@aspectRatio] space:() -> sp = {} sp.modelRatio = @aspectRatio / 2 sp.cubeSize = 144 sp.cubeWidth = sp.cubeSize * 2.0 sp.cubeHeight = sp.cubeSize * sp.modelRatio * 0.8 sp.colsHeight = sp.cubeSize * sp.modelRatio * 0.5 sp.cubeDepth = sp.cubeSize sp.cubeHalf = sp.cubeSize / 2 sp.horzSpace = sp.cubeSize * 2 / 3 sp.vertSpace = sp.horzSpace * sp.modelRatio sp.zzzzSpace = sp.horzSpace sp.colsDepth = sp.cubeSize * 3 + sp.zzzzSpace * 2 sp.x1 = sp.cubeWidth + sp.horzSpace sp.x2 = 0 sp.x3 = -sp.cubeWidth - sp.horzSpace sp.yc = sp.cubeHeight + sp.vertSpace * 2.2 sp.y1 = sp.cubeHeight + sp.vertSpace sp.y2 = 0 sp.y3 = -sp.cubeHeight - sp.vertSpace sp.z1 = sp.cubeDepth + sp.zzzzSpace sp.z2 = 0 sp.z3 = -sp.cubeDepth - sp.zzzzSpace sp.zc = 0 sp.studyWidth = sp.cubeWidth / 3 sp.studyHeight = sp.cubeHeight / 3 sp.sw = sp.studyWidth sp.sh = sp.studyHeight sp.cw = sp.studyWidth sp.ch = sp.studyHeight * 0.5 sp.sx = { center:0, west:-sp.sw, north:0, east:sp.sw, south:0 } sp.sy = { center:0, west:0, north:sp.sh, east:0, south:-sp.sh } sp.cx = { center:0, west:-sp.sw, north:0, east:sp.sw, south:0 } sp.cy = { center:0, west:0, north:sp.sh*0.5, east:0, south:-sp.sh*0.5 } sp ikw: () -> sp = @space() group = new THREE.Group() for plane in [ { name:'Info', z:sp.z1 }, { name:'Know', z:sp.z2 }, { name:'Wise', z:sp.z3 } ] for row in [ { name:'Learn', y:sp.y1 }, { name:'Do', y:sp.y2 }, { name:'Share', y:sp.y3 } ] for col in [ { name:'Embrace', x:sp.x3 }, { name:'Innovate', x:sp.x2 }, { name:'Encourage', x:sp.x1 } ] practice = @build.getPractice( row.name, col.name, plane.name ) # console.log( 'Cube.ikw()', practice.name, row.name, col.name, plane.name ) pracCube = new Cube3D( plane.name, row.name, col.name, practice.name, [col.x,row.y,plane.z], [sp.cubeWidth,sp.cubeHeight,sp.cubeDepth],practice['hsv'], 0.6, @fontPrac ) pracGroup = new THREE.Group() pracGroup.add( pracCube.mesh ) for key, study of practice when vis.isChild(key) x = col.x + sp.sx[study.dir] y = row.y + sp.sy[study.dir] z = plane.z studyCube = new Rect( plane.name, row.name, col.name, study.name, [x,y,z], [sp.sw,sp.sh],study['hsv'], 1.0, @fontPrac, 0x000000 ) pracGroup.add( studyCube.mesh ) group.add( pracGroup ) group.add( @prin() ) @convey( sp, group ) @flow( sp, group ) @conduit( sp, group ) group.material = new THREE.MeshLambertMaterial( { color:0x888888, transparent:true, opacity:0.5, side:THREE.DoubleSide } ) group.rotation.set( 0, 0, 0 ) group.position.set( 0, 0, 0 ) group.scale.set( 1, 1, 1 ) @scene.add( group ) group prin: () -> sp = @space() group = new THREE.Group() for col in [ { name:'Embrace', x:sp.x3 }, { name:'Innovate', x:sp.x2 }, { name:'Encourage', x:sp.x1 } ] practice = @build.getCol( col.name ) pracCube = new Cube3D( 'Prin', 'Dim', col.name, col.name, [col.x,sp.yc,sp.zc], [sp.cubeWidth,sp.colsHeight,sp.colsDepth],practice['hsv'], 0.6, @fontPrac ) pracGroup = new THREE.Group() pracGroup.add( pracCube.mesh ) for plane in [ { name:'Info', z:sp.z1 }, { name:'Know', z:sp.z2 }, { name:'Wise', z:sp.z3 } ] x = col.x y = sp.yc z = plane.z studyCube = new Rect( plane, 'Dim', col.name, col.name, [x,y,z], [sp.cw,sp.ch], [0,0,0], 0.0, @fontPrac, 0xFFFFFF ) pracGroup.add( studyCube.mesh ) for key, study of practice when vis.isChild(key) x = col.x + sp.cx[study.dir] y = sp.yc + sp.cy[study.dir] z = plane.z studyCube = new Rect( '<NAME>', 'Dim', col.name, key, [x,y,z], [sp.cw,sp.ch],study['hsv'], 1.0, @fontPrac, 0x000000 ) pracGroup.add( studyCube.mesh ) group.add( pracGroup ) group.material = new THREE.MeshLambertMaterial( { color:0x888888, transparent:true, opacity:0.5, side:THREE.DoubleSide } ) group.rotation.set( 0, 0, 0 ) group.position.set( 0, 0, 0 ) group.scale.set( 1, 1, 1 ) @scene.add( group ) group convey:( sp, group ) -> hsv = [0,50,50] w = sp.horzSpace h = sp.studyHeight x = ( sp.cubeWidth + w ) / 2 for plane in [ { name:'Info', z:sp.z1 }, { name:'Know', z:sp.z2 }, { name:'Wise', z:sp.z3 } ] for row in [ { name:'Learn', y:sp.y1 }, { name:'Do', y:sp.y2 }, { name:'Share', y:sp.y3 } ] for col in [ { name:'Embrace', x:sp.x3+x }, { name:'Innovate', x:sp.x2+x } ] practice = @build.getPractice( row.name, col.name, plane.name ) name = @build.connectName( practice, 'east', false ) rect = new Rect( plane.name, row.name, col.name, name, [col.x,row.y,plane.z], [w,h],hsv, 0.7, @fontPrac, 0xFFFFFF ) group.add( rect.mesh ) return flow:( sp, group ) -> hsv = [0,50,50] w = sp.studyWidth h = sp.vertSpace y = ( sp.cubeHeight + h ) / 2 for plane in [ { name:'Info', z:sp.z1 }, { name:'Know', z:sp.z2 }, { name:'Wise', z:sp.z3 } ] for row in [ { name:'Learn', y:sp.y1-y}, { name:'Do', y:sp.y2-y } ] for col in [ { name:'Embrace', x:sp.x3}, { name:'Innovate', x:sp.x2 }, { name:'Encourage', x:sp.x1 } ] practice = @build.getPractice( row.name, col.name, plane.name ) name = @build.connectName( practice, 'south', false ) rect = new Rect( plane.name, row.name, col.name, name, [col.x,row.y,plane.z], [w,h],hsv, 0.7, @fontPrac, 0xFFFFFF ) group.add( rect.mesh ) return conduit:( sp, group ) -> hsv = [0,50,50] w = sp.studyWidth h = sp.zzzzSpace z = ( sp.cubeDepth + h ) / 2 for plane in [ { name:'Info', z:sp.z1-z }, { name:'Know', z:sp.z2-z } ] for row in [ { name:'Learn', y:sp.y1 }, { name:'Do', y:sp.y2 }, { name:'Share', y:sp.y3 } ] for col in [ { name:'Embrace', x:sp.x3 }, { name:'Innovate', x:sp.x2 }, { name:'Encourage',x:sp.x1 } ] practice = @build.getPractice( row.name, col.name, plane.name ) name = @build.connectName( practice, 'next', true ) rect = new Rect( plane.name, row.name, col.name, name, [0,0,0], [w,h],hsv, 0.7, @fontPrac, 0xFFFFFF ) rect.mesh.rotation.x = -Math.PI / 2 rect.mesh.position.x = col.x rect.mesh.position.y = row.y rect.mesh.position.z = plane.z group.add( rect.mesh ) return lights:() -> object3d = new THREE.DirectionalLight( 'white', 0.15 ) object3d.position.set(6,3,9) object3d.name = 'Back light' @scene.add(object3d) object3d = new THREE.DirectionalLight( 'white', 0.35 ); object3d.position.set(-6, -3, 0) object3d.name = 'Key light' @scene.add(object3d) object3d = new THREE.DirectionalLight( 'white', 0.55 ) object3d.position.set(9, 9, 6) object3d.name = 'Fill light' @scene.add(object3d) spotLight = new THREE.SpotLight( 0xffffff ) spotLight.position.set( 3, 30, 3 ) spotLight.castShadow = true spotLight.shadow.mapSize.width = 2048 spotLight.shadow.mapSize.height = 2048 spotLight.shadow.camera.near = 1 spotLight.shadow.camera.far = 4000 spotLight.shadow.camera.fov = 45 @scene.add( spotLight ) return createElems:( parElem, guiFlag ) -> return [parElem,null] if not guiFlag ikwElem = document.createElement( 'div' ) guiElem = document.createElement( 'div' ) parElem.appendChild( ikwElem ) parElem.appendChild( guiElem ) ikwStyle = document.createAttribute('style') guiStyle = document.createAttribute('style') ikwStyle.value = "position:absolute; left: 0; top:0; width:80%; height:100%;" guiStyle.value = "position:absolute; left:80%; top:0; width:20%; height:100%; background-color:black;" ikwElem.setAttributeNode( ikwStyle ) guiElem.setAttributeNode( guiStyle ) [ikwElem,guiElem] traverse:( prop, name, act ) => act[name] = not act[name] if @stream? # console.log( 'CubeTh.traverse()', { prop:prop, name:name, visible:act[name] } ) reveal = (child) => # console.log( 'CubeTh.traverse.beg', { name:child.name, tprop:prop, cprop:child[prop], value:value, visible:child.visible } ) if child[prop]? and child[prop] is name child.visible = act[name] # console.log( 'CubeTh.traverse.end', { name:child.name, geom:child.geom, prop:prop, value:value, visible:child.visible } ) @group.traverse( reveal ) if @group? return createAct:( group ) -> { Info : true, Know : true, Wise : true, Learn : true, Do : true, Share : true, Embrace : true, Innovate : true, Encourage : true, Opacity:group.material.opacity, Color:group.material.color, RotationX:group.rotation.x, RotationY:group.rotation.y, RotationZ:group.rotation.z, PositionX:0, PositionY:0, PositionZ:0, ScaleX:1, ScaleY:1, ScaleZ:1 } createTraversals:( act ) -> { info: () => @traverse( 'plane', 'Info', act ) know: () => @traverse( 'plane', 'Know', act ) wise: () => @traverse( 'plane', 'Wise', act ) learn: () => @traverse( 'row', 'Learn', act ) doDo: () => @traverse( 'row', 'Do', act ) share: () => @traverse( 'row', 'Share', act ) embrace: () => @traverse( 'col', 'Embrace', act ) innovate: () => @traverse( 'col', 'Innovate', act ) encourage: () => @traverse( 'col', 'Encourage', act ) } ui:( group, guiElem ) -> act = @createAct( group ) traverals = @createTraversals( act ) dat = vis.getGlobal('dat') gui = dat.GUI( { autoPlace: false } ) guiElem.appendChild( gui.domElement ) f1 = gui.addFolder('Planes') f1.add( act, 'Info' ).onChange( traverals.info ) f1.add( act, 'Know' ).onChange( traverals.know ) f1.add( act, 'Wise' ).onChange( traverals.wise ) f2 = gui.addFolder('Rows') f2.add( act, 'Learn' ).onChange( traverals.learn ) f2.add( act, 'Do' ).onChange( traverals.doDo ) f2.add( act, 'Share' ).onChange( traverals.share ) f3 = gui.addFolder('Prin') f3.add( act, 'Embrace' ).onChange( traverals.embrace ) f3.add( act, 'Innovate' ).onChange( traverals.innovate ) f3.add( act, 'Encourage' ).onChange( traverals.encourage ) f4 = gui.addFolder('Rotation') f4.add( act, 'RotationX', -180, 180 ).onChange( () => group.rotation.x = @deg2rad(act.RotationX) ) f4.add( act, 'RotationY', -180, 180 ).onChange( () => group.rotation.y = @deg2rad(act.RotationY) ) f4.add( act, 'RotationZ', -180, 180 ).onChange( () => group.rotation.z = @deg2rad(act.RotationZ) ) f5 = gui.addFolder('Position'); f5.add( act, 'PositionX', -500, 500 ).onChange( () -> group.position.x = act.PositionX ) f5.add( act, 'PositionY', -500, 500 ).onChange( () -> group.position.y = act.PositionY ) f5.add( act, 'PositionZ', -500, 500 ).onChange( () -> group.position.z = act.PositionZ ) f6 = gui.addFolder('Scale') f6.add( act, 'ScaleX', 0.1, 5 ).onChange( () -> group.scale.x = act.ScaleX ) f6.add( act, 'ScaleY', 0.1, 5 ).onChange( () -> group.scale.y = act.ScaleY ) f6.add( act, 'ScaleZ', 0.1, 5 ).onChange( () -> group.scale.z = act.ScaleZ ) [gui,act] animate:() => requestAnimationFrame( @animate ) @controls.update(); @renderScene() return renderScene:() -> if @needsRender @renderer.render( @scene, @camera ) @needsRender = false return geom:() -> color = 0x888888 # Guess geometry = new THREE.BoxGeometry( 2, 2, 2 ) material = new THREE.MeshLambertMaterial({ color:color, transparent:true } ) mesh = new THREE.Mesh(geometry, material) mesh.position.set(0, 0, 0) mesh.rotation.set(0, 0, 0) mesh.rotation.y = @deg2rad(-90) mesh.scale.set(1, 1, 1) mesh.doubleSided = true mesh.castShadow = true @scene.add(mesh) geometry2 = new THREE.BoxGeometry( 1, 1, 1 ) material2 = new THREE.MeshLambertMaterial({ color:color, transparent:true } ) mesh2 = new THREE.Mesh(geometry2, material2) @scene.add(mesh2) return export default CubeTh
true
import {vis} from '../../../lib/pub/draw/Vis.js' import Access from '../../../lib/pub/util/Access.js' import Build from '../../../lib/pub/util/Build.js' import Cube3D from './Cube3D.js' import Rect from './Rect.js' import * as THREE from 'three' import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js' class CubeTh @init:( batch ) -> vis.ready -> build = new Build( batch ) th = new CubeTh( build, 'CubeTh', false ) th.animate() return @load:() -> Access.local = "http://localhost:63342/aug/app/data/" Access.hosted = "https://ui-48413.firebaseapp.com/" CubeTh.FontUrl = "../../css/font/helvetiker_regular.typeface.json" CubeTh.Batch = Info: { url:'muse/Info.json', data:null, type:'Pack' } Know: { url:'muse/Know.json', data:null, type:'Pack' } Wise: { url:'muse/Wise.json', data:null, type:'Pack' } Font: { url:CubeTh.FontUrl, data:null, type:'Spec' } Access.batchRead( CubeTh.Batch, CubeTh["init"] ) return constructor:( @build, @parElem, @guiFlag ) -> @needsRender = true @stream = null # Set by subscribe() elems = @createElems( @parElem, @guiFlag ) @ikwElem = elems[0] @guiElem = elems[1] @scene = new THREE.Scene() @renderer = new THREE.WebGLRenderer( { antialias:true } ) @ikwElem.appendChild( @renderer.domElement ) [@screenWidth,@screenHeight,@aspectRatio] = @resizeScreen() # Accesses @ikwElem @renderer.setSize( @screenWidth, @screenHeight ) @renderer.setClearColor( 0x000000, 1) # 0x333F47, 1 @renderer.shadowMap.enabled = true @renderer.shadowMapSoft = true @camera = new THREE.PerspectiveCamera( 45, @aspectRatio, 1, 10000 ) @camera.position.set( 0, 6, 1500 ) @camera.lookAt( @scene.position ) @scene.add(@camera) @axes = new THREE.AxesHelper( 2 ) @scene.add( @axes ) @fontPrac = new THREE.Font( @build.batch.Font.data ) @group = @ikw() @lights() [@gui,@act] = @ui( @group, @guiElem ) if @guiFlag @controls = new OrbitControls( @camera, @renderer.domElement ) @controls.addEventListener( 'change', () => @needsRender = true ) window.addEventListener( 'resize', @resizeScreen, false ) subscribe:( stream ) -> @stream = stream @act = @createAct( @group ) @traversals = @createTraversals( @act ) @stream.subscribe( 'Select', 'Cube', (topic) => @onSelect(topic) ) return onSelect:( topic ) => # console.log( 'CubeTh.onCube()', name ) switch topic.name when 'Cube' then vis.noop() when 'Planes' then vis.noop() when 'Information' then @traversals.info() when 'Knowledge' then @traversals.know() when 'Wisdom' then @traversals.wise() when 'Dimensions' then vis.noop() when 'Embrace' then @traversals.embrace() when 'Innovate' then @traversals.innovate() when 'Encourage' then @traversals.encourage() when 'Perspectives' then vis.noop() when 'Learn' then @traversals.learn() when 'Do' then @traversals.doDo() when 'Share' then @traversals.share() else console.error( 'CubeTh.onSelect()', topic ) return deg2rad:( degree ) -> degree*(Math.PI/180) resizeScreen:() => @screenWidth = @ikwElem.clientWidth # window.innerWidth @screenHeight = @ikwElem.clientHeight # window.innerHeight @aspectRatio = @screenWidth / @screenHeight if @camera? and @renderer? @camera.aspect = @aspectRatio @camera.updateProjectionMatrix(); @renderer.setSize( @screenWidth, @screenHeight ) #console.log( "resizeScreen", { width:@screenWidth, height:@screenHeight } ) [@screenWidth,@screenHeight,@aspectRatio] space:() -> sp = {} sp.modelRatio = @aspectRatio / 2 sp.cubeSize = 144 sp.cubeWidth = sp.cubeSize * 2.0 sp.cubeHeight = sp.cubeSize * sp.modelRatio * 0.8 sp.colsHeight = sp.cubeSize * sp.modelRatio * 0.5 sp.cubeDepth = sp.cubeSize sp.cubeHalf = sp.cubeSize / 2 sp.horzSpace = sp.cubeSize * 2 / 3 sp.vertSpace = sp.horzSpace * sp.modelRatio sp.zzzzSpace = sp.horzSpace sp.colsDepth = sp.cubeSize * 3 + sp.zzzzSpace * 2 sp.x1 = sp.cubeWidth + sp.horzSpace sp.x2 = 0 sp.x3 = -sp.cubeWidth - sp.horzSpace sp.yc = sp.cubeHeight + sp.vertSpace * 2.2 sp.y1 = sp.cubeHeight + sp.vertSpace sp.y2 = 0 sp.y3 = -sp.cubeHeight - sp.vertSpace sp.z1 = sp.cubeDepth + sp.zzzzSpace sp.z2 = 0 sp.z3 = -sp.cubeDepth - sp.zzzzSpace sp.zc = 0 sp.studyWidth = sp.cubeWidth / 3 sp.studyHeight = sp.cubeHeight / 3 sp.sw = sp.studyWidth sp.sh = sp.studyHeight sp.cw = sp.studyWidth sp.ch = sp.studyHeight * 0.5 sp.sx = { center:0, west:-sp.sw, north:0, east:sp.sw, south:0 } sp.sy = { center:0, west:0, north:sp.sh, east:0, south:-sp.sh } sp.cx = { center:0, west:-sp.sw, north:0, east:sp.sw, south:0 } sp.cy = { center:0, west:0, north:sp.sh*0.5, east:0, south:-sp.sh*0.5 } sp ikw: () -> sp = @space() group = new THREE.Group() for plane in [ { name:'Info', z:sp.z1 }, { name:'Know', z:sp.z2 }, { name:'Wise', z:sp.z3 } ] for row in [ { name:'Learn', y:sp.y1 }, { name:'Do', y:sp.y2 }, { name:'Share', y:sp.y3 } ] for col in [ { name:'Embrace', x:sp.x3 }, { name:'Innovate', x:sp.x2 }, { name:'Encourage', x:sp.x1 } ] practice = @build.getPractice( row.name, col.name, plane.name ) # console.log( 'Cube.ikw()', practice.name, row.name, col.name, plane.name ) pracCube = new Cube3D( plane.name, row.name, col.name, practice.name, [col.x,row.y,plane.z], [sp.cubeWidth,sp.cubeHeight,sp.cubeDepth],practice['hsv'], 0.6, @fontPrac ) pracGroup = new THREE.Group() pracGroup.add( pracCube.mesh ) for key, study of practice when vis.isChild(key) x = col.x + sp.sx[study.dir] y = row.y + sp.sy[study.dir] z = plane.z studyCube = new Rect( plane.name, row.name, col.name, study.name, [x,y,z], [sp.sw,sp.sh],study['hsv'], 1.0, @fontPrac, 0x000000 ) pracGroup.add( studyCube.mesh ) group.add( pracGroup ) group.add( @prin() ) @convey( sp, group ) @flow( sp, group ) @conduit( sp, group ) group.material = new THREE.MeshLambertMaterial( { color:0x888888, transparent:true, opacity:0.5, side:THREE.DoubleSide } ) group.rotation.set( 0, 0, 0 ) group.position.set( 0, 0, 0 ) group.scale.set( 1, 1, 1 ) @scene.add( group ) group prin: () -> sp = @space() group = new THREE.Group() for col in [ { name:'Embrace', x:sp.x3 }, { name:'Innovate', x:sp.x2 }, { name:'Encourage', x:sp.x1 } ] practice = @build.getCol( col.name ) pracCube = new Cube3D( 'Prin', 'Dim', col.name, col.name, [col.x,sp.yc,sp.zc], [sp.cubeWidth,sp.colsHeight,sp.colsDepth],practice['hsv'], 0.6, @fontPrac ) pracGroup = new THREE.Group() pracGroup.add( pracCube.mesh ) for plane in [ { name:'Info', z:sp.z1 }, { name:'Know', z:sp.z2 }, { name:'Wise', z:sp.z3 } ] x = col.x y = sp.yc z = plane.z studyCube = new Rect( plane, 'Dim', col.name, col.name, [x,y,z], [sp.cw,sp.ch], [0,0,0], 0.0, @fontPrac, 0xFFFFFF ) pracGroup.add( studyCube.mesh ) for key, study of practice when vis.isChild(key) x = col.x + sp.cx[study.dir] y = sp.yc + sp.cy[study.dir] z = plane.z studyCube = new Rect( 'PI:NAME:<NAME>END_PI', 'Dim', col.name, key, [x,y,z], [sp.cw,sp.ch],study['hsv'], 1.0, @fontPrac, 0x000000 ) pracGroup.add( studyCube.mesh ) group.add( pracGroup ) group.material = new THREE.MeshLambertMaterial( { color:0x888888, transparent:true, opacity:0.5, side:THREE.DoubleSide } ) group.rotation.set( 0, 0, 0 ) group.position.set( 0, 0, 0 ) group.scale.set( 1, 1, 1 ) @scene.add( group ) group convey:( sp, group ) -> hsv = [0,50,50] w = sp.horzSpace h = sp.studyHeight x = ( sp.cubeWidth + w ) / 2 for plane in [ { name:'Info', z:sp.z1 }, { name:'Know', z:sp.z2 }, { name:'Wise', z:sp.z3 } ] for row in [ { name:'Learn', y:sp.y1 }, { name:'Do', y:sp.y2 }, { name:'Share', y:sp.y3 } ] for col in [ { name:'Embrace', x:sp.x3+x }, { name:'Innovate', x:sp.x2+x } ] practice = @build.getPractice( row.name, col.name, plane.name ) name = @build.connectName( practice, 'east', false ) rect = new Rect( plane.name, row.name, col.name, name, [col.x,row.y,plane.z], [w,h],hsv, 0.7, @fontPrac, 0xFFFFFF ) group.add( rect.mesh ) return flow:( sp, group ) -> hsv = [0,50,50] w = sp.studyWidth h = sp.vertSpace y = ( sp.cubeHeight + h ) / 2 for plane in [ { name:'Info', z:sp.z1 }, { name:'Know', z:sp.z2 }, { name:'Wise', z:sp.z3 } ] for row in [ { name:'Learn', y:sp.y1-y}, { name:'Do', y:sp.y2-y } ] for col in [ { name:'Embrace', x:sp.x3}, { name:'Innovate', x:sp.x2 }, { name:'Encourage', x:sp.x1 } ] practice = @build.getPractice( row.name, col.name, plane.name ) name = @build.connectName( practice, 'south', false ) rect = new Rect( plane.name, row.name, col.name, name, [col.x,row.y,plane.z], [w,h],hsv, 0.7, @fontPrac, 0xFFFFFF ) group.add( rect.mesh ) return conduit:( sp, group ) -> hsv = [0,50,50] w = sp.studyWidth h = sp.zzzzSpace z = ( sp.cubeDepth + h ) / 2 for plane in [ { name:'Info', z:sp.z1-z }, { name:'Know', z:sp.z2-z } ] for row in [ { name:'Learn', y:sp.y1 }, { name:'Do', y:sp.y2 }, { name:'Share', y:sp.y3 } ] for col in [ { name:'Embrace', x:sp.x3 }, { name:'Innovate', x:sp.x2 }, { name:'Encourage',x:sp.x1 } ] practice = @build.getPractice( row.name, col.name, plane.name ) name = @build.connectName( practice, 'next', true ) rect = new Rect( plane.name, row.name, col.name, name, [0,0,0], [w,h],hsv, 0.7, @fontPrac, 0xFFFFFF ) rect.mesh.rotation.x = -Math.PI / 2 rect.mesh.position.x = col.x rect.mesh.position.y = row.y rect.mesh.position.z = plane.z group.add( rect.mesh ) return lights:() -> object3d = new THREE.DirectionalLight( 'white', 0.15 ) object3d.position.set(6,3,9) object3d.name = 'Back light' @scene.add(object3d) object3d = new THREE.DirectionalLight( 'white', 0.35 ); object3d.position.set(-6, -3, 0) object3d.name = 'Key light' @scene.add(object3d) object3d = new THREE.DirectionalLight( 'white', 0.55 ) object3d.position.set(9, 9, 6) object3d.name = 'Fill light' @scene.add(object3d) spotLight = new THREE.SpotLight( 0xffffff ) spotLight.position.set( 3, 30, 3 ) spotLight.castShadow = true spotLight.shadow.mapSize.width = 2048 spotLight.shadow.mapSize.height = 2048 spotLight.shadow.camera.near = 1 spotLight.shadow.camera.far = 4000 spotLight.shadow.camera.fov = 45 @scene.add( spotLight ) return createElems:( parElem, guiFlag ) -> return [parElem,null] if not guiFlag ikwElem = document.createElement( 'div' ) guiElem = document.createElement( 'div' ) parElem.appendChild( ikwElem ) parElem.appendChild( guiElem ) ikwStyle = document.createAttribute('style') guiStyle = document.createAttribute('style') ikwStyle.value = "position:absolute; left: 0; top:0; width:80%; height:100%;" guiStyle.value = "position:absolute; left:80%; top:0; width:20%; height:100%; background-color:black;" ikwElem.setAttributeNode( ikwStyle ) guiElem.setAttributeNode( guiStyle ) [ikwElem,guiElem] traverse:( prop, name, act ) => act[name] = not act[name] if @stream? # console.log( 'CubeTh.traverse()', { prop:prop, name:name, visible:act[name] } ) reveal = (child) => # console.log( 'CubeTh.traverse.beg', { name:child.name, tprop:prop, cprop:child[prop], value:value, visible:child.visible } ) if child[prop]? and child[prop] is name child.visible = act[name] # console.log( 'CubeTh.traverse.end', { name:child.name, geom:child.geom, prop:prop, value:value, visible:child.visible } ) @group.traverse( reveal ) if @group? return createAct:( group ) -> { Info : true, Know : true, Wise : true, Learn : true, Do : true, Share : true, Embrace : true, Innovate : true, Encourage : true, Opacity:group.material.opacity, Color:group.material.color, RotationX:group.rotation.x, RotationY:group.rotation.y, RotationZ:group.rotation.z, PositionX:0, PositionY:0, PositionZ:0, ScaleX:1, ScaleY:1, ScaleZ:1 } createTraversals:( act ) -> { info: () => @traverse( 'plane', 'Info', act ) know: () => @traverse( 'plane', 'Know', act ) wise: () => @traverse( 'plane', 'Wise', act ) learn: () => @traverse( 'row', 'Learn', act ) doDo: () => @traverse( 'row', 'Do', act ) share: () => @traverse( 'row', 'Share', act ) embrace: () => @traverse( 'col', 'Embrace', act ) innovate: () => @traverse( 'col', 'Innovate', act ) encourage: () => @traverse( 'col', 'Encourage', act ) } ui:( group, guiElem ) -> act = @createAct( group ) traverals = @createTraversals( act ) dat = vis.getGlobal('dat') gui = dat.GUI( { autoPlace: false } ) guiElem.appendChild( gui.domElement ) f1 = gui.addFolder('Planes') f1.add( act, 'Info' ).onChange( traverals.info ) f1.add( act, 'Know' ).onChange( traverals.know ) f1.add( act, 'Wise' ).onChange( traverals.wise ) f2 = gui.addFolder('Rows') f2.add( act, 'Learn' ).onChange( traverals.learn ) f2.add( act, 'Do' ).onChange( traverals.doDo ) f2.add( act, 'Share' ).onChange( traverals.share ) f3 = gui.addFolder('Prin') f3.add( act, 'Embrace' ).onChange( traverals.embrace ) f3.add( act, 'Innovate' ).onChange( traverals.innovate ) f3.add( act, 'Encourage' ).onChange( traverals.encourage ) f4 = gui.addFolder('Rotation') f4.add( act, 'RotationX', -180, 180 ).onChange( () => group.rotation.x = @deg2rad(act.RotationX) ) f4.add( act, 'RotationY', -180, 180 ).onChange( () => group.rotation.y = @deg2rad(act.RotationY) ) f4.add( act, 'RotationZ', -180, 180 ).onChange( () => group.rotation.z = @deg2rad(act.RotationZ) ) f5 = gui.addFolder('Position'); f5.add( act, 'PositionX', -500, 500 ).onChange( () -> group.position.x = act.PositionX ) f5.add( act, 'PositionY', -500, 500 ).onChange( () -> group.position.y = act.PositionY ) f5.add( act, 'PositionZ', -500, 500 ).onChange( () -> group.position.z = act.PositionZ ) f6 = gui.addFolder('Scale') f6.add( act, 'ScaleX', 0.1, 5 ).onChange( () -> group.scale.x = act.ScaleX ) f6.add( act, 'ScaleY', 0.1, 5 ).onChange( () -> group.scale.y = act.ScaleY ) f6.add( act, 'ScaleZ', 0.1, 5 ).onChange( () -> group.scale.z = act.ScaleZ ) [gui,act] animate:() => requestAnimationFrame( @animate ) @controls.update(); @renderScene() return renderScene:() -> if @needsRender @renderer.render( @scene, @camera ) @needsRender = false return geom:() -> color = 0x888888 # Guess geometry = new THREE.BoxGeometry( 2, 2, 2 ) material = new THREE.MeshLambertMaterial({ color:color, transparent:true } ) mesh = new THREE.Mesh(geometry, material) mesh.position.set(0, 0, 0) mesh.rotation.set(0, 0, 0) mesh.rotation.y = @deg2rad(-90) mesh.scale.set(1, 1, 1) mesh.doubleSided = true mesh.castShadow = true @scene.add(mesh) geometry2 = new THREE.BoxGeometry( 1, 1, 1 ) material2 = new THREE.MeshLambertMaterial({ color:color, transparent:true } ) mesh2 = new THREE.Mesh(geometry2, material2) @scene.add(mesh2) return export default CubeTh
[ { "context": "laden\"\n \"guests\" : \"Gäste\"\n \"cancel Invitation\" : \"Einla", "end": 7048, "score": 0.8091983795166016, "start": 7043, "tag": "NAME", "value": "Gäste" }, { "context": "name:\"\n \"sync password\" : \"Passwort: \"\n \"sync help\" : \"Sin", "end": 9344, "score": 0.748931884765625, "start": 9336, "tag": "PASSWORD", "value": "Passwort" }, { "context": "ruar\"\n\n 'Jan' : 'Jan'\n 'Feb' : 'Feb'\n", "end": 10950, "score": 0.9992952942848206, "start": 10947, "tag": "NAME", "value": "Jan" } ]
client/app/locales/de.coffee
aenario/cozy-agenda
0
module.exports = "default calendar name" : "Mein Kalendar" "Add" : "Hinzufügen" "event" : "Ereignis" "create event" : "Ereignis erstellen" "edit event" : "Ereignis bearbeiten" "edit" : "Bearbeiten" "create" : "Erstellen" "creation" : "Erstellung" "invite" : "Einladen" "close" : "Schließen" "delete" : "Löschen" "change color" : "Farbe ändern" "rename" : "Umbennen" "export" : "Exportieren" "remove" : "Ereignis entfernen" "duplicate" : "Ereignis duplizieren" "Place" : "Ort" 'all day' : 'ganztags' 'All day' : 'Ganztags' "description" : "Beschreibung" "date" : "Datum" "Day" : "Tag" "days" : "Tage" "Edit" : "Bearbeiten" "Email" : "E-Mail" "Import" : "Import" "Export" : "Export" "show" : "Anzeigen" "hide" : "Verbergen" "List" : "Liste" "list" : "auflisten" "Calendar" : "Kalendar" "calendar" : "Kalendar" "Sync" : "Sync" "ie: 9:00 important meeting" : "z.B.: 9:00 wichtige Besprechung" "Month" : "Monat" "Popup" : "Popup" "Switch to List" : "Umschalten zu Liste" "Switch to Calendar" : "Umschalten zu Kalendar" "time" : "Zeit" "Today" : "Heute" 'today' : 'heute' "What should I remind you ?" : "An was soll ich Sie erinnern?" "ICalendar import" : "ICalendar importieren" "select an icalendar file" : "Auswählen einer ICalendar Datei" "import your icalendar file" : "Ihre ICalender Datei importieren" "confirm import" : "Importieren bestätigen" "cancel" : "abbrechen" "Create" : "Erstellen" "Events to import" : "Ereignisse zum Importieren" "Create Event" : "Ereignis erstellen" "From [hours:minutes]" : "von [Stunden:Minuten]" "To [hours:minutes]" : "bis [Stunden:Minuten]" "To [date]" : "bis [Datum]" "Description" : "Beschreibung" "days after" : "Tage dannach" "days later" : "Tage später" "Week" : "Woche" "Display" : "Mitteilung" "DISPLAY" : "Mitteilung" "EMAIL" : "E-Mail" "BOTH" : "E-Mail & Mitteilung" "display previous events" : "vorherige Ereignisse anzeigen" "display next events" : "nächste Ereignisse anzeigen" "event" : "Ereignis" "are you sure" : "Sind Sie sicher?" "confirm delete calendar" : "Sie sind im Begriff alle Ereignisse in %{calendarName} zu löschen. Sind Sie sicher?" "advanced" : "Mehr Details" "enter email" : "E-Mail anzeigen" "ON" : "EIN" "OFF" : "AUS" "no description" : "Keine Beschreibung" "add calendar" : "Kalendar hinzufügen" "new calendar" : "Neuer Kalendar" # RRULE related "recurrence" : "Wiederholung" "recurrence rule" : "Wiederholungsregeln rules" "make reccurent" : "Wiederholung erstellen" "repeat every" : "Alle wiederholen" "no recurrence" : "Keine Wiederholung" "repeat on" : "Wiederholung ein" "repeat on date" : "wiederholen an Datum" "repeat on weekday" : "Täglich wiederholen" "repeat until" : "Wiederholen bis" "after" : "Nach" "repeat" : "Wiederholen" "forever" : "Immer" "occurences" : "Ereignis" "every" : "Alle" 'minutes' : 'Minuten' 'minute' : 'Minute' 'minute ' : 'Minute' 'hours' : 'Stunden' 'hour' : 'Stunde' "days" : "Tage" "day" : "Tag" "weeks" : "Wochen" "week" : "Woche" "months" : "Monate" "month" : "Monat" "years" : "Jahre" "year" : "Jahr" "until" : "bis" "for" : "für" "on" : "am" "on the" : "am" "th" : "te" "nd" : "te" "rd" : "te" "st" : "te" "last" : "letzter" "and" : "und" "times" : "mal" "weekday" : "Wochentag" # MODAL "summary" : "Titel" "start" : "Start" "end" : "Ende" "tags" : "Tags" "add tags" : "Tags hinzufügen" "change" : "Wechsel" "change to" : "wechseln zu" "change calendar" : "Kalendar wechseln" "save changes" : "Änderungen speichern" "save changes and invite guests" : "Änderungen speichern und Gäste einladen" "guests" : "Gäste" "cancel Invitation" : "Einladung abbrechen" "From" : "Von" "To" : "Zu" "All day, until" : "Alle Tage, bis" "All one day" : "Alle Tage" 'Reminders before the event' : 'Errinnern vor dem Ereignis' "reminder" : "Erinnerung" # CONFIRM MODAL 'send mails question' : 'Eine Mitteilung senden an E-MAil: ' 'modal send mails' : 'Eine Mitteilung senden' 'yes' : 'Ja' 'no' : 'Nein' # ERRORS "no summary" : "Ein Titel muss vergeben werden." "start after end" : "Das Start-Datum liegt nach dem End-Datum." "invalid start date" : "Das Start-Datum ist ungültig." "invalid end date" : "Das End-Datum ist ungültig." "invalid trigg date" : "Das Datum ist ungültig." "invalid action" : "Die Aktion ist ungültig.." "server error occured" : "EIn Server Fehler ist aufgetreten." # SYNC "synchronization" : "Synchronisation" "mobile sync" : "Mobile Sync (CalDAV)" "link imported events with calendar": "Ereignis auswählen um mit folgendem Kalendar zu importieren:" "import an ical file" : "Um eine ICal Datei in Ihren Cozy Kalender zu importieren, bitte erst diese Schaltfläche zum vorladen drücken:" "download a copy of your calendar" : "Einen Kalender auswählen und dann die Export Schaltfläche drücken um eine Kopie des Kalenders als ICal Datei zu exportieren :" "icalendar export" : "ICalendar Export" "icalendar import" : "ICalendar Import" "to sync your cal with" : "Um Ihren Kalendar mit Ihren anderen Geräten zu synchronisieren müssen zwei Schritte ausgeführt werden" "sync headline with data" : "Um Ihren Kalendar zu synchronisieren, folgende Informationen beachten:" "sync url" : "URL:" "sync login" : "Benutzername:" "sync password" : "Passwort: " "sync help" : "Sind Sie verloren? Folgen Sie der " "sync help link" : "Schritt-für-Schritt Anleitung!" "install the sync module" : "Installieren Sie das Sync Module vom dem Cozy App Store" "connect to it and follow" : "Verbinden Sie sich mit ihm und folgend den Anweisungen zu CalDAV." "some event fail to save" : "Ein Ereignis wurde nicht gespeichert (ein Fehler ist aufgetreten)." "imported events": "Anzahl der importierten Ereignisse" "import finished": "Ihr Import ist nun fertig gestellt" "import error occured for": "Fehler bei Import für folgende Elemente aufgetreten" "export your calendar": "Exportieren Sie Ihren Kalendar" 'please select existing calendar' : 'Bitte wählen Sie einen bestehenden Kalendar aus.' # DATE "January" : "Januar" "February" : "Februar" "March" : "März" "April" : "April" "May" : "Mai" "June" : "Juni" "July" : "Juli" "August" : "August" "September" : "September" "October" : "Oktober" "November" : "November" "December" : "Dezember" "January" : "Januar" "February" : "Februar" 'Jan' : 'Jan' 'Feb' : 'Feb' 'Mar' : 'Mär' 'Apr' : 'Apr' 'Jun' : 'Jun' 'Jul' : 'Jul' 'Aug' : 'Aug' 'Sep' : 'Sep' 'Oct' : 'Okt' 'Nov' : 'Nov' 'Dec' : 'Dez' 'calendar exist error': 'Ein Kalendar mit dem Namenn "Neuer Kalendar" existiert bereits.' # Emails 'email date format': 'DD/MM/YYYY [à] HH[h]mm' 'email date format allday': 'DD/MM/YYYY, [ganztags]' 'email invitation title': 'Einladung z "%{description}"' 'email invitation content': """ Hallo, ich lade Sie zu folgendem Ereignis ein: %{description} %{place} am %{date} Bitte um Zusage/Absage? Ja %{url}?status=ACCEPTED&key=%{key} Nein %{url}?status=DECLINED&key=%{key} """ 'email update title': "Betreff \"%{description}\" a changé" 'email update content': """ Ein Ereignis zu dem Sie eingeladen wurden, hat sich geändert: %{description} %{place} am %{date} Weiterhin; Zusage %{url}?status=ACCEPTED&key=%{key} Nein leider; Absage %{url}?status=DECLINED&key=%{key} """ 'email delete title': 'Diese Ereignis wurde abgesagt: %{description}' 'email delete content': """ Dieses Ereignis wurde abgesagt: %{description} %{place} am %{date} """
185942
module.exports = "default calendar name" : "Mein Kalendar" "Add" : "Hinzufügen" "event" : "Ereignis" "create event" : "Ereignis erstellen" "edit event" : "Ereignis bearbeiten" "edit" : "Bearbeiten" "create" : "Erstellen" "creation" : "Erstellung" "invite" : "Einladen" "close" : "Schließen" "delete" : "Löschen" "change color" : "Farbe ändern" "rename" : "Umbennen" "export" : "Exportieren" "remove" : "Ereignis entfernen" "duplicate" : "Ereignis duplizieren" "Place" : "Ort" 'all day' : 'ganztags' 'All day' : 'Ganztags' "description" : "Beschreibung" "date" : "Datum" "Day" : "Tag" "days" : "Tage" "Edit" : "Bearbeiten" "Email" : "E-Mail" "Import" : "Import" "Export" : "Export" "show" : "Anzeigen" "hide" : "Verbergen" "List" : "Liste" "list" : "auflisten" "Calendar" : "Kalendar" "calendar" : "Kalendar" "Sync" : "Sync" "ie: 9:00 important meeting" : "z.B.: 9:00 wichtige Besprechung" "Month" : "Monat" "Popup" : "Popup" "Switch to List" : "Umschalten zu Liste" "Switch to Calendar" : "Umschalten zu Kalendar" "time" : "Zeit" "Today" : "Heute" 'today' : 'heute' "What should I remind you ?" : "An was soll ich Sie erinnern?" "ICalendar import" : "ICalendar importieren" "select an icalendar file" : "Auswählen einer ICalendar Datei" "import your icalendar file" : "Ihre ICalender Datei importieren" "confirm import" : "Importieren bestätigen" "cancel" : "abbrechen" "Create" : "Erstellen" "Events to import" : "Ereignisse zum Importieren" "Create Event" : "Ereignis erstellen" "From [hours:minutes]" : "von [Stunden:Minuten]" "To [hours:minutes]" : "bis [Stunden:Minuten]" "To [date]" : "bis [Datum]" "Description" : "Beschreibung" "days after" : "Tage dannach" "days later" : "Tage später" "Week" : "Woche" "Display" : "Mitteilung" "DISPLAY" : "Mitteilung" "EMAIL" : "E-Mail" "BOTH" : "E-Mail & Mitteilung" "display previous events" : "vorherige Ereignisse anzeigen" "display next events" : "nächste Ereignisse anzeigen" "event" : "Ereignis" "are you sure" : "Sind Sie sicher?" "confirm delete calendar" : "Sie sind im Begriff alle Ereignisse in %{calendarName} zu löschen. Sind Sie sicher?" "advanced" : "Mehr Details" "enter email" : "E-Mail anzeigen" "ON" : "EIN" "OFF" : "AUS" "no description" : "Keine Beschreibung" "add calendar" : "Kalendar hinzufügen" "new calendar" : "Neuer Kalendar" # RRULE related "recurrence" : "Wiederholung" "recurrence rule" : "Wiederholungsregeln rules" "make reccurent" : "Wiederholung erstellen" "repeat every" : "Alle wiederholen" "no recurrence" : "Keine Wiederholung" "repeat on" : "Wiederholung ein" "repeat on date" : "wiederholen an Datum" "repeat on weekday" : "Täglich wiederholen" "repeat until" : "Wiederholen bis" "after" : "Nach" "repeat" : "Wiederholen" "forever" : "Immer" "occurences" : "Ereignis" "every" : "Alle" 'minutes' : 'Minuten' 'minute' : 'Minute' 'minute ' : 'Minute' 'hours' : 'Stunden' 'hour' : 'Stunde' "days" : "Tage" "day" : "Tag" "weeks" : "Wochen" "week" : "Woche" "months" : "Monate" "month" : "Monat" "years" : "Jahre" "year" : "Jahr" "until" : "bis" "for" : "für" "on" : "am" "on the" : "am" "th" : "te" "nd" : "te" "rd" : "te" "st" : "te" "last" : "letzter" "and" : "und" "times" : "mal" "weekday" : "Wochentag" # MODAL "summary" : "Titel" "start" : "Start" "end" : "Ende" "tags" : "Tags" "add tags" : "Tags hinzufügen" "change" : "Wechsel" "change to" : "wechseln zu" "change calendar" : "Kalendar wechseln" "save changes" : "Änderungen speichern" "save changes and invite guests" : "Änderungen speichern und Gäste einladen" "guests" : "<NAME>" "cancel Invitation" : "Einladung abbrechen" "From" : "Von" "To" : "Zu" "All day, until" : "Alle Tage, bis" "All one day" : "Alle Tage" 'Reminders before the event' : 'Errinnern vor dem Ereignis' "reminder" : "Erinnerung" # CONFIRM MODAL 'send mails question' : 'Eine Mitteilung senden an E-MAil: ' 'modal send mails' : 'Eine Mitteilung senden' 'yes' : 'Ja' 'no' : 'Nein' # ERRORS "no summary" : "Ein Titel muss vergeben werden." "start after end" : "Das Start-Datum liegt nach dem End-Datum." "invalid start date" : "Das Start-Datum ist ungültig." "invalid end date" : "Das End-Datum ist ungültig." "invalid trigg date" : "Das Datum ist ungültig." "invalid action" : "Die Aktion ist ungültig.." "server error occured" : "EIn Server Fehler ist aufgetreten." # SYNC "synchronization" : "Synchronisation" "mobile sync" : "Mobile Sync (CalDAV)" "link imported events with calendar": "Ereignis auswählen um mit folgendem Kalendar zu importieren:" "import an ical file" : "Um eine ICal Datei in Ihren Cozy Kalender zu importieren, bitte erst diese Schaltfläche zum vorladen drücken:" "download a copy of your calendar" : "Einen Kalender auswählen und dann die Export Schaltfläche drücken um eine Kopie des Kalenders als ICal Datei zu exportieren :" "icalendar export" : "ICalendar Export" "icalendar import" : "ICalendar Import" "to sync your cal with" : "Um Ihren Kalendar mit Ihren anderen Geräten zu synchronisieren müssen zwei Schritte ausgeführt werden" "sync headline with data" : "Um Ihren Kalendar zu synchronisieren, folgende Informationen beachten:" "sync url" : "URL:" "sync login" : "Benutzername:" "sync password" : "<PASSWORD>: " "sync help" : "Sind Sie verloren? Folgen Sie der " "sync help link" : "Schritt-für-Schritt Anleitung!" "install the sync module" : "Installieren Sie das Sync Module vom dem Cozy App Store" "connect to it and follow" : "Verbinden Sie sich mit ihm und folgend den Anweisungen zu CalDAV." "some event fail to save" : "Ein Ereignis wurde nicht gespeichert (ein Fehler ist aufgetreten)." "imported events": "Anzahl der importierten Ereignisse" "import finished": "Ihr Import ist nun fertig gestellt" "import error occured for": "Fehler bei Import für folgende Elemente aufgetreten" "export your calendar": "Exportieren Sie Ihren Kalendar" 'please select existing calendar' : 'Bitte wählen Sie einen bestehenden Kalendar aus.' # DATE "January" : "Januar" "February" : "Februar" "March" : "März" "April" : "April" "May" : "Mai" "June" : "Juni" "July" : "Juli" "August" : "August" "September" : "September" "October" : "Oktober" "November" : "November" "December" : "Dezember" "January" : "Januar" "February" : "Februar" 'Jan' : '<NAME>' 'Feb' : 'Feb' 'Mar' : 'Mär' 'Apr' : 'Apr' 'Jun' : 'Jun' 'Jul' : 'Jul' 'Aug' : 'Aug' 'Sep' : 'Sep' 'Oct' : 'Okt' 'Nov' : 'Nov' 'Dec' : 'Dez' 'calendar exist error': 'Ein Kalendar mit dem Namenn "Neuer Kalendar" existiert bereits.' # Emails 'email date format': 'DD/MM/YYYY [à] HH[h]mm' 'email date format allday': 'DD/MM/YYYY, [ganztags]' 'email invitation title': 'Einladung z "%{description}"' 'email invitation content': """ Hallo, ich lade Sie zu folgendem Ereignis ein: %{description} %{place} am %{date} Bitte um Zusage/Absage? Ja %{url}?status=ACCEPTED&key=%{key} Nein %{url}?status=DECLINED&key=%{key} """ 'email update title': "Betreff \"%{description}\" a changé" 'email update content': """ Ein Ereignis zu dem Sie eingeladen wurden, hat sich geändert: %{description} %{place} am %{date} Weiterhin; Zusage %{url}?status=ACCEPTED&key=%{key} Nein leider; Absage %{url}?status=DECLINED&key=%{key} """ 'email delete title': 'Diese Ereignis wurde abgesagt: %{description}' 'email delete content': """ Dieses Ereignis wurde abgesagt: %{description} %{place} am %{date} """
true
module.exports = "default calendar name" : "Mein Kalendar" "Add" : "Hinzufügen" "event" : "Ereignis" "create event" : "Ereignis erstellen" "edit event" : "Ereignis bearbeiten" "edit" : "Bearbeiten" "create" : "Erstellen" "creation" : "Erstellung" "invite" : "Einladen" "close" : "Schließen" "delete" : "Löschen" "change color" : "Farbe ändern" "rename" : "Umbennen" "export" : "Exportieren" "remove" : "Ereignis entfernen" "duplicate" : "Ereignis duplizieren" "Place" : "Ort" 'all day' : 'ganztags' 'All day' : 'Ganztags' "description" : "Beschreibung" "date" : "Datum" "Day" : "Tag" "days" : "Tage" "Edit" : "Bearbeiten" "Email" : "E-Mail" "Import" : "Import" "Export" : "Export" "show" : "Anzeigen" "hide" : "Verbergen" "List" : "Liste" "list" : "auflisten" "Calendar" : "Kalendar" "calendar" : "Kalendar" "Sync" : "Sync" "ie: 9:00 important meeting" : "z.B.: 9:00 wichtige Besprechung" "Month" : "Monat" "Popup" : "Popup" "Switch to List" : "Umschalten zu Liste" "Switch to Calendar" : "Umschalten zu Kalendar" "time" : "Zeit" "Today" : "Heute" 'today' : 'heute' "What should I remind you ?" : "An was soll ich Sie erinnern?" "ICalendar import" : "ICalendar importieren" "select an icalendar file" : "Auswählen einer ICalendar Datei" "import your icalendar file" : "Ihre ICalender Datei importieren" "confirm import" : "Importieren bestätigen" "cancel" : "abbrechen" "Create" : "Erstellen" "Events to import" : "Ereignisse zum Importieren" "Create Event" : "Ereignis erstellen" "From [hours:minutes]" : "von [Stunden:Minuten]" "To [hours:minutes]" : "bis [Stunden:Minuten]" "To [date]" : "bis [Datum]" "Description" : "Beschreibung" "days after" : "Tage dannach" "days later" : "Tage später" "Week" : "Woche" "Display" : "Mitteilung" "DISPLAY" : "Mitteilung" "EMAIL" : "E-Mail" "BOTH" : "E-Mail & Mitteilung" "display previous events" : "vorherige Ereignisse anzeigen" "display next events" : "nächste Ereignisse anzeigen" "event" : "Ereignis" "are you sure" : "Sind Sie sicher?" "confirm delete calendar" : "Sie sind im Begriff alle Ereignisse in %{calendarName} zu löschen. Sind Sie sicher?" "advanced" : "Mehr Details" "enter email" : "E-Mail anzeigen" "ON" : "EIN" "OFF" : "AUS" "no description" : "Keine Beschreibung" "add calendar" : "Kalendar hinzufügen" "new calendar" : "Neuer Kalendar" # RRULE related "recurrence" : "Wiederholung" "recurrence rule" : "Wiederholungsregeln rules" "make reccurent" : "Wiederholung erstellen" "repeat every" : "Alle wiederholen" "no recurrence" : "Keine Wiederholung" "repeat on" : "Wiederholung ein" "repeat on date" : "wiederholen an Datum" "repeat on weekday" : "Täglich wiederholen" "repeat until" : "Wiederholen bis" "after" : "Nach" "repeat" : "Wiederholen" "forever" : "Immer" "occurences" : "Ereignis" "every" : "Alle" 'minutes' : 'Minuten' 'minute' : 'Minute' 'minute ' : 'Minute' 'hours' : 'Stunden' 'hour' : 'Stunde' "days" : "Tage" "day" : "Tag" "weeks" : "Wochen" "week" : "Woche" "months" : "Monate" "month" : "Monat" "years" : "Jahre" "year" : "Jahr" "until" : "bis" "for" : "für" "on" : "am" "on the" : "am" "th" : "te" "nd" : "te" "rd" : "te" "st" : "te" "last" : "letzter" "and" : "und" "times" : "mal" "weekday" : "Wochentag" # MODAL "summary" : "Titel" "start" : "Start" "end" : "Ende" "tags" : "Tags" "add tags" : "Tags hinzufügen" "change" : "Wechsel" "change to" : "wechseln zu" "change calendar" : "Kalendar wechseln" "save changes" : "Änderungen speichern" "save changes and invite guests" : "Änderungen speichern und Gäste einladen" "guests" : "PI:NAME:<NAME>END_PI" "cancel Invitation" : "Einladung abbrechen" "From" : "Von" "To" : "Zu" "All day, until" : "Alle Tage, bis" "All one day" : "Alle Tage" 'Reminders before the event' : 'Errinnern vor dem Ereignis' "reminder" : "Erinnerung" # CONFIRM MODAL 'send mails question' : 'Eine Mitteilung senden an E-MAil: ' 'modal send mails' : 'Eine Mitteilung senden' 'yes' : 'Ja' 'no' : 'Nein' # ERRORS "no summary" : "Ein Titel muss vergeben werden." "start after end" : "Das Start-Datum liegt nach dem End-Datum." "invalid start date" : "Das Start-Datum ist ungültig." "invalid end date" : "Das End-Datum ist ungültig." "invalid trigg date" : "Das Datum ist ungültig." "invalid action" : "Die Aktion ist ungültig.." "server error occured" : "EIn Server Fehler ist aufgetreten." # SYNC "synchronization" : "Synchronisation" "mobile sync" : "Mobile Sync (CalDAV)" "link imported events with calendar": "Ereignis auswählen um mit folgendem Kalendar zu importieren:" "import an ical file" : "Um eine ICal Datei in Ihren Cozy Kalender zu importieren, bitte erst diese Schaltfläche zum vorladen drücken:" "download a copy of your calendar" : "Einen Kalender auswählen und dann die Export Schaltfläche drücken um eine Kopie des Kalenders als ICal Datei zu exportieren :" "icalendar export" : "ICalendar Export" "icalendar import" : "ICalendar Import" "to sync your cal with" : "Um Ihren Kalendar mit Ihren anderen Geräten zu synchronisieren müssen zwei Schritte ausgeführt werden" "sync headline with data" : "Um Ihren Kalendar zu synchronisieren, folgende Informationen beachten:" "sync url" : "URL:" "sync login" : "Benutzername:" "sync password" : "PI:PASSWORD:<PASSWORD>END_PI: " "sync help" : "Sind Sie verloren? Folgen Sie der " "sync help link" : "Schritt-für-Schritt Anleitung!" "install the sync module" : "Installieren Sie das Sync Module vom dem Cozy App Store" "connect to it and follow" : "Verbinden Sie sich mit ihm und folgend den Anweisungen zu CalDAV." "some event fail to save" : "Ein Ereignis wurde nicht gespeichert (ein Fehler ist aufgetreten)." "imported events": "Anzahl der importierten Ereignisse" "import finished": "Ihr Import ist nun fertig gestellt" "import error occured for": "Fehler bei Import für folgende Elemente aufgetreten" "export your calendar": "Exportieren Sie Ihren Kalendar" 'please select existing calendar' : 'Bitte wählen Sie einen bestehenden Kalendar aus.' # DATE "January" : "Januar" "February" : "Februar" "March" : "März" "April" : "April" "May" : "Mai" "June" : "Juni" "July" : "Juli" "August" : "August" "September" : "September" "October" : "Oktober" "November" : "November" "December" : "Dezember" "January" : "Januar" "February" : "Februar" 'Jan' : 'PI:NAME:<NAME>END_PI' 'Feb' : 'Feb' 'Mar' : 'Mär' 'Apr' : 'Apr' 'Jun' : 'Jun' 'Jul' : 'Jul' 'Aug' : 'Aug' 'Sep' : 'Sep' 'Oct' : 'Okt' 'Nov' : 'Nov' 'Dec' : 'Dez' 'calendar exist error': 'Ein Kalendar mit dem Namenn "Neuer Kalendar" existiert bereits.' # Emails 'email date format': 'DD/MM/YYYY [à] HH[h]mm' 'email date format allday': 'DD/MM/YYYY, [ganztags]' 'email invitation title': 'Einladung z "%{description}"' 'email invitation content': """ Hallo, ich lade Sie zu folgendem Ereignis ein: %{description} %{place} am %{date} Bitte um Zusage/Absage? Ja %{url}?status=ACCEPTED&key=%{key} Nein %{url}?status=DECLINED&key=%{key} """ 'email update title': "Betreff \"%{description}\" a changé" 'email update content': """ Ein Ereignis zu dem Sie eingeladen wurden, hat sich geändert: %{description} %{place} am %{date} Weiterhin; Zusage %{url}?status=ACCEPTED&key=%{key} Nein leider; Absage %{url}?status=DECLINED&key=%{key} """ 'email delete title': 'Diese Ereignis wurde abgesagt: %{description}' 'email delete content': """ Dieses Ereignis wurde abgesagt: %{description} %{place} am %{date} """
[ { "context": "cify this easily and deeply enough via params, but Joe wanted affiliation data out of unpaywall \n ", "end": 34057, "score": 0.9782816171646118, "start": 34054, "tag": "NAME", "value": "Joe" } ]
server/convert.coffee
leviathanindustries/noddy
2
import request from 'request' import { Converter } from 'csvtojson' import json2csv from 'json2csv' import textract from 'textract' # note this requires installs on the server for most conversions import mammoth from 'mammoth' import xlsx from 'xlsx' import xml2js from 'xml2js' import PDFParser from 'pdf2json' import stream from 'stream' import html2txt from 'html-to-text' #import canvg from 'canvg' import atob from 'atob' #import Canvas from 'canvas' # note canvas requires sudo apt-get install libcairo2-dev libjpeg-dev libpango1.0-dev libgif-dev build-essential g++ # canvas and canvg cannot be installed in a working manner any more, need to find an alternative solution later # canvg may still be ok. Actually these will both run, it is their underlying libs on ubuntu that cannot run import Future from 'fibers/future' import moment from 'moment' API.convert = {} API.add 'convert', desc: 'Convert files from one format to another. Provide content to convert as either "url" or "content" query param, or POST content as request body. Also provide "from" and "to" query params to identify the formats to convert from and to. It is also possible to provide a comma-separated list of "fields", which when converting from JSON will result in only those fields being used in the output (does not handle deep nesting). The currently available conversions are: svg to png. table to json or csv. csv to json or html or text. html to text. json to csv or text (or json again, which with "fields" can simplify json data). xml to text or json. pdf to text or json (which provides content and metadata). xls to json or csv or html or txt. google sheet (sheet) to json or csv or html or txt. list to string takes a json list of objects and convert it to a string. More conversions are possible, but require additional installations on the API machine, which are not turned on by default.' get: () -> if this.queryParams.url or this.queryParams.content or this.queryParams.es this.queryParams.fields = this.queryParams.fields.split(',') if this.queryParams.fields this.queryParams.from = 'xls' if this.queryParams.from in ['excel','xlsx'] this.queryParams.from = 'txt' if this.queryParams.from is 'text' this.queryParams.to = 'txt' if this.queryParams.to is 'text' this.queryParams.to = 'html' if this.queryParams.to is 'table' and this.queryParams.from in ['json','csv'] to = 'text/plain' to = 'text/csv' if this.queryParams.to is 'csv' to = 'image/png' if this.queryParams.to is 'png' to = 'application/' + this.queryParams.to if this.queryParams.to is 'json' or this.queryParams.to is 'xml' to = 'text/html' if this.queryParams.to is 'html' out = API.convert.run (this.queryParams.url ? this.queryParams.content), this.queryParams.from, this.queryParams.to, this.queryParams to = 'application/json' if typeof out is 'object' try return out if out.statusCode is 401 or out.status is 'error' if to is 'text/csv' this.response.writeHead 200, 'Content-disposition': "attachment; filename=convert.csv" 'Content-type': to + '; charset=UTF-8' 'Content-Encoding': 'UTF-8' this.response.end out else return statusCode: 200 headers: 'Content-Type': to body: out else return {data: 'Accepts URLs of content files and converts them. from csv to json,txt. from html to txt. from xml to txt, json. from pdf to txt. from file to txt. For json to csv a subset param can be provided, giving dot notation to the part of the json object that should be converted.'} post: () -> this.queryParams.fields = this.queryParams.fields.split(',') if this.queryParams.fields this.queryParams.from = 'xls' if this.queryParams.from in ['excel','xlsx'] this.queryParams.from = 'txt' if this.queryParams.from is 'text' this.queryParams.to = 'txt' if this.queryParams.to is 'text' this.queryParams.to = 'html' if this.queryParams.to is 'table' and this.queryParams.from in ['json','csv'] to = 'text/plain' to = 'text/csv' if this.queryParams.to is 'csv' to = 'image/png' if this.queryParams.to is 'png' to = 'application/' + this.queryParams.to if this.queryParams.to is 'json' or this.queryParams.to is 'xml' out = API.convert.run (if this.request.files? and this.request.files.length > 0 then this.request.files[0].data else this.request.body), this.queryParams.from, this.queryParams.to, this.queryParams to = 'application/json' if typeof out is 'object' try return out if out.statusCode is 401 or out.status is 'error' if to is 'text/csv' this.response.writeHead 200, 'Content-disposition': "attachment; filename=convert.csv" 'Content-type': to + '; charset=UTF-8' 'Content-Encoding': 'UTF-8' this.response.end out else return statusCode: 200 headers: 'Content-Type': to body: out API.convert.run = (content,from,to,opts={}) -> from ?= opts.from to ?= opts.to if from is 'svg' and to is 'png' output = API.convert.svg2png(content,opts) else if from is 'table' and to in ['json','csv'] output = API.convert['table2' + to](content,opts) else if from is 'csv' if to.indexOf('json') isnt -1 output = API.convert.csv2json(content,opts) else if to.indexOf('html') isnt -1 content = API.convert.csv2json content, opts workbook = xlsx.utils.json_to_sheet content output = API.convert._workbook2 'html', workbook, opts else if to.indexOf('txt') isnt -1 from = 'file' else if from is 'html' and to.indexOf('txt') isnt -1 output = API.convert.html2txt(content) else if from is 'json' if opts.es user = API.accounts.retrieve({apikey:opts.apikey}) if opts.apikey uid = if user then user._id else undefined # because could be querying a public ES endpoint params = {} if opts.es.indexOf('?') isnt -1 prs = opts.es.split('?')[1] parts = prs.split('&') for p in parts kp = p.split('=') params[kp[0]] = kp[1] opts.es = opts.es.split('?')[0] opts.es = opts.es.substring(1,opts.es.length-1) if opts.es.substring(0,1) is '/' rts = opts.es.split('/') content = API.es.action(uid,'GET',rts,params) return content if content.statusCode is 401 delete opts.es delete opts.apikey if to.indexOf('csv') isnt -1 output = API.convert.json2csv(content,opts) if to.indexOf('html') isnt -1 workbook = xlsx.utils.json_to_sheet content output = API.convert._workbook2 'html', workbook, opts else if to.indexOf('txt') isnt -1 from = 'file' else if to.indexOf('json') isnt -1 output = API.convert.json2json(content,opts) else if from is 'xml' and to in ['txt','json'] output = API.convert['xml2' + to](content) else if from is 'pdf' and to in ['txt','json'] output = API.convert['pdf2' + to](content,opts) else if from is 'docx' and to in ['txt','text'] output = API.convert.docx2txt content, opts else if from is 'docx' and to is 'html' output = API.convert.docx2html content, opts else if from is 'docx' and to is 'markdown' output = API.convert.docx2markdown content, opts else if from in ['xls','sheet','list'] and to in ['txt','json','html','csv','string'] output = API.convert[from + '2' + to](content,opts) if from is 'file' and to.indexOf('txt') isnt -1 # some of the above switch to this, so separate loop output = API.convert.file2txt(content,opts) if not output? return {status: 'error', data: 'conversion from ' + from + ' to ' + to + ' is not currently possible.'} else return output API.convert.svg2png = (content,opts) -> return false # need alternative to canvas and canvg for newer ubuntu where they try to use old libgif4 that can no longer run '''content = HTTP.call('GET',content,{npmRequestOptions:{encoding:null}}).content if content.indexOf('http') is 0 content = content.toString('utf-8') if Buffer.isBuffer content content = atob(content.substring('data:image/svg+xml;base64,'.length)) if content.indexOf('data:image/svg+xml;base64,') >= 0 canvas = new Canvas() canvg canvas, content, { ignoreMouse: true, ignoreAnimation: true, ImageClass: Canvas.Image } stream = canvas.pngStream() data = [] done = false stream.on 'data', (chunk) -> data.push chunk stream.on 'end', () -> done = true while not done future = new Future() Meteor.setTimeout (() -> future.return()), 500 future.wait() return Buffer.concat data''' API.convert.csv2json = Async.wrap (content,opts,callback) -> if typeof opts isnt 'object' callback = opts opts = {} content = HTTP.call('GET', content).content if content.indexOf('http') is 0 converter = new Converter({}) converter.fromString content, (err,result) -> return callback(null,result) API.convert.table2json = (content,opts={}) -> content = API.http.puppeteer(content) if content.indexOf('http') is 0 content = content.split(opts.start)[1] if opts.start if content.indexOf('<table') isnt -1 content = '<table' + content.split('<table')[1] else if content.indexOf('<TABLE') isnt -1 content = '<TABLE' + content.split('<TABLE')[1] content = content.split(opts.end)[0] if opts.end if content.indexOf('</table') isnt -1 content = content.split('</table')[0] + '</table>' else if content.indexOf('</TABLE') isnt -1 content = content.split('</TABLE')[1] + '</TABLE>' content = content.replace(/\r?\n|\r/g,'') ths = content.match(/<th.*?<\/th/gi) headers = [] results = [] if ths? for h in ths str = API.http.decode h.replace(/<th.*?>/i,'').replace(/<\/th.*?/i,'').replace(/<.*?>/gi,'').replace(/\s\s+/g,' ').trim() str = 'UNKNOWN' if str.replace(/ /g,'').length is 0 headers.push str for r in content.split('<tr') if r.toLowerCase().indexOf('<th') is -1 result = {} row = r.replace(/.*?>/i,'').replace(/<\/tr.*?/i,'') vals = row.match(/<td.*?<\/td/gi) keycounter = 0 for d of vals val = vals[d].replace(/<.*?>/gi,'').replace('</td','') if headers.length > keycounter result[headers[keycounter]] = API.http.decode val keycounter += 1 if vals[d].toLowerCase().indexOf('colspan') isnt -1 try keycounter += parseInt(vals[d].toLowerCase().split('colspan')[1].split('>')[0].replace(/[^0-9]/,''))-1 delete result.UNKNOWN if result.UNKNOWN? if not _.isEmpty result results.push result return results API.convert.table2csv = (content,opts) -> d = API.convert.table2json(content,opts) return API.convert.json2csv(d) API.convert.html2txt = (content,render=false) -> if content.indexOf('http') is 0 content = if render then API.http.puppeteer(content) else HTTP.call('GET', content).content text = html2txt.fromString(content, {wordwrap: 130}) return text API.convert._mimes = { '.aac': 'audio/aac', # AAC audio '.abw': 'application/x-abiword', # AbiWord document '.arc': 'application/x-freearc', # Archive document (multiple files embedded) '.avi': 'video/x-msvideo', # AVI: Audio Video Interleave '.azw': 'application/vnd.amazon.ebook', # Amazon Kindle eBook format '.bin': 'application/octet-stream', # Any kind of binary data '.bmp': 'image/bmp', # Windows OS/2 Bitmap Graphics '.bz': 'application/x-bzip', # BZip archive '.bz2': 'application/x-bzip2', # BZip2 archive '.csh': 'application/x-csh', # C-Shell script '.css': 'text/css', # Cascading Style Sheets (CSS) '.csv': 'text/csv', # Comma-separated values (CSV) '.doc': 'application/msword', # Microsoft Word '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', # Microsoft Word (OpenXML) '.eot': 'application/vnd.ms-fontobject', # MS Embedded OpenType fonts '.epub': 'application/epub+zip', # Electronic publication (EPUB) '.gz': 'application/gzip', # GZip Compressed Archive '.gif': 'image/gif', # Graphics Interchange Format (GIF) '.htm': 'text/html', # HyperText Markup Language (HTML) '.ico': 'image/vnd.microsoft.icon', # Icon format '.ics': 'text/calendar', # iCalendar format '.jar': 'application/java-archive', # Java Archive (JAR) '.jpg': 'image/jpeg', # JPEG images '.js': 'text/javascript', # JavaScript '.json': 'application/json', # JSON format '.jsonld': 'application/ld+json', # JSON-LD format '.mid': 'audio/midi', # Musical Instrument Digital Interface (MIDI) audio/x-midi '.mjs': 'text/javascript', # JavaScript module '.mp3': 'audio/mpeg', # MP3 audio '.mpeg': 'video/mpeg', # MPEG Video '.mpkg': 'application/vnd.apple.installer+xml', # Apple Installer Package '.odp': 'application/vnd.oasis.opendocument.presentation', # OpenDocument presentation document '.ods': 'application/vnd.oasis.opendocument.spreadsheet', # OpenDocument spreadsheet document '.odt': 'application/vnd.oasis.opendocument.text', # OpenDocument text document '.oga': 'audio/ogg', # OGG audio '.ogv': 'video/ogg', # OGG video '.ogx': 'application/ogg', # OGG '.opus': 'audio/opus', # Opus audio '.otf': 'font/otf', # OpenType font '.png': 'image/png', # Portable Network Graphics '.pdf': 'application/pdf', # Adobe Portable Document Format (PDF) '.php': 'application/php', # Hypertext Preprocessor (Personal Home Page) '.ppt': 'application/vnd.ms-powerpoint', # Microsoft PowerPoint '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', # Microsoft PowerPoint (OpenXML) '.py': 'text/plain', '.rar': 'application/vnd.rar', # RAR archive '.rb': 'text/plain', '.rtf': 'application/rtf', # Rich Text Format (RTF) '.sh': 'application/x-sh', # Bourne shell script '.svg': 'image/svg+xml', # Scalable Vector Graphics (SVG) '.swf': 'application/x-shockwave-flash', # Small web format (SWF) or Adobe Flash document '.tar': 'application/x-tar', # Tape Archive (TAR) '.tif': 'image/tiff', # Tagged Image File Format (TIFF) '.ts': 'video/mp2t', # MPEG transport stream '.ttf': 'font/ttf', # TrueType Font '.txt': 'text/plain', # Text, (generally ASCII or ISO 8859-n) '.vsd': 'application/vnd.visio', # Microsoft Visio '.wav': 'audio/wav', # Waveform Audio Format '.weba': 'audio/webm', # WEBM audio '.webm': 'video/webm', # WEBM video '.webp': 'image/webp', # WEBP image '.woff': 'font/woff', # Web Open Font Format (WOFF) '.woff2': 'font/woff2', # Web Open Font Format (WOFF) '.xhtml': 'application/xhtml+xml', # XHTML '.xls': 'application/vnd.ms-excel', # Microsoft Excel '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', # Microsoft Excel (OpenXML) '.xml': 'application/xml', # XML '.xul': 'application/vnd.mozilla.xul+xml', # XUL '.zip': 'application/zip', # ZIP archive '.3gp': 'video/3gpp', # 3GPP audio/video container audio/3gpp if it doesn't contain video '.3g2': 'video/3gpp2', # 3GPP2 audio/video container audio/3gpp2 if it doesn't contain video '.7z': 'application/x-7z-compressed' # 7-zip archive } API.convert.mime = (fn) -> # plus some programming languages with text/plain, useful for filtering on filenames tp = (if fn.indexOf('.') is -1 then fn else fn.substr(fn.lastIndexOf('.')+1)).toLowerCase() tp = 'htm' if tp is 'html' tp = 'jpg' if tp is 'jpeg' tp = 'tif' if tp is 'tiff' tp = 'mid' if tp is 'midi' mime = API.convert._mimes['.'+tp] return if typeof mime is 'string' then mime else false API.convert._docx2 = Async.wrap (what='txt', content, opts={}, callback) -> if typeof opts isnt 'object' callback = opts opts = {} if typeof content is 'string' and content.indexOf('http') is 0 content = API.http.getFile(content).data if typeof content is 'string' content = new Buffer content try # NOTE the convert to html fails within mammoth, but txt and markdown both work. Could add a markdown to html converter later if necessary # some mammoth calls just go off into nowhere - need a way to return, but it throws no error no done... mammoth[(if what is 'html' then 'convertToHTML' else if what is 'markdown' then 'convertToMarkdown' else 'extractRawText')]({buffer: content}) .then((res) -> return callback null, res.value ).done() catch return callback null, '' API.convert.docx2txt = (content, opts={}) -> return API.convert._docx2 'txt', content, opts API.convert.docx2html = (content, opts={}) -> return API.convert._docx2 'html', content, opts API.convert.docx2markdown = (content, opts={}) -> return API.convert._docx2 'markdown', content, opts API.convert.file2txt = Async.wrap (content, opts={}, callback) -> if typeof opts isnt 'object' callback = opts opts = {} # NOTE for this to work, see textract on npm - requires other things (antiword for word docs) installed. May not be useful. opts.from = undefined if typeof opts.from is 'string' and opts.from.indexOf('/') is -1 # need a proper mime type here from = opts.from delete opts.from named = opts.name ? false delete opts.name if named and not from mime = API.convert.mime named if mime from = mime named = false from ?= 'application/msword' return API.convert.docx2txt(content, opts) if (typeof content is 'string' and content.split('?')[0].endsWith('.docx')) or (typeof named is 'string' and content.split('?')[0].endsWith('.docx')) try if typeof content is 'string' and content.indexOf('http') is 0 textract.fromUrl content, opts, ( err, result ) -> return callback null, result else if named if typeof content is 'string' content = new Buffer content textract.fromBufferWithName named, content, opts, ( err, result ) -> return callback null, result else if typeof content is 'string' content = new Buffer content textract.fromBufferWithMime from, content, opts, ( err, result ) -> return callback null, result catch return callback null, '' # xlsx has lots more useful options that could be used to get particular parts of sheets. See: # https://www.npmjs.com/package/xlsx API.convert._workbook2 = (what='csv', workbook, opts={}) -> # add some options to crop to certain rows here try res = xlsx.utils['sheet_to_' + what] workbook # this works if just one simple sheet catch sheets = workbook.SheetNames # this works if it is a sheet with names opts.sheet ?= sheets[0] res = xlsx.utils['sheet_to_' + what] workbook.Sheets[opts.sheet] res = res.split('<body>')[1].split('</body>')[0] if what is 'html' return res API.convert._xls2 = (what='csv', content, opts={}) -> content = new Buffer (if content.indexOf('http') is 0 then HTTP.call('GET',content,{npmRequestOptions:{encoding:null}}).content else content) workbook = xlsx.read content return API.convert._workbook2 what, workbook, opts API.convert._sheet2 = (what='csv', content, opts={}) -> content = API.use.google.sheets.feed content, opts workbook = xlsx.utils.json_to_sheet content return API.convert._workbook2 what, workbook, opts API.convert.xls2txt = (content, opts={}) -> return API.convert._xls2 'txt', content, opts API.convert.xls2html = (content, opts={}) -> return API.convert._xls2 'html', content, opts API.convert.xls2json = (content, opts={}) -> return API.convert._xls2 'json', content, opts API.convert.xls2csv = (content, opts={}) -> return API.convert._xls2 'csv', content, opts API.convert.sheet2txt = (content, opts={}) -> return API.convert._sheet2 'txt', content, opts API.convert.sheet2html = (content, opts={}) -> return API.convert._sheet2 'html', content, opts API.convert.sheet2csv = (content, opts={}) -> return API.convert._sheet2 'csv', content, opts API.convert.sheet2json = (content, opts={}) -> return API.convert._sheet2 'json', content, opts API.convert.pdf2txt = Async.wrap (content, opts={}, callback) -> if typeof opts isnt 'object' callback = opts opts = {} opts.timeout ?= 20000 pdfParser = new PDFParser(this,1) completed = false pdfParser.on "pdfParser_dataReady", (pdfData) -> completed = true if not pdfParser? return callback(null,'') else if opts.raw return callback null, pdfData else if opts.metadata return callback null, pdfData.formImage.Id else if opts.newlines isnt true and opts.pages isnt true strs = [] for p in pdfData.formImage.Pages for t in p.Texts for s in t.R strs.push decodeURIComponent s.T return callback null, if opts.list then strs else strs.join(' ') else res = pdfParser.getRawTextContent() res = res.replace(/\r\n/g,'\n') if opts.newlines isnt true res = res.replace(/\n/g,' ') if opts.pages isnt true res = res.replace(/----------------Page \([0-9].*?\) Break----------------/g,' ') return callback(null,res) # TODO some PDFs are capable of causing an error within the parser that it fails to catch - this needs further investigation at some point # https://dev.openaccessbutton.org/static/test-manuscripts/Unwelcome_Change-_Coming_to_Terms_with_Democratic_Backsliding_Lust.pdf # https://dev.openaccessbutton.org/static/test-manuscripts/weitz_hair_and_power_article.pdf pdfParser.on "pdfParser_dataError", (err) -> completed = true return callback(null,'') try console.log('CONVERT PDF retrieving from ' + content) if content.indexOf('http') is 0 and API.settings.dev content = new Buffer (if content.indexOf('http') is 0 then HTTP.call('GET',content,{timeout:opts.timeout,npmRequestOptions:{encoding:null}}).content else content) pdfParser.parseBuffer(content) catch return callback(null,'') # some PDF seem to cause an endless wait, such as # https://www.carolinaperformingarts.org/wp-content/uploads/2015/04/Butoh-Bibliography-guide.pdf # so only wait for up to a minute # but still found a worse problem. This URL: # https://www.thoracic.org/patients/patient-resources/breathing-in-america/resources/chapter-23-sleep-disordered-breathing.pdf # spikes cpu to 100% and never times out... weird. It does not take long to download normally. Have not figured out how to catch this... # and it makes the system unusable waited = 0 if not completed while waited <= opts.timeout and completed isnt true future = new Future() Meteor.setTimeout (() -> future.return()), 5000 future.wait() waited += 5000 if not completed console.log 'PDF to text conversion timed out at ' + waited pdfParser = undefined # does this kill the async process??? - not really, TODO fix this so it does not keep running and eat the memory return callback(null,'') API.convert.pdf2json = Async.wrap (content, opts={}, callback) -> if typeof opts isnt 'object' callback = opts opts = {} opts.timeout ?= 20000 pdfParser = new PDFParser(); pdfParser.on "pdfParser_dataReady", (pdfData) -> return callback(null,pdfData) pdfParser.on "pdfParser_dataError", () -> return callback(null,{}) try content = new Buffer (if content.indexOf('http') is 0 then HTTP.call('GET',content,{timeout:20000,npmRequestOptions:{encoding:null}}).content else content) pdfParser.parseBuffer(content) catch return callback(null,{}) waited = 0 while waited < opts.timeout future = new Future() Meteor.setTimeout (() -> future.return()), 5000 future.wait() waited += 5000 return callback(null,{}) API.convert.xml2txt = (content) -> return API.convert.file2txt(content,{from:'application/xml'}) API.convert._xml2json = Async.wrap (content, callback) -> content = HTTP.call('GET', content).content if content.indexOf('http') is 0 parser = new xml2js.Parser() parser.parseString content, (err, result) -> return callback(null,result) # make a neater version of xml converted straight to json API.convert._cleanJson = (val, k, clean) -> if typeof clean is 'function' val = clean(val, k) if _.isArray val vv = [] singleKeyObjects = true for v in val if typeof v isnt 'string' or v.replace(/ /g,'').replace(/\n/g,'') isnt '' cv = API.convert._cleanJson v, k, clean singleKeyObjects = typeof cv is 'object' and not _.isArray(cv) and _.keys(cv).length is 1 vv.push cv else singleKeyObjects = false if false #singleKeyObjects nv = [] for sv in vv nv.push sv[_.keys(sv)[0]] val = nv else val = if vv.length then if vv.length is 1 and typeof vv[0] is 'string' then vv[0] else vv else '' else if typeof val is 'object' keys = _.keys(val) if keys.length is 1 and (keys[0].toLowerCase() is k.toLowerCase() or (k.toLowerCase().split('').pop() is 's' and keys[0].toLowerCase() is k.toLowerCase().slice(0, -1))) val = API.convert._cleanJson val[keys[0]], k, clean else if val.$?.key? and val._? and keys.length is 2 nv = {} nv[val.$.key] = val._ val = nv else if val.$? and _.keys(val.$).length is 1 sk = _.keys(val.$)[0] val[sk] = val.$[sk] #API.convert._cleanJson val.$[sk], sk, clean delete val.$ else if val.$? and typeof val.$ is 'object' unique = true for dk of val.$ unique = dk not in keys if unique for dkk of val.$ val[dkk] = val.$[dkk] #API.convert._cleanJson val.$[dkk], dkk, clean delete val.$ ak = _.keys(val) if ak.length is 1 and typeof val[ak[0]] is 'string' and val[ak[0]].toLowerCase() is k.toLowerCase() val = '' else wk = _.without(ak,'_') for o of val val[o] = API.convert._cleanJson val[o], o, clean if o is '_' and typeof val[o] is 'string' and not val.value? if wk.length is 1 and val[wk[0]].toLowerCase() is k.toLowerCase() return val._ else val.value = val._ delete val._ return val API.convert.xml2json = (content, subset, clean=true) -> res = API.convert._xml2json content if clean is false return res else recs = [] res = [res] if not _.isArray res for row in res for k of row row[k] = API.convert._cleanJson row[k], k, clean recs.push row return if recs.length is 1 then recs[0] else recs # using meteorhacks:async and Async.wrap seems to work better than using Meteor.wrapAsync API.convert.json2csv = (content, opts={}) -> content = JSON.parse(HTTP.call('GET', content).content) if typeof content is 'string' and content.indexOf('http') is 0 content = JSON.parse JSON.stringify content content = [content] if typeof content is 'object' and not _.isArray content if opts.subset parts = opts.subset.split('.') delete opts.subset for p in parts if Array.isArray(content) c = [] for r in content c.push(r[p]) content = c else content = content[p] opts.fields = opts.fields.split(',') if typeof opts.fields is 'string' if not opts.fields? opts.fields = [] for o of content if typeof content[o] isnt 'object' content[o] = {jsn_split_rw_list: content[o]} opts.fields.push('jsn_split_rw_list') if 'jsn_split_rw_list' not in opts.fields else l = content[o] for k of l if Array.isArray l[k] if l[k].length is 0 opts.fields.push(k) if opts.fields.indexOf(k) is -1 l[k] = '' else if typeof l[k][0] is 'string' or typeof l[k][0] is 'number' opts.fields.push(k) if opts.fields.indexOf(k) is -1 l[k] = l[k].join(',') else if opts.flat # not the same as the lib opts.flatten for tk of l[k] itk = k + '.' + tk opts.fields.push(itk) if opts.fields.indexOf(itk) is -1 l[itk] ?= '' if typeof l[k][tk] is 'object' # and note this only goes down to objects in lists for otk of l[k][tk] etk = k + '.' + tk + '.' + otk opts.fields.push(etk) if opts.fields.indexOf(etk) is -1 l[etk] ?= '' l[etk] += (if l[etk].length then if typeof opts.flat is 'boolean' then ', ' else opts.flat else '') + (if _.isArray(l[k][tk][otk]) then l[k][tk][otk].join(',') else if typeof l[k][tk][otk] is 'object' then JSON.stringify(l[k][tk][otk]) else l[k][tk][otk]) else # note this would lead to this level of nested values being piled into one field even if they came from separate objects l[itk] += (if l[itk].length then if typeof opts.flat is 'boolean' then ', ' else opts.flat else '') + (if _.isArray(l[k][tk]) then l[k][tk].join(',') else if typeof l[k][tk] is 'object' then JSON.stringify(l[k][tk]) else l[k][tk]) else opts.fields.push(k) if opts.fields.indexOf(k) is -1 l[k] = JSON.stringify l[k] else opts.fields.push(k) if opts.fields.indexOf(k) is -1 else if _.isArray(opts.fields) and opts.fields.length is 1 for o of content if typeof content[o] isnt 'object' co = {} co[opts.fields[0]] = content[o] content[o] = co # an odd use of a stream here, passing it what is already a variable. But this # avoids json2csv OOM errors which seem to occur even if the memory is not all used # moving to all stream at some point would be nice, but not done yet... tf = new json2csv.Transform opts res = '' rs = new stream.Readable rs.push JSON.stringify content rs.push null rs.pipe tf done = false tf.on 'data', (chunk) -> res += chunk tf.on 'end', () -> done = true while not done future = new Future() Meteor.setTimeout (() -> future.return()), 500 future.wait() res = res.replace('"jsn_split_rw_list"\n','') if res.indexOf('"jsn_split_rw_list"') is 0 return res API.convert.json2keys = (content, opts={}) -> opts.flat = false keys = [] _extract = (content,key) -> if _.isArray content _extract(c,key) for c in content else if typeof content is 'object' for c of content key = if opts.flat and key then key + '.' + c else c kl = if opts.lowercase then key.toLowerCase() else key keys.push(kl) if kl not in keys _extract(content[c],key) _extract content return keys API.convert.json2txt = (content, opts={}) -> opts.unique ?= false opts.list ?= false opts.keys ?= false # means only occurrences of key strings in the text values - still would not include the actual keys opts.lowercase = true # only means matches on lowercase, still provides strings as found keys = if not opts.keys then API.convert.json2keys(content, opts) else [] strings = [] lstrings = [] _extract = (content) -> if _.isArray content _extract(c) for c in content else if typeof content is 'object' _extract(content[c]) for c of content else if content try cl = content.toLowerCase() catch cl = content if opts.numbers isnt false or isNaN(parseInt(content)) strings.push(content) if (opts.keys or content not in keys) and (not opts.unique or content not in strings) and (not opts.lowercase or cl not in lstrings) lstrings.push(cl) if cl not in lstrings _extract content return if opts.list then strings else strings.join(' ') # this does not really belong as a convert function, # but it seems to have no better place. It is used in aestivus to wrap .csv routes, but may also be useful direclty # on other custom written routes, so keep it here API.convert.json2csv2response = (ths, data, filename) -> rows = [] for dr in (if data?.hits?.hits? then data.hits.hits else data) if typeof dr isnt 'object' rows.push dr else rw = if dr._source? then dr._source else if dr.fields then dr.fields else dr for k of rw rw[k] = rw[k][0] if _.isArray(rw[k]) and rw[k].length is 1 rows.push rw csv = API.convert.json2csv rows, {fields:ths.queryParams?.fields ? ths.bodyParams?.fields} API.convert.csv2response ths, csv, filename API.convert.csv2response = (ths, csv, filename) -> filename ?= 'export_' + moment(Date.now(), "x").format("YYYY_MM_DD_HHmm_ss") + ".csv" ths.response.writeHead(200, {'Content-disposition': "attachment; filename=" + filename, 'Content-type': 'text/csv; charset=UTF-8', 'Content-Encoding': 'UTF-8'}) ths.response.end csv API.convert.json2json = (content, opts) -> content = HTTP.call('GET', content).content if content.indexOf('http') is 0 content = JSON.parse(content) if typeof content is 'string' if opts.subset parts = opts.subset.split('.') n = {} n[s] = content[s] for s in parts content = n if opts.fields recs = [] for r in content rec = {} rec[f] = r[f] for f in opts.fields recs.push rec content = recs return content API.convert.list2string = (content, opts={}) -> opts.newline ?= '\n' opts.join ?= ', ' st = '' try content = HTTP.call('GET', content).content if content.indexOf('http') is 0 content = API.convert.xml2json(content) if typeof content is 'string' and content.indexOf('<') is 0 content = API.convert.json2json(content,opts) if opts.subset? or opts.fields? content = content[opts.subset] if opts.subset? for row in content st += opts.newline if st isnt '' if typeof row is 'string' st += row else opts.order ?= _.keys row opts.order = opts.order.split(',') if typeof opts.order is 'string' first = true for o in opts.order if row[o]? if first first = false else st += opts.join if typeof row[o] is 'string' dt = row[o] else # can't easily specify this easily and deeply enough via params, but Joe wanted affiliation data out of unpaywall # which provides affiliation as a list of objects, each of which has at least a key called name. So make some assumptions dt = '' ob = if _.isArray(row[o]) then row[o] else [row[o]] for rw in ob dt += opts.join if dt isnt '' if typeof rw is 'string' dt += rw else for k of rw dt += (if opts.keys then k + ': ' else '') + rw[k] st += (if opts.keys then o + ': ' else '') + dt return if opts.json then {text: st} else st API.convert._hexMatch = '0': '0000', '1': '0001', '2': '0010', '3': '0011', '4': '0100', '5': '0101', '6': '0110', '7': '0111', '8': '1000', '9': '1001', 'a': '1010', 'b': '1011', 'c': '1100', 'd': '1101', 'e': '1110', 'f': '1111' API.convert.hex2binary = (ls,listed=false) -> ls = [ls] if not _.isArray ls res = [] for l in ls res.push API.convert._hexMatch[l.toLowerCase()] return if listed then res else res.join('') API.convert.binary2hex = (ls) -> # this needs work... if not _.isArray ls els = [] sls = ls.split('') pr = '' while sls.length pr += sls.shift() if pr.length is 4 els.push pr pr = '' ls = els res = [] hm = {} for k of API.convert._hexMatch hm[API.convert._hexMatch[k]] = k for l in ls res.push '0x' + hm[l] return new Buffer(res).toString() API.convert.buffer2binary = (buf) -> buf = buf.toString('hex') if Buffer.isBuffer buf buf = buf.replace /^0x/, '' #assert(/^[0-9a-fA-F]+$/.test(s)) ret = '' c = 0 while c < buf.length ret += API.convert.hex2binary buf[c] c++ return ret ################################################################################ ### API.add 'convert/test', get: roleRequired: if API.settings.dev then undefined else 'root' action: () -> return API.convert.test this.queryParams.fixtures API.convert.test = (fixtures) -> console.log('Starting convert test') if API.settings.dev if (fixtures === undefined && API.settings.fixtures && API.settings.fixtures.url) fixtures = API.settings.fixtures.url; if (fixtures === undefined) return {passed: false, failed: [], NOTE: 'fixtures.url MUST BE PROVIDED IN SETTINGS FOR THIS TEST TO RUN, and must point to a folder containing files called test in csv, html, pdf, xml and json format'} var result = {failed:[]}; result.csv2json = API.convert.run(fixtures + 'test.csv','csv','json'); result.table2json = API.convert.run(fixtures + 'test.html','table','json'); result.html2txt = API.convert.run(fixtures + 'test.html','html','txt'); //result.file2txt = API.convert.run(fixtures + 'test.doc','file','txt'); result.pdf2txt = API.convert.run(fixtures + 'test.doc','pdf','txt'); result.xml2txt = API.convert.run(fixtures + 'test.xml','xml','txt'); result.xml2json = API.convert.run(fixtures + 'test.xml','xml','json'); result.json2csv = API.convert.run(fixtures + 'test.json','json','csv'); result.json2json = API.convert.run(fixtures + 'test.json','json','json'); result.passed = result.passed isnt false and result.failed.length is 0 console.log('Ending collection test') if API.settings.dev return result ###
223499
import request from 'request' import { Converter } from 'csvtojson' import json2csv from 'json2csv' import textract from 'textract' # note this requires installs on the server for most conversions import mammoth from 'mammoth' import xlsx from 'xlsx' import xml2js from 'xml2js' import PDFParser from 'pdf2json' import stream from 'stream' import html2txt from 'html-to-text' #import canvg from 'canvg' import atob from 'atob' #import Canvas from 'canvas' # note canvas requires sudo apt-get install libcairo2-dev libjpeg-dev libpango1.0-dev libgif-dev build-essential g++ # canvas and canvg cannot be installed in a working manner any more, need to find an alternative solution later # canvg may still be ok. Actually these will both run, it is their underlying libs on ubuntu that cannot run import Future from 'fibers/future' import moment from 'moment' API.convert = {} API.add 'convert', desc: 'Convert files from one format to another. Provide content to convert as either "url" or "content" query param, or POST content as request body. Also provide "from" and "to" query params to identify the formats to convert from and to. It is also possible to provide a comma-separated list of "fields", which when converting from JSON will result in only those fields being used in the output (does not handle deep nesting). The currently available conversions are: svg to png. table to json or csv. csv to json or html or text. html to text. json to csv or text (or json again, which with "fields" can simplify json data). xml to text or json. pdf to text or json (which provides content and metadata). xls to json or csv or html or txt. google sheet (sheet) to json or csv or html or txt. list to string takes a json list of objects and convert it to a string. More conversions are possible, but require additional installations on the API machine, which are not turned on by default.' get: () -> if this.queryParams.url or this.queryParams.content or this.queryParams.es this.queryParams.fields = this.queryParams.fields.split(',') if this.queryParams.fields this.queryParams.from = 'xls' if this.queryParams.from in ['excel','xlsx'] this.queryParams.from = 'txt' if this.queryParams.from is 'text' this.queryParams.to = 'txt' if this.queryParams.to is 'text' this.queryParams.to = 'html' if this.queryParams.to is 'table' and this.queryParams.from in ['json','csv'] to = 'text/plain' to = 'text/csv' if this.queryParams.to is 'csv' to = 'image/png' if this.queryParams.to is 'png' to = 'application/' + this.queryParams.to if this.queryParams.to is 'json' or this.queryParams.to is 'xml' to = 'text/html' if this.queryParams.to is 'html' out = API.convert.run (this.queryParams.url ? this.queryParams.content), this.queryParams.from, this.queryParams.to, this.queryParams to = 'application/json' if typeof out is 'object' try return out if out.statusCode is 401 or out.status is 'error' if to is 'text/csv' this.response.writeHead 200, 'Content-disposition': "attachment; filename=convert.csv" 'Content-type': to + '; charset=UTF-8' 'Content-Encoding': 'UTF-8' this.response.end out else return statusCode: 200 headers: 'Content-Type': to body: out else return {data: 'Accepts URLs of content files and converts them. from csv to json,txt. from html to txt. from xml to txt, json. from pdf to txt. from file to txt. For json to csv a subset param can be provided, giving dot notation to the part of the json object that should be converted.'} post: () -> this.queryParams.fields = this.queryParams.fields.split(',') if this.queryParams.fields this.queryParams.from = 'xls' if this.queryParams.from in ['excel','xlsx'] this.queryParams.from = 'txt' if this.queryParams.from is 'text' this.queryParams.to = 'txt' if this.queryParams.to is 'text' this.queryParams.to = 'html' if this.queryParams.to is 'table' and this.queryParams.from in ['json','csv'] to = 'text/plain' to = 'text/csv' if this.queryParams.to is 'csv' to = 'image/png' if this.queryParams.to is 'png' to = 'application/' + this.queryParams.to if this.queryParams.to is 'json' or this.queryParams.to is 'xml' out = API.convert.run (if this.request.files? and this.request.files.length > 0 then this.request.files[0].data else this.request.body), this.queryParams.from, this.queryParams.to, this.queryParams to = 'application/json' if typeof out is 'object' try return out if out.statusCode is 401 or out.status is 'error' if to is 'text/csv' this.response.writeHead 200, 'Content-disposition': "attachment; filename=convert.csv" 'Content-type': to + '; charset=UTF-8' 'Content-Encoding': 'UTF-8' this.response.end out else return statusCode: 200 headers: 'Content-Type': to body: out API.convert.run = (content,from,to,opts={}) -> from ?= opts.from to ?= opts.to if from is 'svg' and to is 'png' output = API.convert.svg2png(content,opts) else if from is 'table' and to in ['json','csv'] output = API.convert['table2' + to](content,opts) else if from is 'csv' if to.indexOf('json') isnt -1 output = API.convert.csv2json(content,opts) else if to.indexOf('html') isnt -1 content = API.convert.csv2json content, opts workbook = xlsx.utils.json_to_sheet content output = API.convert._workbook2 'html', workbook, opts else if to.indexOf('txt') isnt -1 from = 'file' else if from is 'html' and to.indexOf('txt') isnt -1 output = API.convert.html2txt(content) else if from is 'json' if opts.es user = API.accounts.retrieve({apikey:opts.apikey}) if opts.apikey uid = if user then user._id else undefined # because could be querying a public ES endpoint params = {} if opts.es.indexOf('?') isnt -1 prs = opts.es.split('?')[1] parts = prs.split('&') for p in parts kp = p.split('=') params[kp[0]] = kp[1] opts.es = opts.es.split('?')[0] opts.es = opts.es.substring(1,opts.es.length-1) if opts.es.substring(0,1) is '/' rts = opts.es.split('/') content = API.es.action(uid,'GET',rts,params) return content if content.statusCode is 401 delete opts.es delete opts.apikey if to.indexOf('csv') isnt -1 output = API.convert.json2csv(content,opts) if to.indexOf('html') isnt -1 workbook = xlsx.utils.json_to_sheet content output = API.convert._workbook2 'html', workbook, opts else if to.indexOf('txt') isnt -1 from = 'file' else if to.indexOf('json') isnt -1 output = API.convert.json2json(content,opts) else if from is 'xml' and to in ['txt','json'] output = API.convert['xml2' + to](content) else if from is 'pdf' and to in ['txt','json'] output = API.convert['pdf2' + to](content,opts) else if from is 'docx' and to in ['txt','text'] output = API.convert.docx2txt content, opts else if from is 'docx' and to is 'html' output = API.convert.docx2html content, opts else if from is 'docx' and to is 'markdown' output = API.convert.docx2markdown content, opts else if from in ['xls','sheet','list'] and to in ['txt','json','html','csv','string'] output = API.convert[from + '2' + to](content,opts) if from is 'file' and to.indexOf('txt') isnt -1 # some of the above switch to this, so separate loop output = API.convert.file2txt(content,opts) if not output? return {status: 'error', data: 'conversion from ' + from + ' to ' + to + ' is not currently possible.'} else return output API.convert.svg2png = (content,opts) -> return false # need alternative to canvas and canvg for newer ubuntu where they try to use old libgif4 that can no longer run '''content = HTTP.call('GET',content,{npmRequestOptions:{encoding:null}}).content if content.indexOf('http') is 0 content = content.toString('utf-8') if Buffer.isBuffer content content = atob(content.substring('data:image/svg+xml;base64,'.length)) if content.indexOf('data:image/svg+xml;base64,') >= 0 canvas = new Canvas() canvg canvas, content, { ignoreMouse: true, ignoreAnimation: true, ImageClass: Canvas.Image } stream = canvas.pngStream() data = [] done = false stream.on 'data', (chunk) -> data.push chunk stream.on 'end', () -> done = true while not done future = new Future() Meteor.setTimeout (() -> future.return()), 500 future.wait() return Buffer.concat data''' API.convert.csv2json = Async.wrap (content,opts,callback) -> if typeof opts isnt 'object' callback = opts opts = {} content = HTTP.call('GET', content).content if content.indexOf('http') is 0 converter = new Converter({}) converter.fromString content, (err,result) -> return callback(null,result) API.convert.table2json = (content,opts={}) -> content = API.http.puppeteer(content) if content.indexOf('http') is 0 content = content.split(opts.start)[1] if opts.start if content.indexOf('<table') isnt -1 content = '<table' + content.split('<table')[1] else if content.indexOf('<TABLE') isnt -1 content = '<TABLE' + content.split('<TABLE')[1] content = content.split(opts.end)[0] if opts.end if content.indexOf('</table') isnt -1 content = content.split('</table')[0] + '</table>' else if content.indexOf('</TABLE') isnt -1 content = content.split('</TABLE')[1] + '</TABLE>' content = content.replace(/\r?\n|\r/g,'') ths = content.match(/<th.*?<\/th/gi) headers = [] results = [] if ths? for h in ths str = API.http.decode h.replace(/<th.*?>/i,'').replace(/<\/th.*?/i,'').replace(/<.*?>/gi,'').replace(/\s\s+/g,' ').trim() str = 'UNKNOWN' if str.replace(/ /g,'').length is 0 headers.push str for r in content.split('<tr') if r.toLowerCase().indexOf('<th') is -1 result = {} row = r.replace(/.*?>/i,'').replace(/<\/tr.*?/i,'') vals = row.match(/<td.*?<\/td/gi) keycounter = 0 for d of vals val = vals[d].replace(/<.*?>/gi,'').replace('</td','') if headers.length > keycounter result[headers[keycounter]] = API.http.decode val keycounter += 1 if vals[d].toLowerCase().indexOf('colspan') isnt -1 try keycounter += parseInt(vals[d].toLowerCase().split('colspan')[1].split('>')[0].replace(/[^0-9]/,''))-1 delete result.UNKNOWN if result.UNKNOWN? if not _.isEmpty result results.push result return results API.convert.table2csv = (content,opts) -> d = API.convert.table2json(content,opts) return API.convert.json2csv(d) API.convert.html2txt = (content,render=false) -> if content.indexOf('http') is 0 content = if render then API.http.puppeteer(content) else HTTP.call('GET', content).content text = html2txt.fromString(content, {wordwrap: 130}) return text API.convert._mimes = { '.aac': 'audio/aac', # AAC audio '.abw': 'application/x-abiword', # AbiWord document '.arc': 'application/x-freearc', # Archive document (multiple files embedded) '.avi': 'video/x-msvideo', # AVI: Audio Video Interleave '.azw': 'application/vnd.amazon.ebook', # Amazon Kindle eBook format '.bin': 'application/octet-stream', # Any kind of binary data '.bmp': 'image/bmp', # Windows OS/2 Bitmap Graphics '.bz': 'application/x-bzip', # BZip archive '.bz2': 'application/x-bzip2', # BZip2 archive '.csh': 'application/x-csh', # C-Shell script '.css': 'text/css', # Cascading Style Sheets (CSS) '.csv': 'text/csv', # Comma-separated values (CSV) '.doc': 'application/msword', # Microsoft Word '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', # Microsoft Word (OpenXML) '.eot': 'application/vnd.ms-fontobject', # MS Embedded OpenType fonts '.epub': 'application/epub+zip', # Electronic publication (EPUB) '.gz': 'application/gzip', # GZip Compressed Archive '.gif': 'image/gif', # Graphics Interchange Format (GIF) '.htm': 'text/html', # HyperText Markup Language (HTML) '.ico': 'image/vnd.microsoft.icon', # Icon format '.ics': 'text/calendar', # iCalendar format '.jar': 'application/java-archive', # Java Archive (JAR) '.jpg': 'image/jpeg', # JPEG images '.js': 'text/javascript', # JavaScript '.json': 'application/json', # JSON format '.jsonld': 'application/ld+json', # JSON-LD format '.mid': 'audio/midi', # Musical Instrument Digital Interface (MIDI) audio/x-midi '.mjs': 'text/javascript', # JavaScript module '.mp3': 'audio/mpeg', # MP3 audio '.mpeg': 'video/mpeg', # MPEG Video '.mpkg': 'application/vnd.apple.installer+xml', # Apple Installer Package '.odp': 'application/vnd.oasis.opendocument.presentation', # OpenDocument presentation document '.ods': 'application/vnd.oasis.opendocument.spreadsheet', # OpenDocument spreadsheet document '.odt': 'application/vnd.oasis.opendocument.text', # OpenDocument text document '.oga': 'audio/ogg', # OGG audio '.ogv': 'video/ogg', # OGG video '.ogx': 'application/ogg', # OGG '.opus': 'audio/opus', # Opus audio '.otf': 'font/otf', # OpenType font '.png': 'image/png', # Portable Network Graphics '.pdf': 'application/pdf', # Adobe Portable Document Format (PDF) '.php': 'application/php', # Hypertext Preprocessor (Personal Home Page) '.ppt': 'application/vnd.ms-powerpoint', # Microsoft PowerPoint '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', # Microsoft PowerPoint (OpenXML) '.py': 'text/plain', '.rar': 'application/vnd.rar', # RAR archive '.rb': 'text/plain', '.rtf': 'application/rtf', # Rich Text Format (RTF) '.sh': 'application/x-sh', # Bourne shell script '.svg': 'image/svg+xml', # Scalable Vector Graphics (SVG) '.swf': 'application/x-shockwave-flash', # Small web format (SWF) or Adobe Flash document '.tar': 'application/x-tar', # Tape Archive (TAR) '.tif': 'image/tiff', # Tagged Image File Format (TIFF) '.ts': 'video/mp2t', # MPEG transport stream '.ttf': 'font/ttf', # TrueType Font '.txt': 'text/plain', # Text, (generally ASCII or ISO 8859-n) '.vsd': 'application/vnd.visio', # Microsoft Visio '.wav': 'audio/wav', # Waveform Audio Format '.weba': 'audio/webm', # WEBM audio '.webm': 'video/webm', # WEBM video '.webp': 'image/webp', # WEBP image '.woff': 'font/woff', # Web Open Font Format (WOFF) '.woff2': 'font/woff2', # Web Open Font Format (WOFF) '.xhtml': 'application/xhtml+xml', # XHTML '.xls': 'application/vnd.ms-excel', # Microsoft Excel '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', # Microsoft Excel (OpenXML) '.xml': 'application/xml', # XML '.xul': 'application/vnd.mozilla.xul+xml', # XUL '.zip': 'application/zip', # ZIP archive '.3gp': 'video/3gpp', # 3GPP audio/video container audio/3gpp if it doesn't contain video '.3g2': 'video/3gpp2', # 3GPP2 audio/video container audio/3gpp2 if it doesn't contain video '.7z': 'application/x-7z-compressed' # 7-zip archive } API.convert.mime = (fn) -> # plus some programming languages with text/plain, useful for filtering on filenames tp = (if fn.indexOf('.') is -1 then fn else fn.substr(fn.lastIndexOf('.')+1)).toLowerCase() tp = 'htm' if tp is 'html' tp = 'jpg' if tp is 'jpeg' tp = 'tif' if tp is 'tiff' tp = 'mid' if tp is 'midi' mime = API.convert._mimes['.'+tp] return if typeof mime is 'string' then mime else false API.convert._docx2 = Async.wrap (what='txt', content, opts={}, callback) -> if typeof opts isnt 'object' callback = opts opts = {} if typeof content is 'string' and content.indexOf('http') is 0 content = API.http.getFile(content).data if typeof content is 'string' content = new Buffer content try # NOTE the convert to html fails within mammoth, but txt and markdown both work. Could add a markdown to html converter later if necessary # some mammoth calls just go off into nowhere - need a way to return, but it throws no error no done... mammoth[(if what is 'html' then 'convertToHTML' else if what is 'markdown' then 'convertToMarkdown' else 'extractRawText')]({buffer: content}) .then((res) -> return callback null, res.value ).done() catch return callback null, '' API.convert.docx2txt = (content, opts={}) -> return API.convert._docx2 'txt', content, opts API.convert.docx2html = (content, opts={}) -> return API.convert._docx2 'html', content, opts API.convert.docx2markdown = (content, opts={}) -> return API.convert._docx2 'markdown', content, opts API.convert.file2txt = Async.wrap (content, opts={}, callback) -> if typeof opts isnt 'object' callback = opts opts = {} # NOTE for this to work, see textract on npm - requires other things (antiword for word docs) installed. May not be useful. opts.from = undefined if typeof opts.from is 'string' and opts.from.indexOf('/') is -1 # need a proper mime type here from = opts.from delete opts.from named = opts.name ? false delete opts.name if named and not from mime = API.convert.mime named if mime from = mime named = false from ?= 'application/msword' return API.convert.docx2txt(content, opts) if (typeof content is 'string' and content.split('?')[0].endsWith('.docx')) or (typeof named is 'string' and content.split('?')[0].endsWith('.docx')) try if typeof content is 'string' and content.indexOf('http') is 0 textract.fromUrl content, opts, ( err, result ) -> return callback null, result else if named if typeof content is 'string' content = new Buffer content textract.fromBufferWithName named, content, opts, ( err, result ) -> return callback null, result else if typeof content is 'string' content = new Buffer content textract.fromBufferWithMime from, content, opts, ( err, result ) -> return callback null, result catch return callback null, '' # xlsx has lots more useful options that could be used to get particular parts of sheets. See: # https://www.npmjs.com/package/xlsx API.convert._workbook2 = (what='csv', workbook, opts={}) -> # add some options to crop to certain rows here try res = xlsx.utils['sheet_to_' + what] workbook # this works if just one simple sheet catch sheets = workbook.SheetNames # this works if it is a sheet with names opts.sheet ?= sheets[0] res = xlsx.utils['sheet_to_' + what] workbook.Sheets[opts.sheet] res = res.split('<body>')[1].split('</body>')[0] if what is 'html' return res API.convert._xls2 = (what='csv', content, opts={}) -> content = new Buffer (if content.indexOf('http') is 0 then HTTP.call('GET',content,{npmRequestOptions:{encoding:null}}).content else content) workbook = xlsx.read content return API.convert._workbook2 what, workbook, opts API.convert._sheet2 = (what='csv', content, opts={}) -> content = API.use.google.sheets.feed content, opts workbook = xlsx.utils.json_to_sheet content return API.convert._workbook2 what, workbook, opts API.convert.xls2txt = (content, opts={}) -> return API.convert._xls2 'txt', content, opts API.convert.xls2html = (content, opts={}) -> return API.convert._xls2 'html', content, opts API.convert.xls2json = (content, opts={}) -> return API.convert._xls2 'json', content, opts API.convert.xls2csv = (content, opts={}) -> return API.convert._xls2 'csv', content, opts API.convert.sheet2txt = (content, opts={}) -> return API.convert._sheet2 'txt', content, opts API.convert.sheet2html = (content, opts={}) -> return API.convert._sheet2 'html', content, opts API.convert.sheet2csv = (content, opts={}) -> return API.convert._sheet2 'csv', content, opts API.convert.sheet2json = (content, opts={}) -> return API.convert._sheet2 'json', content, opts API.convert.pdf2txt = Async.wrap (content, opts={}, callback) -> if typeof opts isnt 'object' callback = opts opts = {} opts.timeout ?= 20000 pdfParser = new PDFParser(this,1) completed = false pdfParser.on "pdfParser_dataReady", (pdfData) -> completed = true if not pdfParser? return callback(null,'') else if opts.raw return callback null, pdfData else if opts.metadata return callback null, pdfData.formImage.Id else if opts.newlines isnt true and opts.pages isnt true strs = [] for p in pdfData.formImage.Pages for t in p.Texts for s in t.R strs.push decodeURIComponent s.T return callback null, if opts.list then strs else strs.join(' ') else res = pdfParser.getRawTextContent() res = res.replace(/\r\n/g,'\n') if opts.newlines isnt true res = res.replace(/\n/g,' ') if opts.pages isnt true res = res.replace(/----------------Page \([0-9].*?\) Break----------------/g,' ') return callback(null,res) # TODO some PDFs are capable of causing an error within the parser that it fails to catch - this needs further investigation at some point # https://dev.openaccessbutton.org/static/test-manuscripts/Unwelcome_Change-_Coming_to_Terms_with_Democratic_Backsliding_Lust.pdf # https://dev.openaccessbutton.org/static/test-manuscripts/weitz_hair_and_power_article.pdf pdfParser.on "pdfParser_dataError", (err) -> completed = true return callback(null,'') try console.log('CONVERT PDF retrieving from ' + content) if content.indexOf('http') is 0 and API.settings.dev content = new Buffer (if content.indexOf('http') is 0 then HTTP.call('GET',content,{timeout:opts.timeout,npmRequestOptions:{encoding:null}}).content else content) pdfParser.parseBuffer(content) catch return callback(null,'') # some PDF seem to cause an endless wait, such as # https://www.carolinaperformingarts.org/wp-content/uploads/2015/04/Butoh-Bibliography-guide.pdf # so only wait for up to a minute # but still found a worse problem. This URL: # https://www.thoracic.org/patients/patient-resources/breathing-in-america/resources/chapter-23-sleep-disordered-breathing.pdf # spikes cpu to 100% and never times out... weird. It does not take long to download normally. Have not figured out how to catch this... # and it makes the system unusable waited = 0 if not completed while waited <= opts.timeout and completed isnt true future = new Future() Meteor.setTimeout (() -> future.return()), 5000 future.wait() waited += 5000 if not completed console.log 'PDF to text conversion timed out at ' + waited pdfParser = undefined # does this kill the async process??? - not really, TODO fix this so it does not keep running and eat the memory return callback(null,'') API.convert.pdf2json = Async.wrap (content, opts={}, callback) -> if typeof opts isnt 'object' callback = opts opts = {} opts.timeout ?= 20000 pdfParser = new PDFParser(); pdfParser.on "pdfParser_dataReady", (pdfData) -> return callback(null,pdfData) pdfParser.on "pdfParser_dataError", () -> return callback(null,{}) try content = new Buffer (if content.indexOf('http') is 0 then HTTP.call('GET',content,{timeout:20000,npmRequestOptions:{encoding:null}}).content else content) pdfParser.parseBuffer(content) catch return callback(null,{}) waited = 0 while waited < opts.timeout future = new Future() Meteor.setTimeout (() -> future.return()), 5000 future.wait() waited += 5000 return callback(null,{}) API.convert.xml2txt = (content) -> return API.convert.file2txt(content,{from:'application/xml'}) API.convert._xml2json = Async.wrap (content, callback) -> content = HTTP.call('GET', content).content if content.indexOf('http') is 0 parser = new xml2js.Parser() parser.parseString content, (err, result) -> return callback(null,result) # make a neater version of xml converted straight to json API.convert._cleanJson = (val, k, clean) -> if typeof clean is 'function' val = clean(val, k) if _.isArray val vv = [] singleKeyObjects = true for v in val if typeof v isnt 'string' or v.replace(/ /g,'').replace(/\n/g,'') isnt '' cv = API.convert._cleanJson v, k, clean singleKeyObjects = typeof cv is 'object' and not _.isArray(cv) and _.keys(cv).length is 1 vv.push cv else singleKeyObjects = false if false #singleKeyObjects nv = [] for sv in vv nv.push sv[_.keys(sv)[0]] val = nv else val = if vv.length then if vv.length is 1 and typeof vv[0] is 'string' then vv[0] else vv else '' else if typeof val is 'object' keys = _.keys(val) if keys.length is 1 and (keys[0].toLowerCase() is k.toLowerCase() or (k.toLowerCase().split('').pop() is 's' and keys[0].toLowerCase() is k.toLowerCase().slice(0, -1))) val = API.convert._cleanJson val[keys[0]], k, clean else if val.$?.key? and val._? and keys.length is 2 nv = {} nv[val.$.key] = val._ val = nv else if val.$? and _.keys(val.$).length is 1 sk = _.keys(val.$)[0] val[sk] = val.$[sk] #API.convert._cleanJson val.$[sk], sk, clean delete val.$ else if val.$? and typeof val.$ is 'object' unique = true for dk of val.$ unique = dk not in keys if unique for dkk of val.$ val[dkk] = val.$[dkk] #API.convert._cleanJson val.$[dkk], dkk, clean delete val.$ ak = _.keys(val) if ak.length is 1 and typeof val[ak[0]] is 'string' and val[ak[0]].toLowerCase() is k.toLowerCase() val = '' else wk = _.without(ak,'_') for o of val val[o] = API.convert._cleanJson val[o], o, clean if o is '_' and typeof val[o] is 'string' and not val.value? if wk.length is 1 and val[wk[0]].toLowerCase() is k.toLowerCase() return val._ else val.value = val._ delete val._ return val API.convert.xml2json = (content, subset, clean=true) -> res = API.convert._xml2json content if clean is false return res else recs = [] res = [res] if not _.isArray res for row in res for k of row row[k] = API.convert._cleanJson row[k], k, clean recs.push row return if recs.length is 1 then recs[0] else recs # using meteorhacks:async and Async.wrap seems to work better than using Meteor.wrapAsync API.convert.json2csv = (content, opts={}) -> content = JSON.parse(HTTP.call('GET', content).content) if typeof content is 'string' and content.indexOf('http') is 0 content = JSON.parse JSON.stringify content content = [content] if typeof content is 'object' and not _.isArray content if opts.subset parts = opts.subset.split('.') delete opts.subset for p in parts if Array.isArray(content) c = [] for r in content c.push(r[p]) content = c else content = content[p] opts.fields = opts.fields.split(',') if typeof opts.fields is 'string' if not opts.fields? opts.fields = [] for o of content if typeof content[o] isnt 'object' content[o] = {jsn_split_rw_list: content[o]} opts.fields.push('jsn_split_rw_list') if 'jsn_split_rw_list' not in opts.fields else l = content[o] for k of l if Array.isArray l[k] if l[k].length is 0 opts.fields.push(k) if opts.fields.indexOf(k) is -1 l[k] = '' else if typeof l[k][0] is 'string' or typeof l[k][0] is 'number' opts.fields.push(k) if opts.fields.indexOf(k) is -1 l[k] = l[k].join(',') else if opts.flat # not the same as the lib opts.flatten for tk of l[k] itk = k + '.' + tk opts.fields.push(itk) if opts.fields.indexOf(itk) is -1 l[itk] ?= '' if typeof l[k][tk] is 'object' # and note this only goes down to objects in lists for otk of l[k][tk] etk = k + '.' + tk + '.' + otk opts.fields.push(etk) if opts.fields.indexOf(etk) is -1 l[etk] ?= '' l[etk] += (if l[etk].length then if typeof opts.flat is 'boolean' then ', ' else opts.flat else '') + (if _.isArray(l[k][tk][otk]) then l[k][tk][otk].join(',') else if typeof l[k][tk][otk] is 'object' then JSON.stringify(l[k][tk][otk]) else l[k][tk][otk]) else # note this would lead to this level of nested values being piled into one field even if they came from separate objects l[itk] += (if l[itk].length then if typeof opts.flat is 'boolean' then ', ' else opts.flat else '') + (if _.isArray(l[k][tk]) then l[k][tk].join(',') else if typeof l[k][tk] is 'object' then JSON.stringify(l[k][tk]) else l[k][tk]) else opts.fields.push(k) if opts.fields.indexOf(k) is -1 l[k] = JSON.stringify l[k] else opts.fields.push(k) if opts.fields.indexOf(k) is -1 else if _.isArray(opts.fields) and opts.fields.length is 1 for o of content if typeof content[o] isnt 'object' co = {} co[opts.fields[0]] = content[o] content[o] = co # an odd use of a stream here, passing it what is already a variable. But this # avoids json2csv OOM errors which seem to occur even if the memory is not all used # moving to all stream at some point would be nice, but not done yet... tf = new json2csv.Transform opts res = '' rs = new stream.Readable rs.push JSON.stringify content rs.push null rs.pipe tf done = false tf.on 'data', (chunk) -> res += chunk tf.on 'end', () -> done = true while not done future = new Future() Meteor.setTimeout (() -> future.return()), 500 future.wait() res = res.replace('"jsn_split_rw_list"\n','') if res.indexOf('"jsn_split_rw_list"') is 0 return res API.convert.json2keys = (content, opts={}) -> opts.flat = false keys = [] _extract = (content,key) -> if _.isArray content _extract(c,key) for c in content else if typeof content is 'object' for c of content key = if opts.flat and key then key + '.' + c else c kl = if opts.lowercase then key.toLowerCase() else key keys.push(kl) if kl not in keys _extract(content[c],key) _extract content return keys API.convert.json2txt = (content, opts={}) -> opts.unique ?= false opts.list ?= false opts.keys ?= false # means only occurrences of key strings in the text values - still would not include the actual keys opts.lowercase = true # only means matches on lowercase, still provides strings as found keys = if not opts.keys then API.convert.json2keys(content, opts) else [] strings = [] lstrings = [] _extract = (content) -> if _.isArray content _extract(c) for c in content else if typeof content is 'object' _extract(content[c]) for c of content else if content try cl = content.toLowerCase() catch cl = content if opts.numbers isnt false or isNaN(parseInt(content)) strings.push(content) if (opts.keys or content not in keys) and (not opts.unique or content not in strings) and (not opts.lowercase or cl not in lstrings) lstrings.push(cl) if cl not in lstrings _extract content return if opts.list then strings else strings.join(' ') # this does not really belong as a convert function, # but it seems to have no better place. It is used in aestivus to wrap .csv routes, but may also be useful direclty # on other custom written routes, so keep it here API.convert.json2csv2response = (ths, data, filename) -> rows = [] for dr in (if data?.hits?.hits? then data.hits.hits else data) if typeof dr isnt 'object' rows.push dr else rw = if dr._source? then dr._source else if dr.fields then dr.fields else dr for k of rw rw[k] = rw[k][0] if _.isArray(rw[k]) and rw[k].length is 1 rows.push rw csv = API.convert.json2csv rows, {fields:ths.queryParams?.fields ? ths.bodyParams?.fields} API.convert.csv2response ths, csv, filename API.convert.csv2response = (ths, csv, filename) -> filename ?= 'export_' + moment(Date.now(), "x").format("YYYY_MM_DD_HHmm_ss") + ".csv" ths.response.writeHead(200, {'Content-disposition': "attachment; filename=" + filename, 'Content-type': 'text/csv; charset=UTF-8', 'Content-Encoding': 'UTF-8'}) ths.response.end csv API.convert.json2json = (content, opts) -> content = HTTP.call('GET', content).content if content.indexOf('http') is 0 content = JSON.parse(content) if typeof content is 'string' if opts.subset parts = opts.subset.split('.') n = {} n[s] = content[s] for s in parts content = n if opts.fields recs = [] for r in content rec = {} rec[f] = r[f] for f in opts.fields recs.push rec content = recs return content API.convert.list2string = (content, opts={}) -> opts.newline ?= '\n' opts.join ?= ', ' st = '' try content = HTTP.call('GET', content).content if content.indexOf('http') is 0 content = API.convert.xml2json(content) if typeof content is 'string' and content.indexOf('<') is 0 content = API.convert.json2json(content,opts) if opts.subset? or opts.fields? content = content[opts.subset] if opts.subset? for row in content st += opts.newline if st isnt '' if typeof row is 'string' st += row else opts.order ?= _.keys row opts.order = opts.order.split(',') if typeof opts.order is 'string' first = true for o in opts.order if row[o]? if first first = false else st += opts.join if typeof row[o] is 'string' dt = row[o] else # can't easily specify this easily and deeply enough via params, but <NAME> wanted affiliation data out of unpaywall # which provides affiliation as a list of objects, each of which has at least a key called name. So make some assumptions dt = '' ob = if _.isArray(row[o]) then row[o] else [row[o]] for rw in ob dt += opts.join if dt isnt '' if typeof rw is 'string' dt += rw else for k of rw dt += (if opts.keys then k + ': ' else '') + rw[k] st += (if opts.keys then o + ': ' else '') + dt return if opts.json then {text: st} else st API.convert._hexMatch = '0': '0000', '1': '0001', '2': '0010', '3': '0011', '4': '0100', '5': '0101', '6': '0110', '7': '0111', '8': '1000', '9': '1001', 'a': '1010', 'b': '1011', 'c': '1100', 'd': '1101', 'e': '1110', 'f': '1111' API.convert.hex2binary = (ls,listed=false) -> ls = [ls] if not _.isArray ls res = [] for l in ls res.push API.convert._hexMatch[l.toLowerCase()] return if listed then res else res.join('') API.convert.binary2hex = (ls) -> # this needs work... if not _.isArray ls els = [] sls = ls.split('') pr = '' while sls.length pr += sls.shift() if pr.length is 4 els.push pr pr = '' ls = els res = [] hm = {} for k of API.convert._hexMatch hm[API.convert._hexMatch[k]] = k for l in ls res.push '0x' + hm[l] return new Buffer(res).toString() API.convert.buffer2binary = (buf) -> buf = buf.toString('hex') if Buffer.isBuffer buf buf = buf.replace /^0x/, '' #assert(/^[0-9a-fA-F]+$/.test(s)) ret = '' c = 0 while c < buf.length ret += API.convert.hex2binary buf[c] c++ return ret ################################################################################ ### API.add 'convert/test', get: roleRequired: if API.settings.dev then undefined else 'root' action: () -> return API.convert.test this.queryParams.fixtures API.convert.test = (fixtures) -> console.log('Starting convert test') if API.settings.dev if (fixtures === undefined && API.settings.fixtures && API.settings.fixtures.url) fixtures = API.settings.fixtures.url; if (fixtures === undefined) return {passed: false, failed: [], NOTE: 'fixtures.url MUST BE PROVIDED IN SETTINGS FOR THIS TEST TO RUN, and must point to a folder containing files called test in csv, html, pdf, xml and json format'} var result = {failed:[]}; result.csv2json = API.convert.run(fixtures + 'test.csv','csv','json'); result.table2json = API.convert.run(fixtures + 'test.html','table','json'); result.html2txt = API.convert.run(fixtures + 'test.html','html','txt'); //result.file2txt = API.convert.run(fixtures + 'test.doc','file','txt'); result.pdf2txt = API.convert.run(fixtures + 'test.doc','pdf','txt'); result.xml2txt = API.convert.run(fixtures + 'test.xml','xml','txt'); result.xml2json = API.convert.run(fixtures + 'test.xml','xml','json'); result.json2csv = API.convert.run(fixtures + 'test.json','json','csv'); result.json2json = API.convert.run(fixtures + 'test.json','json','json'); result.passed = result.passed isnt false and result.failed.length is 0 console.log('Ending collection test') if API.settings.dev return result ###
true
import request from 'request' import { Converter } from 'csvtojson' import json2csv from 'json2csv' import textract from 'textract' # note this requires installs on the server for most conversions import mammoth from 'mammoth' import xlsx from 'xlsx' import xml2js from 'xml2js' import PDFParser from 'pdf2json' import stream from 'stream' import html2txt from 'html-to-text' #import canvg from 'canvg' import atob from 'atob' #import Canvas from 'canvas' # note canvas requires sudo apt-get install libcairo2-dev libjpeg-dev libpango1.0-dev libgif-dev build-essential g++ # canvas and canvg cannot be installed in a working manner any more, need to find an alternative solution later # canvg may still be ok. Actually these will both run, it is their underlying libs on ubuntu that cannot run import Future from 'fibers/future' import moment from 'moment' API.convert = {} API.add 'convert', desc: 'Convert files from one format to another. Provide content to convert as either "url" or "content" query param, or POST content as request body. Also provide "from" and "to" query params to identify the formats to convert from and to. It is also possible to provide a comma-separated list of "fields", which when converting from JSON will result in only those fields being used in the output (does not handle deep nesting). The currently available conversions are: svg to png. table to json or csv. csv to json or html or text. html to text. json to csv or text (or json again, which with "fields" can simplify json data). xml to text or json. pdf to text or json (which provides content and metadata). xls to json or csv or html or txt. google sheet (sheet) to json or csv or html or txt. list to string takes a json list of objects and convert it to a string. More conversions are possible, but require additional installations on the API machine, which are not turned on by default.' get: () -> if this.queryParams.url or this.queryParams.content or this.queryParams.es this.queryParams.fields = this.queryParams.fields.split(',') if this.queryParams.fields this.queryParams.from = 'xls' if this.queryParams.from in ['excel','xlsx'] this.queryParams.from = 'txt' if this.queryParams.from is 'text' this.queryParams.to = 'txt' if this.queryParams.to is 'text' this.queryParams.to = 'html' if this.queryParams.to is 'table' and this.queryParams.from in ['json','csv'] to = 'text/plain' to = 'text/csv' if this.queryParams.to is 'csv' to = 'image/png' if this.queryParams.to is 'png' to = 'application/' + this.queryParams.to if this.queryParams.to is 'json' or this.queryParams.to is 'xml' to = 'text/html' if this.queryParams.to is 'html' out = API.convert.run (this.queryParams.url ? this.queryParams.content), this.queryParams.from, this.queryParams.to, this.queryParams to = 'application/json' if typeof out is 'object' try return out if out.statusCode is 401 or out.status is 'error' if to is 'text/csv' this.response.writeHead 200, 'Content-disposition': "attachment; filename=convert.csv" 'Content-type': to + '; charset=UTF-8' 'Content-Encoding': 'UTF-8' this.response.end out else return statusCode: 200 headers: 'Content-Type': to body: out else return {data: 'Accepts URLs of content files and converts them. from csv to json,txt. from html to txt. from xml to txt, json. from pdf to txt. from file to txt. For json to csv a subset param can be provided, giving dot notation to the part of the json object that should be converted.'} post: () -> this.queryParams.fields = this.queryParams.fields.split(',') if this.queryParams.fields this.queryParams.from = 'xls' if this.queryParams.from in ['excel','xlsx'] this.queryParams.from = 'txt' if this.queryParams.from is 'text' this.queryParams.to = 'txt' if this.queryParams.to is 'text' this.queryParams.to = 'html' if this.queryParams.to is 'table' and this.queryParams.from in ['json','csv'] to = 'text/plain' to = 'text/csv' if this.queryParams.to is 'csv' to = 'image/png' if this.queryParams.to is 'png' to = 'application/' + this.queryParams.to if this.queryParams.to is 'json' or this.queryParams.to is 'xml' out = API.convert.run (if this.request.files? and this.request.files.length > 0 then this.request.files[0].data else this.request.body), this.queryParams.from, this.queryParams.to, this.queryParams to = 'application/json' if typeof out is 'object' try return out if out.statusCode is 401 or out.status is 'error' if to is 'text/csv' this.response.writeHead 200, 'Content-disposition': "attachment; filename=convert.csv" 'Content-type': to + '; charset=UTF-8' 'Content-Encoding': 'UTF-8' this.response.end out else return statusCode: 200 headers: 'Content-Type': to body: out API.convert.run = (content,from,to,opts={}) -> from ?= opts.from to ?= opts.to if from is 'svg' and to is 'png' output = API.convert.svg2png(content,opts) else if from is 'table' and to in ['json','csv'] output = API.convert['table2' + to](content,opts) else if from is 'csv' if to.indexOf('json') isnt -1 output = API.convert.csv2json(content,opts) else if to.indexOf('html') isnt -1 content = API.convert.csv2json content, opts workbook = xlsx.utils.json_to_sheet content output = API.convert._workbook2 'html', workbook, opts else if to.indexOf('txt') isnt -1 from = 'file' else if from is 'html' and to.indexOf('txt') isnt -1 output = API.convert.html2txt(content) else if from is 'json' if opts.es user = API.accounts.retrieve({apikey:opts.apikey}) if opts.apikey uid = if user then user._id else undefined # because could be querying a public ES endpoint params = {} if opts.es.indexOf('?') isnt -1 prs = opts.es.split('?')[1] parts = prs.split('&') for p in parts kp = p.split('=') params[kp[0]] = kp[1] opts.es = opts.es.split('?')[0] opts.es = opts.es.substring(1,opts.es.length-1) if opts.es.substring(0,1) is '/' rts = opts.es.split('/') content = API.es.action(uid,'GET',rts,params) return content if content.statusCode is 401 delete opts.es delete opts.apikey if to.indexOf('csv') isnt -1 output = API.convert.json2csv(content,opts) if to.indexOf('html') isnt -1 workbook = xlsx.utils.json_to_sheet content output = API.convert._workbook2 'html', workbook, opts else if to.indexOf('txt') isnt -1 from = 'file' else if to.indexOf('json') isnt -1 output = API.convert.json2json(content,opts) else if from is 'xml' and to in ['txt','json'] output = API.convert['xml2' + to](content) else if from is 'pdf' and to in ['txt','json'] output = API.convert['pdf2' + to](content,opts) else if from is 'docx' and to in ['txt','text'] output = API.convert.docx2txt content, opts else if from is 'docx' and to is 'html' output = API.convert.docx2html content, opts else if from is 'docx' and to is 'markdown' output = API.convert.docx2markdown content, opts else if from in ['xls','sheet','list'] and to in ['txt','json','html','csv','string'] output = API.convert[from + '2' + to](content,opts) if from is 'file' and to.indexOf('txt') isnt -1 # some of the above switch to this, so separate loop output = API.convert.file2txt(content,opts) if not output? return {status: 'error', data: 'conversion from ' + from + ' to ' + to + ' is not currently possible.'} else return output API.convert.svg2png = (content,opts) -> return false # need alternative to canvas and canvg for newer ubuntu where they try to use old libgif4 that can no longer run '''content = HTTP.call('GET',content,{npmRequestOptions:{encoding:null}}).content if content.indexOf('http') is 0 content = content.toString('utf-8') if Buffer.isBuffer content content = atob(content.substring('data:image/svg+xml;base64,'.length)) if content.indexOf('data:image/svg+xml;base64,') >= 0 canvas = new Canvas() canvg canvas, content, { ignoreMouse: true, ignoreAnimation: true, ImageClass: Canvas.Image } stream = canvas.pngStream() data = [] done = false stream.on 'data', (chunk) -> data.push chunk stream.on 'end', () -> done = true while not done future = new Future() Meteor.setTimeout (() -> future.return()), 500 future.wait() return Buffer.concat data''' API.convert.csv2json = Async.wrap (content,opts,callback) -> if typeof opts isnt 'object' callback = opts opts = {} content = HTTP.call('GET', content).content if content.indexOf('http') is 0 converter = new Converter({}) converter.fromString content, (err,result) -> return callback(null,result) API.convert.table2json = (content,opts={}) -> content = API.http.puppeteer(content) if content.indexOf('http') is 0 content = content.split(opts.start)[1] if opts.start if content.indexOf('<table') isnt -1 content = '<table' + content.split('<table')[1] else if content.indexOf('<TABLE') isnt -1 content = '<TABLE' + content.split('<TABLE')[1] content = content.split(opts.end)[0] if opts.end if content.indexOf('</table') isnt -1 content = content.split('</table')[0] + '</table>' else if content.indexOf('</TABLE') isnt -1 content = content.split('</TABLE')[1] + '</TABLE>' content = content.replace(/\r?\n|\r/g,'') ths = content.match(/<th.*?<\/th/gi) headers = [] results = [] if ths? for h in ths str = API.http.decode h.replace(/<th.*?>/i,'').replace(/<\/th.*?/i,'').replace(/<.*?>/gi,'').replace(/\s\s+/g,' ').trim() str = 'UNKNOWN' if str.replace(/ /g,'').length is 0 headers.push str for r in content.split('<tr') if r.toLowerCase().indexOf('<th') is -1 result = {} row = r.replace(/.*?>/i,'').replace(/<\/tr.*?/i,'') vals = row.match(/<td.*?<\/td/gi) keycounter = 0 for d of vals val = vals[d].replace(/<.*?>/gi,'').replace('</td','') if headers.length > keycounter result[headers[keycounter]] = API.http.decode val keycounter += 1 if vals[d].toLowerCase().indexOf('colspan') isnt -1 try keycounter += parseInt(vals[d].toLowerCase().split('colspan')[1].split('>')[0].replace(/[^0-9]/,''))-1 delete result.UNKNOWN if result.UNKNOWN? if not _.isEmpty result results.push result return results API.convert.table2csv = (content,opts) -> d = API.convert.table2json(content,opts) return API.convert.json2csv(d) API.convert.html2txt = (content,render=false) -> if content.indexOf('http') is 0 content = if render then API.http.puppeteer(content) else HTTP.call('GET', content).content text = html2txt.fromString(content, {wordwrap: 130}) return text API.convert._mimes = { '.aac': 'audio/aac', # AAC audio '.abw': 'application/x-abiword', # AbiWord document '.arc': 'application/x-freearc', # Archive document (multiple files embedded) '.avi': 'video/x-msvideo', # AVI: Audio Video Interleave '.azw': 'application/vnd.amazon.ebook', # Amazon Kindle eBook format '.bin': 'application/octet-stream', # Any kind of binary data '.bmp': 'image/bmp', # Windows OS/2 Bitmap Graphics '.bz': 'application/x-bzip', # BZip archive '.bz2': 'application/x-bzip2', # BZip2 archive '.csh': 'application/x-csh', # C-Shell script '.css': 'text/css', # Cascading Style Sheets (CSS) '.csv': 'text/csv', # Comma-separated values (CSV) '.doc': 'application/msword', # Microsoft Word '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', # Microsoft Word (OpenXML) '.eot': 'application/vnd.ms-fontobject', # MS Embedded OpenType fonts '.epub': 'application/epub+zip', # Electronic publication (EPUB) '.gz': 'application/gzip', # GZip Compressed Archive '.gif': 'image/gif', # Graphics Interchange Format (GIF) '.htm': 'text/html', # HyperText Markup Language (HTML) '.ico': 'image/vnd.microsoft.icon', # Icon format '.ics': 'text/calendar', # iCalendar format '.jar': 'application/java-archive', # Java Archive (JAR) '.jpg': 'image/jpeg', # JPEG images '.js': 'text/javascript', # JavaScript '.json': 'application/json', # JSON format '.jsonld': 'application/ld+json', # JSON-LD format '.mid': 'audio/midi', # Musical Instrument Digital Interface (MIDI) audio/x-midi '.mjs': 'text/javascript', # JavaScript module '.mp3': 'audio/mpeg', # MP3 audio '.mpeg': 'video/mpeg', # MPEG Video '.mpkg': 'application/vnd.apple.installer+xml', # Apple Installer Package '.odp': 'application/vnd.oasis.opendocument.presentation', # OpenDocument presentation document '.ods': 'application/vnd.oasis.opendocument.spreadsheet', # OpenDocument spreadsheet document '.odt': 'application/vnd.oasis.opendocument.text', # OpenDocument text document '.oga': 'audio/ogg', # OGG audio '.ogv': 'video/ogg', # OGG video '.ogx': 'application/ogg', # OGG '.opus': 'audio/opus', # Opus audio '.otf': 'font/otf', # OpenType font '.png': 'image/png', # Portable Network Graphics '.pdf': 'application/pdf', # Adobe Portable Document Format (PDF) '.php': 'application/php', # Hypertext Preprocessor (Personal Home Page) '.ppt': 'application/vnd.ms-powerpoint', # Microsoft PowerPoint '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation', # Microsoft PowerPoint (OpenXML) '.py': 'text/plain', '.rar': 'application/vnd.rar', # RAR archive '.rb': 'text/plain', '.rtf': 'application/rtf', # Rich Text Format (RTF) '.sh': 'application/x-sh', # Bourne shell script '.svg': 'image/svg+xml', # Scalable Vector Graphics (SVG) '.swf': 'application/x-shockwave-flash', # Small web format (SWF) or Adobe Flash document '.tar': 'application/x-tar', # Tape Archive (TAR) '.tif': 'image/tiff', # Tagged Image File Format (TIFF) '.ts': 'video/mp2t', # MPEG transport stream '.ttf': 'font/ttf', # TrueType Font '.txt': 'text/plain', # Text, (generally ASCII or ISO 8859-n) '.vsd': 'application/vnd.visio', # Microsoft Visio '.wav': 'audio/wav', # Waveform Audio Format '.weba': 'audio/webm', # WEBM audio '.webm': 'video/webm', # WEBM video '.webp': 'image/webp', # WEBP image '.woff': 'font/woff', # Web Open Font Format (WOFF) '.woff2': 'font/woff2', # Web Open Font Format (WOFF) '.xhtml': 'application/xhtml+xml', # XHTML '.xls': 'application/vnd.ms-excel', # Microsoft Excel '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', # Microsoft Excel (OpenXML) '.xml': 'application/xml', # XML '.xul': 'application/vnd.mozilla.xul+xml', # XUL '.zip': 'application/zip', # ZIP archive '.3gp': 'video/3gpp', # 3GPP audio/video container audio/3gpp if it doesn't contain video '.3g2': 'video/3gpp2', # 3GPP2 audio/video container audio/3gpp2 if it doesn't contain video '.7z': 'application/x-7z-compressed' # 7-zip archive } API.convert.mime = (fn) -> # plus some programming languages with text/plain, useful for filtering on filenames tp = (if fn.indexOf('.') is -1 then fn else fn.substr(fn.lastIndexOf('.')+1)).toLowerCase() tp = 'htm' if tp is 'html' tp = 'jpg' if tp is 'jpeg' tp = 'tif' if tp is 'tiff' tp = 'mid' if tp is 'midi' mime = API.convert._mimes['.'+tp] return if typeof mime is 'string' then mime else false API.convert._docx2 = Async.wrap (what='txt', content, opts={}, callback) -> if typeof opts isnt 'object' callback = opts opts = {} if typeof content is 'string' and content.indexOf('http') is 0 content = API.http.getFile(content).data if typeof content is 'string' content = new Buffer content try # NOTE the convert to html fails within mammoth, but txt and markdown both work. Could add a markdown to html converter later if necessary # some mammoth calls just go off into nowhere - need a way to return, but it throws no error no done... mammoth[(if what is 'html' then 'convertToHTML' else if what is 'markdown' then 'convertToMarkdown' else 'extractRawText')]({buffer: content}) .then((res) -> return callback null, res.value ).done() catch return callback null, '' API.convert.docx2txt = (content, opts={}) -> return API.convert._docx2 'txt', content, opts API.convert.docx2html = (content, opts={}) -> return API.convert._docx2 'html', content, opts API.convert.docx2markdown = (content, opts={}) -> return API.convert._docx2 'markdown', content, opts API.convert.file2txt = Async.wrap (content, opts={}, callback) -> if typeof opts isnt 'object' callback = opts opts = {} # NOTE for this to work, see textract on npm - requires other things (antiword for word docs) installed. May not be useful. opts.from = undefined if typeof opts.from is 'string' and opts.from.indexOf('/') is -1 # need a proper mime type here from = opts.from delete opts.from named = opts.name ? false delete opts.name if named and not from mime = API.convert.mime named if mime from = mime named = false from ?= 'application/msword' return API.convert.docx2txt(content, opts) if (typeof content is 'string' and content.split('?')[0].endsWith('.docx')) or (typeof named is 'string' and content.split('?')[0].endsWith('.docx')) try if typeof content is 'string' and content.indexOf('http') is 0 textract.fromUrl content, opts, ( err, result ) -> return callback null, result else if named if typeof content is 'string' content = new Buffer content textract.fromBufferWithName named, content, opts, ( err, result ) -> return callback null, result else if typeof content is 'string' content = new Buffer content textract.fromBufferWithMime from, content, opts, ( err, result ) -> return callback null, result catch return callback null, '' # xlsx has lots more useful options that could be used to get particular parts of sheets. See: # https://www.npmjs.com/package/xlsx API.convert._workbook2 = (what='csv', workbook, opts={}) -> # add some options to crop to certain rows here try res = xlsx.utils['sheet_to_' + what] workbook # this works if just one simple sheet catch sheets = workbook.SheetNames # this works if it is a sheet with names opts.sheet ?= sheets[0] res = xlsx.utils['sheet_to_' + what] workbook.Sheets[opts.sheet] res = res.split('<body>')[1].split('</body>')[0] if what is 'html' return res API.convert._xls2 = (what='csv', content, opts={}) -> content = new Buffer (if content.indexOf('http') is 0 then HTTP.call('GET',content,{npmRequestOptions:{encoding:null}}).content else content) workbook = xlsx.read content return API.convert._workbook2 what, workbook, opts API.convert._sheet2 = (what='csv', content, opts={}) -> content = API.use.google.sheets.feed content, opts workbook = xlsx.utils.json_to_sheet content return API.convert._workbook2 what, workbook, opts API.convert.xls2txt = (content, opts={}) -> return API.convert._xls2 'txt', content, opts API.convert.xls2html = (content, opts={}) -> return API.convert._xls2 'html', content, opts API.convert.xls2json = (content, opts={}) -> return API.convert._xls2 'json', content, opts API.convert.xls2csv = (content, opts={}) -> return API.convert._xls2 'csv', content, opts API.convert.sheet2txt = (content, opts={}) -> return API.convert._sheet2 'txt', content, opts API.convert.sheet2html = (content, opts={}) -> return API.convert._sheet2 'html', content, opts API.convert.sheet2csv = (content, opts={}) -> return API.convert._sheet2 'csv', content, opts API.convert.sheet2json = (content, opts={}) -> return API.convert._sheet2 'json', content, opts API.convert.pdf2txt = Async.wrap (content, opts={}, callback) -> if typeof opts isnt 'object' callback = opts opts = {} opts.timeout ?= 20000 pdfParser = new PDFParser(this,1) completed = false pdfParser.on "pdfParser_dataReady", (pdfData) -> completed = true if not pdfParser? return callback(null,'') else if opts.raw return callback null, pdfData else if opts.metadata return callback null, pdfData.formImage.Id else if opts.newlines isnt true and opts.pages isnt true strs = [] for p in pdfData.formImage.Pages for t in p.Texts for s in t.R strs.push decodeURIComponent s.T return callback null, if opts.list then strs else strs.join(' ') else res = pdfParser.getRawTextContent() res = res.replace(/\r\n/g,'\n') if opts.newlines isnt true res = res.replace(/\n/g,' ') if opts.pages isnt true res = res.replace(/----------------Page \([0-9].*?\) Break----------------/g,' ') return callback(null,res) # TODO some PDFs are capable of causing an error within the parser that it fails to catch - this needs further investigation at some point # https://dev.openaccessbutton.org/static/test-manuscripts/Unwelcome_Change-_Coming_to_Terms_with_Democratic_Backsliding_Lust.pdf # https://dev.openaccessbutton.org/static/test-manuscripts/weitz_hair_and_power_article.pdf pdfParser.on "pdfParser_dataError", (err) -> completed = true return callback(null,'') try console.log('CONVERT PDF retrieving from ' + content) if content.indexOf('http') is 0 and API.settings.dev content = new Buffer (if content.indexOf('http') is 0 then HTTP.call('GET',content,{timeout:opts.timeout,npmRequestOptions:{encoding:null}}).content else content) pdfParser.parseBuffer(content) catch return callback(null,'') # some PDF seem to cause an endless wait, such as # https://www.carolinaperformingarts.org/wp-content/uploads/2015/04/Butoh-Bibliography-guide.pdf # so only wait for up to a minute # but still found a worse problem. This URL: # https://www.thoracic.org/patients/patient-resources/breathing-in-america/resources/chapter-23-sleep-disordered-breathing.pdf # spikes cpu to 100% and never times out... weird. It does not take long to download normally. Have not figured out how to catch this... # and it makes the system unusable waited = 0 if not completed while waited <= opts.timeout and completed isnt true future = new Future() Meteor.setTimeout (() -> future.return()), 5000 future.wait() waited += 5000 if not completed console.log 'PDF to text conversion timed out at ' + waited pdfParser = undefined # does this kill the async process??? - not really, TODO fix this so it does not keep running and eat the memory return callback(null,'') API.convert.pdf2json = Async.wrap (content, opts={}, callback) -> if typeof opts isnt 'object' callback = opts opts = {} opts.timeout ?= 20000 pdfParser = new PDFParser(); pdfParser.on "pdfParser_dataReady", (pdfData) -> return callback(null,pdfData) pdfParser.on "pdfParser_dataError", () -> return callback(null,{}) try content = new Buffer (if content.indexOf('http') is 0 then HTTP.call('GET',content,{timeout:20000,npmRequestOptions:{encoding:null}}).content else content) pdfParser.parseBuffer(content) catch return callback(null,{}) waited = 0 while waited < opts.timeout future = new Future() Meteor.setTimeout (() -> future.return()), 5000 future.wait() waited += 5000 return callback(null,{}) API.convert.xml2txt = (content) -> return API.convert.file2txt(content,{from:'application/xml'}) API.convert._xml2json = Async.wrap (content, callback) -> content = HTTP.call('GET', content).content if content.indexOf('http') is 0 parser = new xml2js.Parser() parser.parseString content, (err, result) -> return callback(null,result) # make a neater version of xml converted straight to json API.convert._cleanJson = (val, k, clean) -> if typeof clean is 'function' val = clean(val, k) if _.isArray val vv = [] singleKeyObjects = true for v in val if typeof v isnt 'string' or v.replace(/ /g,'').replace(/\n/g,'') isnt '' cv = API.convert._cleanJson v, k, clean singleKeyObjects = typeof cv is 'object' and not _.isArray(cv) and _.keys(cv).length is 1 vv.push cv else singleKeyObjects = false if false #singleKeyObjects nv = [] for sv in vv nv.push sv[_.keys(sv)[0]] val = nv else val = if vv.length then if vv.length is 1 and typeof vv[0] is 'string' then vv[0] else vv else '' else if typeof val is 'object' keys = _.keys(val) if keys.length is 1 and (keys[0].toLowerCase() is k.toLowerCase() or (k.toLowerCase().split('').pop() is 's' and keys[0].toLowerCase() is k.toLowerCase().slice(0, -1))) val = API.convert._cleanJson val[keys[0]], k, clean else if val.$?.key? and val._? and keys.length is 2 nv = {} nv[val.$.key] = val._ val = nv else if val.$? and _.keys(val.$).length is 1 sk = _.keys(val.$)[0] val[sk] = val.$[sk] #API.convert._cleanJson val.$[sk], sk, clean delete val.$ else if val.$? and typeof val.$ is 'object' unique = true for dk of val.$ unique = dk not in keys if unique for dkk of val.$ val[dkk] = val.$[dkk] #API.convert._cleanJson val.$[dkk], dkk, clean delete val.$ ak = _.keys(val) if ak.length is 1 and typeof val[ak[0]] is 'string' and val[ak[0]].toLowerCase() is k.toLowerCase() val = '' else wk = _.without(ak,'_') for o of val val[o] = API.convert._cleanJson val[o], o, clean if o is '_' and typeof val[o] is 'string' and not val.value? if wk.length is 1 and val[wk[0]].toLowerCase() is k.toLowerCase() return val._ else val.value = val._ delete val._ return val API.convert.xml2json = (content, subset, clean=true) -> res = API.convert._xml2json content if clean is false return res else recs = [] res = [res] if not _.isArray res for row in res for k of row row[k] = API.convert._cleanJson row[k], k, clean recs.push row return if recs.length is 1 then recs[0] else recs # using meteorhacks:async and Async.wrap seems to work better than using Meteor.wrapAsync API.convert.json2csv = (content, opts={}) -> content = JSON.parse(HTTP.call('GET', content).content) if typeof content is 'string' and content.indexOf('http') is 0 content = JSON.parse JSON.stringify content content = [content] if typeof content is 'object' and not _.isArray content if opts.subset parts = opts.subset.split('.') delete opts.subset for p in parts if Array.isArray(content) c = [] for r in content c.push(r[p]) content = c else content = content[p] opts.fields = opts.fields.split(',') if typeof opts.fields is 'string' if not opts.fields? opts.fields = [] for o of content if typeof content[o] isnt 'object' content[o] = {jsn_split_rw_list: content[o]} opts.fields.push('jsn_split_rw_list') if 'jsn_split_rw_list' not in opts.fields else l = content[o] for k of l if Array.isArray l[k] if l[k].length is 0 opts.fields.push(k) if opts.fields.indexOf(k) is -1 l[k] = '' else if typeof l[k][0] is 'string' or typeof l[k][0] is 'number' opts.fields.push(k) if opts.fields.indexOf(k) is -1 l[k] = l[k].join(',') else if opts.flat # not the same as the lib opts.flatten for tk of l[k] itk = k + '.' + tk opts.fields.push(itk) if opts.fields.indexOf(itk) is -1 l[itk] ?= '' if typeof l[k][tk] is 'object' # and note this only goes down to objects in lists for otk of l[k][tk] etk = k + '.' + tk + '.' + otk opts.fields.push(etk) if opts.fields.indexOf(etk) is -1 l[etk] ?= '' l[etk] += (if l[etk].length then if typeof opts.flat is 'boolean' then ', ' else opts.flat else '') + (if _.isArray(l[k][tk][otk]) then l[k][tk][otk].join(',') else if typeof l[k][tk][otk] is 'object' then JSON.stringify(l[k][tk][otk]) else l[k][tk][otk]) else # note this would lead to this level of nested values being piled into one field even if they came from separate objects l[itk] += (if l[itk].length then if typeof opts.flat is 'boolean' then ', ' else opts.flat else '') + (if _.isArray(l[k][tk]) then l[k][tk].join(',') else if typeof l[k][tk] is 'object' then JSON.stringify(l[k][tk]) else l[k][tk]) else opts.fields.push(k) if opts.fields.indexOf(k) is -1 l[k] = JSON.stringify l[k] else opts.fields.push(k) if opts.fields.indexOf(k) is -1 else if _.isArray(opts.fields) and opts.fields.length is 1 for o of content if typeof content[o] isnt 'object' co = {} co[opts.fields[0]] = content[o] content[o] = co # an odd use of a stream here, passing it what is already a variable. But this # avoids json2csv OOM errors which seem to occur even if the memory is not all used # moving to all stream at some point would be nice, but not done yet... tf = new json2csv.Transform opts res = '' rs = new stream.Readable rs.push JSON.stringify content rs.push null rs.pipe tf done = false tf.on 'data', (chunk) -> res += chunk tf.on 'end', () -> done = true while not done future = new Future() Meteor.setTimeout (() -> future.return()), 500 future.wait() res = res.replace('"jsn_split_rw_list"\n','') if res.indexOf('"jsn_split_rw_list"') is 0 return res API.convert.json2keys = (content, opts={}) -> opts.flat = false keys = [] _extract = (content,key) -> if _.isArray content _extract(c,key) for c in content else if typeof content is 'object' for c of content key = if opts.flat and key then key + '.' + c else c kl = if opts.lowercase then key.toLowerCase() else key keys.push(kl) if kl not in keys _extract(content[c],key) _extract content return keys API.convert.json2txt = (content, opts={}) -> opts.unique ?= false opts.list ?= false opts.keys ?= false # means only occurrences of key strings in the text values - still would not include the actual keys opts.lowercase = true # only means matches on lowercase, still provides strings as found keys = if not opts.keys then API.convert.json2keys(content, opts) else [] strings = [] lstrings = [] _extract = (content) -> if _.isArray content _extract(c) for c in content else if typeof content is 'object' _extract(content[c]) for c of content else if content try cl = content.toLowerCase() catch cl = content if opts.numbers isnt false or isNaN(parseInt(content)) strings.push(content) if (opts.keys or content not in keys) and (not opts.unique or content not in strings) and (not opts.lowercase or cl not in lstrings) lstrings.push(cl) if cl not in lstrings _extract content return if opts.list then strings else strings.join(' ') # this does not really belong as a convert function, # but it seems to have no better place. It is used in aestivus to wrap .csv routes, but may also be useful direclty # on other custom written routes, so keep it here API.convert.json2csv2response = (ths, data, filename) -> rows = [] for dr in (if data?.hits?.hits? then data.hits.hits else data) if typeof dr isnt 'object' rows.push dr else rw = if dr._source? then dr._source else if dr.fields then dr.fields else dr for k of rw rw[k] = rw[k][0] if _.isArray(rw[k]) and rw[k].length is 1 rows.push rw csv = API.convert.json2csv rows, {fields:ths.queryParams?.fields ? ths.bodyParams?.fields} API.convert.csv2response ths, csv, filename API.convert.csv2response = (ths, csv, filename) -> filename ?= 'export_' + moment(Date.now(), "x").format("YYYY_MM_DD_HHmm_ss") + ".csv" ths.response.writeHead(200, {'Content-disposition': "attachment; filename=" + filename, 'Content-type': 'text/csv; charset=UTF-8', 'Content-Encoding': 'UTF-8'}) ths.response.end csv API.convert.json2json = (content, opts) -> content = HTTP.call('GET', content).content if content.indexOf('http') is 0 content = JSON.parse(content) if typeof content is 'string' if opts.subset parts = opts.subset.split('.') n = {} n[s] = content[s] for s in parts content = n if opts.fields recs = [] for r in content rec = {} rec[f] = r[f] for f in opts.fields recs.push rec content = recs return content API.convert.list2string = (content, opts={}) -> opts.newline ?= '\n' opts.join ?= ', ' st = '' try content = HTTP.call('GET', content).content if content.indexOf('http') is 0 content = API.convert.xml2json(content) if typeof content is 'string' and content.indexOf('<') is 0 content = API.convert.json2json(content,opts) if opts.subset? or opts.fields? content = content[opts.subset] if opts.subset? for row in content st += opts.newline if st isnt '' if typeof row is 'string' st += row else opts.order ?= _.keys row opts.order = opts.order.split(',') if typeof opts.order is 'string' first = true for o in opts.order if row[o]? if first first = false else st += opts.join if typeof row[o] is 'string' dt = row[o] else # can't easily specify this easily and deeply enough via params, but PI:NAME:<NAME>END_PI wanted affiliation data out of unpaywall # which provides affiliation as a list of objects, each of which has at least a key called name. So make some assumptions dt = '' ob = if _.isArray(row[o]) then row[o] else [row[o]] for rw in ob dt += opts.join if dt isnt '' if typeof rw is 'string' dt += rw else for k of rw dt += (if opts.keys then k + ': ' else '') + rw[k] st += (if opts.keys then o + ': ' else '') + dt return if opts.json then {text: st} else st API.convert._hexMatch = '0': '0000', '1': '0001', '2': '0010', '3': '0011', '4': '0100', '5': '0101', '6': '0110', '7': '0111', '8': '1000', '9': '1001', 'a': '1010', 'b': '1011', 'c': '1100', 'd': '1101', 'e': '1110', 'f': '1111' API.convert.hex2binary = (ls,listed=false) -> ls = [ls] if not _.isArray ls res = [] for l in ls res.push API.convert._hexMatch[l.toLowerCase()] return if listed then res else res.join('') API.convert.binary2hex = (ls) -> # this needs work... if not _.isArray ls els = [] sls = ls.split('') pr = '' while sls.length pr += sls.shift() if pr.length is 4 els.push pr pr = '' ls = els res = [] hm = {} for k of API.convert._hexMatch hm[API.convert._hexMatch[k]] = k for l in ls res.push '0x' + hm[l] return new Buffer(res).toString() API.convert.buffer2binary = (buf) -> buf = buf.toString('hex') if Buffer.isBuffer buf buf = buf.replace /^0x/, '' #assert(/^[0-9a-fA-F]+$/.test(s)) ret = '' c = 0 while c < buf.length ret += API.convert.hex2binary buf[c] c++ return ret ################################################################################ ### API.add 'convert/test', get: roleRequired: if API.settings.dev then undefined else 'root' action: () -> return API.convert.test this.queryParams.fixtures API.convert.test = (fixtures) -> console.log('Starting convert test') if API.settings.dev if (fixtures === undefined && API.settings.fixtures && API.settings.fixtures.url) fixtures = API.settings.fixtures.url; if (fixtures === undefined) return {passed: false, failed: [], NOTE: 'fixtures.url MUST BE PROVIDED IN SETTINGS FOR THIS TEST TO RUN, and must point to a folder containing files called test in csv, html, pdf, xml and json format'} var result = {failed:[]}; result.csv2json = API.convert.run(fixtures + 'test.csv','csv','json'); result.table2json = API.convert.run(fixtures + 'test.html','table','json'); result.html2txt = API.convert.run(fixtures + 'test.html','html','txt'); //result.file2txt = API.convert.run(fixtures + 'test.doc','file','txt'); result.pdf2txt = API.convert.run(fixtures + 'test.doc','pdf','txt'); result.xml2txt = API.convert.run(fixtures + 'test.xml','xml','txt'); result.xml2json = API.convert.run(fixtures + 'test.xml','xml','json'); result.json2csv = API.convert.run(fixtures + 'test.json','json','csv'); result.json2json = API.convert.run(fixtures + 'test.json','json','json'); result.passed = result.passed isnt false and result.failed.length is 0 console.log('Ending collection test') if API.settings.dev return result ###
[ { "context": "USERNAME: Gmail username\n# HUBOT_GMAIL_PASSWORD: Gmail password\n# OMNI_MAIL_DROP_ADDRESS: Private OmniSyncServe", "end": 230, "score": 0.9972230792045593, "start": 216, "tag": "PASSWORD", "value": "Gmail password" }, { "context": "item in OmniFocus with text 'Todo'\n#\n# Author:\n# lazerwalker\n\nmodule.exports = (robot) ->\n robot.respond /of ", "end": 453, "score": 0.9995189309120178, "start": 442, "tag": "USERNAME", "value": "lazerwalker" }, { "context": "er: process.env.HUBOT_GMAIL_USERNAME\n pass: process.env.HUBOT_GMAIL_PASSWORD\n\n from = process.env.HUBOT_EMAIL_", "end": 720, "score": 0.8771082162857056, "start": 701, "tag": "PASSWORD", "value": "process.env.HUBOT_G" }, { "context": "AIL_USERNAME\n pass: process.env.HUBOT_GMAIL_PASSWORD\n\n from = process.env.HUBOT_EMAIL_SENDE", "end": 724, "score": 0.537164032459259, "start": 724, "tag": "PASSWORD", "value": "" } ]
scripts/omnifocus.coffee
lazerwalker/lazerwalker-hubot-scripts
5
# Description: # Adds a task to the OmniFocus inbox # # Dependencies: # Nodemailer # # Configuration: # (currently assumes you're using Gmail) # HUBOT_GMAIL_USERNAME: Gmail username # HUBOT_GMAIL_PASSWORD: Gmail password # OMNI_MAIL_DROP_ADDRESS: Private OmniSyncServer address (see http://www.omnigroup.com/support/omnifocus-mail-drop) # # Commands: # of Todo - Adds an inbox item in OmniFocus with text 'Todo' # # Author: # lazerwalker module.exports = (robot) -> robot.respond /of (.*) ?$/i, (msg) -> todo = msg.match[1] mail = require('nodemailer').createTransport "SMTP", service: "Gmail" auth: user: process.env.HUBOT_GMAIL_USERNAME pass: process.env.HUBOT_GMAIL_PASSWORD from = process.env.HUBOT_EMAIL_SENDER to = process.env.OMNI_MAIL_DROP_ADDRESS options = {from, to, subject: todo} mail.sendMail options, (err, response) -> if err msg.send "OmniFocus error! #{err}" else msg.send "Added inbox item."
59043
# Description: # Adds a task to the OmniFocus inbox # # Dependencies: # Nodemailer # # Configuration: # (currently assumes you're using Gmail) # HUBOT_GMAIL_USERNAME: Gmail username # HUBOT_GMAIL_PASSWORD: <PASSWORD> # OMNI_MAIL_DROP_ADDRESS: Private OmniSyncServer address (see http://www.omnigroup.com/support/omnifocus-mail-drop) # # Commands: # of Todo - Adds an inbox item in OmniFocus with text 'Todo' # # Author: # lazerwalker module.exports = (robot) -> robot.respond /of (.*) ?$/i, (msg) -> todo = msg.match[1] mail = require('nodemailer').createTransport "SMTP", service: "Gmail" auth: user: process.env.HUBOT_GMAIL_USERNAME pass: <PASSWORD>MAIL<PASSWORD>_PASSWORD from = process.env.HUBOT_EMAIL_SENDER to = process.env.OMNI_MAIL_DROP_ADDRESS options = {from, to, subject: todo} mail.sendMail options, (err, response) -> if err msg.send "OmniFocus error! #{err}" else msg.send "Added inbox item."
true
# Description: # Adds a task to the OmniFocus inbox # # Dependencies: # Nodemailer # # Configuration: # (currently assumes you're using Gmail) # HUBOT_GMAIL_USERNAME: Gmail username # HUBOT_GMAIL_PASSWORD: PI:PASSWORD:<PASSWORD>END_PI # OMNI_MAIL_DROP_ADDRESS: Private OmniSyncServer address (see http://www.omnigroup.com/support/omnifocus-mail-drop) # # Commands: # of Todo - Adds an inbox item in OmniFocus with text 'Todo' # # Author: # lazerwalker module.exports = (robot) -> robot.respond /of (.*) ?$/i, (msg) -> todo = msg.match[1] mail = require('nodemailer').createTransport "SMTP", service: "Gmail" auth: user: process.env.HUBOT_GMAIL_USERNAME pass: PI:PASSWORD:<PASSWORD>END_PIMAILPI:PASSWORD:<PASSWORD>END_PI_PASSWORD from = process.env.HUBOT_EMAIL_SENDER to = process.env.OMNI_MAIL_DROP_ADDRESS options = {from, to, subject: todo} mail.sendMail options, (err, response) -> if err msg.send "OmniFocus error! #{err}" else msg.send "Added inbox item."
[ { "context": " = sinon.spy()\n arg1 = \"A\"\n arg2 = \"B\"\n notArg = \"C\"\n\n describe \"calledWith\",", "end": 176, "score": 0.6609664559364319, "start": 175, "tag": "NAME", "value": "B" } ]
vendor/sinon-chai/test/callArguments.coffee
asmblah/modular
1
describe "Call arguments", -> spy = null arg1 = null arg2 = null notArg = null beforeEach -> spy = sinon.spy() arg1 = "A" arg2 = "B" notArg = "C" describe "calledWith", -> it "should throw an assertion error when the spy is not called", -> expect(-> spy.should.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with the correct arguments", -> spy(arg1, arg2) expect(-> spy.should.have.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.getCall(0).should.have.been.calledWith(arg1, arg2)).to.not.throw() it "should not throw when the spy is called with the correct arguments and more", -> spy(arg1, arg2, notArg) expect(-> spy.should.have.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.getCall(0).should.have.been.calledWith(arg1, arg2)).to.not.throw() it "should throw an assertion error when the spy is called with incorrect arguments", -> spy(notArg, arg1) expect(-> spy.should.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.getCall(0).should.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with incorrect arguments but then correct ones", -> spy(notArg, arg1) spy(arg1, arg2) expect(-> spy.should.have.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.getCall(1).should.have.been.calledWith(arg1, arg2)).to.not.throw() describe "always calledWith", -> it "should throw an assertion error when the spy is not called", -> expect(-> spy.should.always.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWith(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with the correct arguments", -> spy(arg1, arg2) expect(-> spy.should.always.have.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.should.have.always.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.should.have.been.always.calledWith(arg1, arg2)).to.not.throw() it "should not throw when the spy is called with the correct arguments and more", -> spy(arg1, arg2, notArg) expect(-> spy.should.always.have.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.should.have.always.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.should.have.been.always.calledWith(arg1, arg2)).to.not.throw() it "should throw an assertion error when the spy is called with incorrect arguments", -> spy(notArg, arg1) expect(-> spy.should.always.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWith(arg1, arg2)).to.throw(AssertionError) it "should throw an assertion error when the spy is called with incorrect arguments but then correct ones", -> spy(notArg, arg1) spy(arg1, arg2) expect(-> spy.should.always.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWith(arg1, arg2)).to.throw(AssertionError) describe "calledWithExactly", -> it "should throw an assertion error when the spy is not called", -> expect(-> spy.should.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with the correct arguments", -> spy(arg1, arg2) expect(-> spy.should.have.been.calledWithExactly(arg1, arg2)).to.not.throw() expect(-> spy.getCall(0).should.have.been.calledWithExactly(arg1, arg2)).to.not.throw() it "should throw an assertion error when the spy is called with the correct arguments and more", -> spy(arg1, arg2, notArg) expect(-> spy.should.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.getCall(0).should.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should throw an assertion error when the spy is called with incorrect arguments", -> spy(notArg, arg1) expect(-> spy.should.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.getCall(0).should.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with incorrect arguments but then correct ones", -> spy(notArg, arg1) spy(arg1, arg2) expect(-> spy.should.have.been.calledWithExactly(arg1, arg2)).to.not.throw() expect(-> spy.getCall(1).should.have.been.calledWithExactly(arg1, arg2)).to.not.throw() describe "always calledWithExactly", -> it "should throw an assertion error when the spy is not called", -> expect(-> spy.should.always.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with the correct arguments", -> spy(arg1, arg2) expect(-> spy.should.always.have.been.calledWithExactly(arg1, arg2)).to.not.throw() expect(-> spy.should.have.always.been.calledWithExactly(arg1, arg2)).to.not.throw() expect(-> spy.should.have.been.always.calledWithExactly(arg1, arg2)).to.not.throw() it "should throw an assertion error when the spy is called with the correct arguments and more", -> spy(arg1, arg2, notArg) expect(-> spy.should.always.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should throw an assertion error when the spy is called with incorrect arguments", -> spy(notArg, arg1) expect(-> spy.should.always.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should throw an assertion error when the spy is called with incorrect arguments but then correct ones", -> spy(notArg, arg1) spy(arg1, arg2) expect(-> spy.should.always.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWithExactly(arg1, arg2)).to.throw(AssertionError)
212643
describe "Call arguments", -> spy = null arg1 = null arg2 = null notArg = null beforeEach -> spy = sinon.spy() arg1 = "A" arg2 = "<NAME>" notArg = "C" describe "calledWith", -> it "should throw an assertion error when the spy is not called", -> expect(-> spy.should.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with the correct arguments", -> spy(arg1, arg2) expect(-> spy.should.have.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.getCall(0).should.have.been.calledWith(arg1, arg2)).to.not.throw() it "should not throw when the spy is called with the correct arguments and more", -> spy(arg1, arg2, notArg) expect(-> spy.should.have.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.getCall(0).should.have.been.calledWith(arg1, arg2)).to.not.throw() it "should throw an assertion error when the spy is called with incorrect arguments", -> spy(notArg, arg1) expect(-> spy.should.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.getCall(0).should.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with incorrect arguments but then correct ones", -> spy(notArg, arg1) spy(arg1, arg2) expect(-> spy.should.have.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.getCall(1).should.have.been.calledWith(arg1, arg2)).to.not.throw() describe "always calledWith", -> it "should throw an assertion error when the spy is not called", -> expect(-> spy.should.always.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWith(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with the correct arguments", -> spy(arg1, arg2) expect(-> spy.should.always.have.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.should.have.always.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.should.have.been.always.calledWith(arg1, arg2)).to.not.throw() it "should not throw when the spy is called with the correct arguments and more", -> spy(arg1, arg2, notArg) expect(-> spy.should.always.have.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.should.have.always.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.should.have.been.always.calledWith(arg1, arg2)).to.not.throw() it "should throw an assertion error when the spy is called with incorrect arguments", -> spy(notArg, arg1) expect(-> spy.should.always.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWith(arg1, arg2)).to.throw(AssertionError) it "should throw an assertion error when the spy is called with incorrect arguments but then correct ones", -> spy(notArg, arg1) spy(arg1, arg2) expect(-> spy.should.always.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWith(arg1, arg2)).to.throw(AssertionError) describe "calledWithExactly", -> it "should throw an assertion error when the spy is not called", -> expect(-> spy.should.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with the correct arguments", -> spy(arg1, arg2) expect(-> spy.should.have.been.calledWithExactly(arg1, arg2)).to.not.throw() expect(-> spy.getCall(0).should.have.been.calledWithExactly(arg1, arg2)).to.not.throw() it "should throw an assertion error when the spy is called with the correct arguments and more", -> spy(arg1, arg2, notArg) expect(-> spy.should.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.getCall(0).should.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should throw an assertion error when the spy is called with incorrect arguments", -> spy(notArg, arg1) expect(-> spy.should.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.getCall(0).should.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with incorrect arguments but then correct ones", -> spy(notArg, arg1) spy(arg1, arg2) expect(-> spy.should.have.been.calledWithExactly(arg1, arg2)).to.not.throw() expect(-> spy.getCall(1).should.have.been.calledWithExactly(arg1, arg2)).to.not.throw() describe "always calledWithExactly", -> it "should throw an assertion error when the spy is not called", -> expect(-> spy.should.always.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with the correct arguments", -> spy(arg1, arg2) expect(-> spy.should.always.have.been.calledWithExactly(arg1, arg2)).to.not.throw() expect(-> spy.should.have.always.been.calledWithExactly(arg1, arg2)).to.not.throw() expect(-> spy.should.have.been.always.calledWithExactly(arg1, arg2)).to.not.throw() it "should throw an assertion error when the spy is called with the correct arguments and more", -> spy(arg1, arg2, notArg) expect(-> spy.should.always.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should throw an assertion error when the spy is called with incorrect arguments", -> spy(notArg, arg1) expect(-> spy.should.always.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should throw an assertion error when the spy is called with incorrect arguments but then correct ones", -> spy(notArg, arg1) spy(arg1, arg2) expect(-> spy.should.always.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWithExactly(arg1, arg2)).to.throw(AssertionError)
true
describe "Call arguments", -> spy = null arg1 = null arg2 = null notArg = null beforeEach -> spy = sinon.spy() arg1 = "A" arg2 = "PI:NAME:<NAME>END_PI" notArg = "C" describe "calledWith", -> it "should throw an assertion error when the spy is not called", -> expect(-> spy.should.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with the correct arguments", -> spy(arg1, arg2) expect(-> spy.should.have.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.getCall(0).should.have.been.calledWith(arg1, arg2)).to.not.throw() it "should not throw when the spy is called with the correct arguments and more", -> spy(arg1, arg2, notArg) expect(-> spy.should.have.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.getCall(0).should.have.been.calledWith(arg1, arg2)).to.not.throw() it "should throw an assertion error when the spy is called with incorrect arguments", -> spy(notArg, arg1) expect(-> spy.should.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.getCall(0).should.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with incorrect arguments but then correct ones", -> spy(notArg, arg1) spy(arg1, arg2) expect(-> spy.should.have.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.getCall(1).should.have.been.calledWith(arg1, arg2)).to.not.throw() describe "always calledWith", -> it "should throw an assertion error when the spy is not called", -> expect(-> spy.should.always.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWith(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with the correct arguments", -> spy(arg1, arg2) expect(-> spy.should.always.have.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.should.have.always.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.should.have.been.always.calledWith(arg1, arg2)).to.not.throw() it "should not throw when the spy is called with the correct arguments and more", -> spy(arg1, arg2, notArg) expect(-> spy.should.always.have.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.should.have.always.been.calledWith(arg1, arg2)).to.not.throw() expect(-> spy.should.have.been.always.calledWith(arg1, arg2)).to.not.throw() it "should throw an assertion error when the spy is called with incorrect arguments", -> spy(notArg, arg1) expect(-> spy.should.always.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWith(arg1, arg2)).to.throw(AssertionError) it "should throw an assertion error when the spy is called with incorrect arguments but then correct ones", -> spy(notArg, arg1) spy(arg1, arg2) expect(-> spy.should.always.have.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWith(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWith(arg1, arg2)).to.throw(AssertionError) describe "calledWithExactly", -> it "should throw an assertion error when the spy is not called", -> expect(-> spy.should.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with the correct arguments", -> spy(arg1, arg2) expect(-> spy.should.have.been.calledWithExactly(arg1, arg2)).to.not.throw() expect(-> spy.getCall(0).should.have.been.calledWithExactly(arg1, arg2)).to.not.throw() it "should throw an assertion error when the spy is called with the correct arguments and more", -> spy(arg1, arg2, notArg) expect(-> spy.should.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.getCall(0).should.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should throw an assertion error when the spy is called with incorrect arguments", -> spy(notArg, arg1) expect(-> spy.should.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.getCall(0).should.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with incorrect arguments but then correct ones", -> spy(notArg, arg1) spy(arg1, arg2) expect(-> spy.should.have.been.calledWithExactly(arg1, arg2)).to.not.throw() expect(-> spy.getCall(1).should.have.been.calledWithExactly(arg1, arg2)).to.not.throw() describe "always calledWithExactly", -> it "should throw an assertion error when the spy is not called", -> expect(-> spy.should.always.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should not throw when the spy is called with the correct arguments", -> spy(arg1, arg2) expect(-> spy.should.always.have.been.calledWithExactly(arg1, arg2)).to.not.throw() expect(-> spy.should.have.always.been.calledWithExactly(arg1, arg2)).to.not.throw() expect(-> spy.should.have.been.always.calledWithExactly(arg1, arg2)).to.not.throw() it "should throw an assertion error when the spy is called with the correct arguments and more", -> spy(arg1, arg2, notArg) expect(-> spy.should.always.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should throw an assertion error when the spy is called with incorrect arguments", -> spy(notArg, arg1) expect(-> spy.should.always.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWithExactly(arg1, arg2)).to.throw(AssertionError) it "should throw an assertion error when the spy is called with incorrect arguments but then correct ones", -> spy(notArg, arg1) spy(arg1, arg2) expect(-> spy.should.always.have.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.always.been.calledWithExactly(arg1, arg2)).to.throw(AssertionError) expect(-> spy.should.have.been.always.calledWithExactly(arg1, arg2)).to.throw(AssertionError)
[ { "context": "Tests for newline-per-chained-call rule.\n# @author Rajendra Patil\n###\n\n'use strict'\n\n#-----------------------------", "end": 86, "score": 0.9998533129692078, "start": 72, "tag": "NAME", "value": "Rajendra Patil" } ]
src/tests/rules/newline-per-chained-call.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for newline-per-chained-call rule. # @author Rajendra Patil ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/newline-per-chained-call' {RuleTester} = require 'eslint' path = require 'path' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'newline-per-chained-call', rule, valid: [ ''' _ .chain {} .map foo .filter bar .value() ''' 'a.b.c.d.e.f' ''' a() .b() .c .e ''' ''' a = m1.m2() b = m1.m2() c = m1.m2() ''' ''' a = m1() .m2() ''' 'a = m1()' ''' a() .b().c.e.d() ''' 'a().b().c.e.d()' 'a.b.c.e.d()' ''' a = window .location .href .match(/(^[^#]*)/)[0] ''' ''' a = window['location'] .href .match(/(^[^#]*)/)[0] ''' "a = window['location'].href.match(/(^[^#]*)/)[0]" , code: 'a = m1().m2.m3()' options: [ignoreChainWithDepth: 3] , code: 'a = m1().m2.m3().m4.m5().m6.m7().m8' options: [ignoreChainWithDepth: 8] , code: ''' http.request a: 1 # Param .on 'response', (response) -> # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. .on 'error', (error) -> # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. .end() ''' , code: ''' anObject.method1().method2()['method' + n]()[if aCondition method3 else method4]() ''' , code: 'foo.bar()[(biz)]()' , code: "foo.bar()['foo' + \u2029 + 'bar']()" ] invalid: [ code: ''' _ .chain({}).map(foo).filter(bar).value() ''' # output: '_\n.chain({}).map(foo)\n.filter(bar)\n.value()' errors: [ message: 'Expected line break before `.filter`.' , message: 'Expected line break before `.value`.' ] , code: ''' _ .chain {} .map foo .filter(bar).value() ''' # output: '_\n.chain({})\n.map(foo)\n.filter(bar)\n.value()' errors: [message: 'Expected line break before `.value`.'] , code: 'a().b().c().e.d()' # output: 'a().b()\n.c().e.d()' errors: [message: 'Expected line break before `.c`.'] , code: 'a.b.c().e().d()' # output: 'a.b.c().e()\n.d()' errors: [message: 'Expected line break before `.d`.'] , code: '_.chain({}).map(a).value() ' # output: '_.chain({}).map(a)\n.value() ' errors: [message: 'Expected line break before `.value`.'] , code: ''' a = m1.m2() b = m1.m2().m3().m4().m5() ''' # output: 'a = m1.m2()\n b = m1.m2().m3()\n.m4()\n.m5()' errors: [ message: 'Expected line break before `.m4`.' , message: 'Expected line break before `.m5`.' ] , code: ''' a = m1.m2() b = m1.m2().m3() .m4().m5() ''' # output: 'a = m1.m2()\n b = m1.m2().m3()\n.m4()\n.m5()' errors: [message: 'Expected line break before `.m5`.'] , code: ''' a = m1().m2 .m3().m4().m5().m6().m7() ''' # output: 'a = m1().m2\n.m3().m4().m5()\n.m6()\n.m7()' options: [ignoreChainWithDepth: 3] errors: [ message: 'Expected line break before `.m6`.' , message: 'Expected line break before `.m7`.' ] , code: ''' http.request({ a: 1 # Param # Param # Param }).on('response', (response) -> # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. ).on('error', (error) -> # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. ).end() ''' # output: [ # 'http.request({' # ' # Param' # ' # Param' # ' # Param' # "}).on('response', function(response) {" # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # '})' # ".on('error', function(error) {" # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # '})' # '.end()' # ].join '\n' errors: [ message: 'Expected line break before `.on`.' , message: 'Expected line break before `.end`.' ] , code: '(foo).bar().biz()' # output: '(foo).bar()\n.biz()' options: [ignoreChainWithDepth: 1] errors: [message: 'Expected line break before `.biz`.'] , code: 'foo.bar(). ### comment ### biz()' # output: 'foo.bar()\n. ### comment ### biz()' options: [ignoreChainWithDepth: 1] errors: [message: 'Expected line break before `.biz`.'] , code: 'foo.bar() ### comment ### .biz()' # output: 'foo.bar() ### comment ### \n.biz()' options: [ignoreChainWithDepth: 1] errors: [message: 'Expected line break before `.biz`.'] ]
118000
###* # @fileoverview Tests for newline-per-chained-call rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/newline-per-chained-call' {RuleTester} = require 'eslint' path = require 'path' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'newline-per-chained-call', rule, valid: [ ''' _ .chain {} .map foo .filter bar .value() ''' 'a.b.c.d.e.f' ''' a() .b() .c .e ''' ''' a = m1.m2() b = m1.m2() c = m1.m2() ''' ''' a = m1() .m2() ''' 'a = m1()' ''' a() .b().c.e.d() ''' 'a().b().c.e.d()' 'a.b.c.e.d()' ''' a = window .location .href .match(/(^[^#]*)/)[0] ''' ''' a = window['location'] .href .match(/(^[^#]*)/)[0] ''' "a = window['location'].href.match(/(^[^#]*)/)[0]" , code: 'a = m1().m2.m3()' options: [ignoreChainWithDepth: 3] , code: 'a = m1().m2.m3().m4.m5().m6.m7().m8' options: [ignoreChainWithDepth: 8] , code: ''' http.request a: 1 # Param .on 'response', (response) -> # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. .on 'error', (error) -> # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. .end() ''' , code: ''' anObject.method1().method2()['method' + n]()[if aCondition method3 else method4]() ''' , code: 'foo.bar()[(biz)]()' , code: "foo.bar()['foo' + \u2029 + 'bar']()" ] invalid: [ code: ''' _ .chain({}).map(foo).filter(bar).value() ''' # output: '_\n.chain({}).map(foo)\n.filter(bar)\n.value()' errors: [ message: 'Expected line break before `.filter`.' , message: 'Expected line break before `.value`.' ] , code: ''' _ .chain {} .map foo .filter(bar).value() ''' # output: '_\n.chain({})\n.map(foo)\n.filter(bar)\n.value()' errors: [message: 'Expected line break before `.value`.'] , code: 'a().b().c().e.d()' # output: 'a().b()\n.c().e.d()' errors: [message: 'Expected line break before `.c`.'] , code: 'a.b.c().e().d()' # output: 'a.b.c().e()\n.d()' errors: [message: 'Expected line break before `.d`.'] , code: '_.chain({}).map(a).value() ' # output: '_.chain({}).map(a)\n.value() ' errors: [message: 'Expected line break before `.value`.'] , code: ''' a = m1.m2() b = m1.m2().m3().m4().m5() ''' # output: 'a = m1.m2()\n b = m1.m2().m3()\n.m4()\n.m5()' errors: [ message: 'Expected line break before `.m4`.' , message: 'Expected line break before `.m5`.' ] , code: ''' a = m1.m2() b = m1.m2().m3() .m4().m5() ''' # output: 'a = m1.m2()\n b = m1.m2().m3()\n.m4()\n.m5()' errors: [message: 'Expected line break before `.m5`.'] , code: ''' a = m1().m2 .m3().m4().m5().m6().m7() ''' # output: 'a = m1().m2\n.m3().m4().m5()\n.m6()\n.m7()' options: [ignoreChainWithDepth: 3] errors: [ message: 'Expected line break before `.m6`.' , message: 'Expected line break before `.m7`.' ] , code: ''' http.request({ a: 1 # Param # Param # Param }).on('response', (response) -> # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. ).on('error', (error) -> # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. ).end() ''' # output: [ # 'http.request({' # ' # Param' # ' # Param' # ' # Param' # "}).on('response', function(response) {" # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # '})' # ".on('error', function(error) {" # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # '})' # '.end()' # ].join '\n' errors: [ message: 'Expected line break before `.on`.' , message: 'Expected line break before `.end`.' ] , code: '(foo).bar().biz()' # output: '(foo).bar()\n.biz()' options: [ignoreChainWithDepth: 1] errors: [message: 'Expected line break before `.biz`.'] , code: 'foo.bar(). ### comment ### biz()' # output: 'foo.bar()\n. ### comment ### biz()' options: [ignoreChainWithDepth: 1] errors: [message: 'Expected line break before `.biz`.'] , code: 'foo.bar() ### comment ### .biz()' # output: 'foo.bar() ### comment ### \n.biz()' options: [ignoreChainWithDepth: 1] errors: [message: 'Expected line break before `.biz`.'] ]
true
###* # @fileoverview Tests for newline-per-chained-call rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/newline-per-chained-call' {RuleTester} = require 'eslint' path = require 'path' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'newline-per-chained-call', rule, valid: [ ''' _ .chain {} .map foo .filter bar .value() ''' 'a.b.c.d.e.f' ''' a() .b() .c .e ''' ''' a = m1.m2() b = m1.m2() c = m1.m2() ''' ''' a = m1() .m2() ''' 'a = m1()' ''' a() .b().c.e.d() ''' 'a().b().c.e.d()' 'a.b.c.e.d()' ''' a = window .location .href .match(/(^[^#]*)/)[0] ''' ''' a = window['location'] .href .match(/(^[^#]*)/)[0] ''' "a = window['location'].href.match(/(^[^#]*)/)[0]" , code: 'a = m1().m2.m3()' options: [ignoreChainWithDepth: 3] , code: 'a = m1().m2.m3().m4.m5().m6.m7().m8' options: [ignoreChainWithDepth: 8] , code: ''' http.request a: 1 # Param .on 'response', (response) -> # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. .on 'error', (error) -> # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. .end() ''' , code: ''' anObject.method1().method2()['method' + n]()[if aCondition method3 else method4]() ''' , code: 'foo.bar()[(biz)]()' , code: "foo.bar()['foo' + \u2029 + 'bar']()" ] invalid: [ code: ''' _ .chain({}).map(foo).filter(bar).value() ''' # output: '_\n.chain({}).map(foo)\n.filter(bar)\n.value()' errors: [ message: 'Expected line break before `.filter`.' , message: 'Expected line break before `.value`.' ] , code: ''' _ .chain {} .map foo .filter(bar).value() ''' # output: '_\n.chain({})\n.map(foo)\n.filter(bar)\n.value()' errors: [message: 'Expected line break before `.value`.'] , code: 'a().b().c().e.d()' # output: 'a().b()\n.c().e.d()' errors: [message: 'Expected line break before `.c`.'] , code: 'a.b.c().e().d()' # output: 'a.b.c().e()\n.d()' errors: [message: 'Expected line break before `.d`.'] , code: '_.chain({}).map(a).value() ' # output: '_.chain({}).map(a)\n.value() ' errors: [message: 'Expected line break before `.value`.'] , code: ''' a = m1.m2() b = m1.m2().m3().m4().m5() ''' # output: 'a = m1.m2()\n b = m1.m2().m3()\n.m4()\n.m5()' errors: [ message: 'Expected line break before `.m4`.' , message: 'Expected line break before `.m5`.' ] , code: ''' a = m1.m2() b = m1.m2().m3() .m4().m5() ''' # output: 'a = m1.m2()\n b = m1.m2().m3()\n.m4()\n.m5()' errors: [message: 'Expected line break before `.m5`.'] , code: ''' a = m1().m2 .m3().m4().m5().m6().m7() ''' # output: 'a = m1().m2\n.m3().m4().m5()\n.m6()\n.m7()' options: [ignoreChainWithDepth: 3] errors: [ message: 'Expected line break before `.m6`.' , message: 'Expected line break before `.m7`.' ] , code: ''' http.request({ a: 1 # Param # Param # Param }).on('response', (response) -> # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. # Do something with response. ).on('error', (error) -> # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. # Do something with error. ).end() ''' # output: [ # 'http.request({' # ' # Param' # ' # Param' # ' # Param' # "}).on('response', function(response) {" # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # ' # Do something with response.' # '})' # ".on('error', function(error) {" # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # ' # Do something with error.' # '})' # '.end()' # ].join '\n' errors: [ message: 'Expected line break before `.on`.' , message: 'Expected line break before `.end`.' ] , code: '(foo).bar().biz()' # output: '(foo).bar()\n.biz()' options: [ignoreChainWithDepth: 1] errors: [message: 'Expected line break before `.biz`.'] , code: 'foo.bar(). ### comment ### biz()' # output: 'foo.bar()\n. ### comment ### biz()' options: [ignoreChainWithDepth: 1] errors: [message: 'Expected line break before `.biz`.'] , code: 'foo.bar() ### comment ### .biz()' # output: 'foo.bar() ### comment ### \n.biz()' options: [ignoreChainWithDepth: 1] errors: [message: 'Expected line break before `.biz`.'] ]