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": "I.Options module tests\n#\n# Copyright (C) 2012-2013 Nikolay Nemshilov\n#\n{Test,should} = require('lovely')\n\ndescribe 'UI",
"end": 77,
"score": 0.9998880624771118,
"start": 60,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | ui/core/test/options_test.coffee | lovely-io/lovely.io-stl | 2 | #
# The UI.Options module tests
#
# Copyright (C) 2012-2013 Nikolay Nemshilov
#
{Test,should} = require('lovely')
describe 'UI.Options', ->
UI = Element = element = window = document = $ = Widget = widget = null
before Test.load (build, win)->
UI = build
window = win
document = win.document
$ = win.Lovely.module('dom')
Element = $.Element
Widget = Element.inherit
include: UI.Options
extend:
Options:
stuff: 'something'
other: 'stuff'
somth: 'something'
nested:
value1: 'value1'
value2: 'value2'
constructor: (element, options)->
options = @setOptions(options, 'widget', element)
@$super element, options
element = document.createElement('div')
element.setAttribute('data-widget-stuff', 'new stuff')
widget = new Widget(element, id: 'some-id', other: 'changed', nested: value1: 'new value')
it "should set the 'options' property", ->
widget.options.should.be.a 'object'
it "should bypass the Element#constructor options", ->
widget._.id.should.equal 'some-id'
it "should not bypass Element#constructor options into the @options", ->
(widget.options.id is undefined).should.be.true
it "should assign the unchanged global options", ->
widget.options.somth.should.equal 'something'
it "should overwrite options from the hash specified in the constructor", ->
widget.options.other.should.equal 'changed'
it "should read the 'data-widget' attributes from the element", ->
widget.options.stuff.should.equal 'new stuff'
it "should merge nested properties correctly", ->
widget.options.nested.value1.should.equal 'new value'
widget.options.nested.value2.should.equal 'value2'
| 152286 | #
# The UI.Options module tests
#
# Copyright (C) 2012-2013 <NAME>
#
{Test,should} = require('lovely')
describe 'UI.Options', ->
UI = Element = element = window = document = $ = Widget = widget = null
before Test.load (build, win)->
UI = build
window = win
document = win.document
$ = win.Lovely.module('dom')
Element = $.Element
Widget = Element.inherit
include: UI.Options
extend:
Options:
stuff: 'something'
other: 'stuff'
somth: 'something'
nested:
value1: 'value1'
value2: 'value2'
constructor: (element, options)->
options = @setOptions(options, 'widget', element)
@$super element, options
element = document.createElement('div')
element.setAttribute('data-widget-stuff', 'new stuff')
widget = new Widget(element, id: 'some-id', other: 'changed', nested: value1: 'new value')
it "should set the 'options' property", ->
widget.options.should.be.a 'object'
it "should bypass the Element#constructor options", ->
widget._.id.should.equal 'some-id'
it "should not bypass Element#constructor options into the @options", ->
(widget.options.id is undefined).should.be.true
it "should assign the unchanged global options", ->
widget.options.somth.should.equal 'something'
it "should overwrite options from the hash specified in the constructor", ->
widget.options.other.should.equal 'changed'
it "should read the 'data-widget' attributes from the element", ->
widget.options.stuff.should.equal 'new stuff'
it "should merge nested properties correctly", ->
widget.options.nested.value1.should.equal 'new value'
widget.options.nested.value2.should.equal 'value2'
| true | #
# The UI.Options module tests
#
# Copyright (C) 2012-2013 PI:NAME:<NAME>END_PI
#
{Test,should} = require('lovely')
describe 'UI.Options', ->
UI = Element = element = window = document = $ = Widget = widget = null
before Test.load (build, win)->
UI = build
window = win
document = win.document
$ = win.Lovely.module('dom')
Element = $.Element
Widget = Element.inherit
include: UI.Options
extend:
Options:
stuff: 'something'
other: 'stuff'
somth: 'something'
nested:
value1: 'value1'
value2: 'value2'
constructor: (element, options)->
options = @setOptions(options, 'widget', element)
@$super element, options
element = document.createElement('div')
element.setAttribute('data-widget-stuff', 'new stuff')
widget = new Widget(element, id: 'some-id', other: 'changed', nested: value1: 'new value')
it "should set the 'options' property", ->
widget.options.should.be.a 'object'
it "should bypass the Element#constructor options", ->
widget._.id.should.equal 'some-id'
it "should not bypass Element#constructor options into the @options", ->
(widget.options.id is undefined).should.be.true
it "should assign the unchanged global options", ->
widget.options.somth.should.equal 'something'
it "should overwrite options from the hash specified in the constructor", ->
widget.options.other.should.equal 'changed'
it "should read the 'data-widget' attributes from the element", ->
widget.options.stuff.should.equal 'new stuff'
it "should merge nested properties correctly", ->
widget.options.nested.value1.should.equal 'new value'
widget.options.nested.value2.should.equal 'value2'
|
[
{
"context": "sdk/simple-storage\")\n{encypt_password} = require('lixian').utils\n{prefs} = require(\"sdk/simple-prefs\")\n_ =",
"end": 266,
"score": 0.6847755908966064,
"start": 260,
"tag": "USERNAME",
"value": "lixian"
},
{
"context": ", verification_code}) ->\n\tif password\n\t\tpassword = encypt_password password\n\tif save\n\t\tstorage.username = username\n\t\tstorage.",
"end": 989,
"score": 0.9947212338447571,
"start": 965,
"tag": "PASSWORD",
"value": "encypt_password password"
},
{
"context": "pt_password password\n\tif save\n\t\tstorage.username = username\n\t\tstorage.password = password\n\tstorage.save = sav",
"end": 1028,
"score": 0.7040157914161682,
"start": 1020,
"tag": "USERNAME",
"value": "username"
},
{
"context": "\t\tstorage.username = username\n\t\tstorage.password = password\n\tstorage.save = save\n\tcallback = login_panel.call",
"end": 1058,
"score": 0.996407687664032,
"start": 1050,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "el.hide()\n\tcallback? username: username, password: password, verification_code: verification_code\n\nrequire_lo",
"end": 1216,
"score": 0.8949165344238281,
"start": 1208,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "e\n\tif not password\n\t\tif storage.save\n\t\t\tpassword = storage.password\n\tsave = storage.save\n\tusername = username or clie",
"end": 1458,
"score": 0.9755429625511169,
"start": 1442,
"tag": "PASSWORD",
"value": "storage.password"
},
{
"context": "e = username or client.get_cookie('.xunlei.com', 'usernewno') or client.last_username\n\tlogin_panel.callback =",
"end": 1547,
"score": 0.9357566237449646,
"start": 1538,
"tag": "USERNAME",
"value": "usernewno"
},
{
"context": "callback\n\tlogin_panel.port.emit 'login', username: username, password: password, save: save, verification_cod",
"end": 1657,
"score": 0.9995874762535095,
"start": 1649,
"tag": "USERNAME",
"value": "username"
},
{
"context": "l.port.emit 'login', username: username, password: password, save: save, verification_code: verification_code",
"end": 1677,
"score": 0.998770534992218,
"start": 1669,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "bel')\n\t\tcommand: -> tabs.open(\"https://github.com/iambus/xunlei-lixian-web\")\n\t]\n\tmenu_download_tool_firefo",
"end": 5595,
"score": 0.9992652535438538,
"start": 5589,
"tag": "USERNAME",
"value": "iambus"
},
{
"context": "ent = require('client').create()\nclient.username = storage.username\nclient.password = storage.password\nclient.require",
"end": 6673,
"score": 0.7835383415222168,
"start": 6657,
"tag": "USERNAME",
"value": "storage.username"
},
{
"context": "ient.username = storage.username\nclient.password = storage.password\nclient.require_login = require_login\nclient.requi",
"end": 6708,
"score": 0.9993007779121399,
"start": 6692,
"tag": "PASSWORD",
"value": "storage.password"
}
] | firefox/lib/main.coffee | yineric/xunlei-lixian-web | 0 |
{Widget} = require("sdk/widget")
{Panel} = require("sdk/panel")
tabs = require("sdk/tabs")
self = require("sdk/self")
context_menu = require("sdk/context-menu")
notify = require("notify")
{storage} = require("sdk/simple-storage")
{encypt_password} = require('lixian').utils
{prefs} = require("sdk/simple-prefs")
_ = require('sdk/l10n').get
widget_menu = require 'widget_menu'
login_panel = Panel
width: 200
height: 180
contentURL: self.data.url('content/login.html')
contentScriptFile: self.data.url('content/login.js')
verification_code_panel = Panel
width: 200
height: 140
contentURL: self.data.url('content/verification_code.html')
contentScriptFile: self.data.url('content/verification_code.js')
task_panel = Panel
width: 200
height: 220
contentURL: self.data.url('content/task.html')
contentScriptFile: self.data.url('content/task.js')
login_panel.port.on 'login', ({username, password, save, verification_code}) ->
if password
password = encypt_password password
if save
storage.username = username
storage.password = password
storage.save = save
callback = login_panel.callback
login_panel.callback = undefined
login_panel.hide()
callback? username: username, password: password, verification_code: verification_code
require_login = ({username, password, verification_code}, callback) ->
if not username
if storage.save
username = storage.username
if not password
if storage.save
password = storage.password
save = storage.save
username = username or client.get_cookie('.xunlei.com', 'usernewno') or client.last_username
login_panel.callback = callback
login_panel.port.emit 'login', username: username, password: password, save: save, verification_code: verification_code
login_panel.show()
verification_code_panel.port.on 'verify', (verification_code) ->
callback = verification_code_panel.callback
verification_code_panel.callback = undefined
verification_code_panel.hide()
callback? verification_code
require_verification_code = (callback) ->
verification_code_panel.callback = callback
verification_code_panel.port.emit 'verify'
verification_code_panel.show()
widget_id = 'iambus-xunlei-lixian-web-firefox'
widget = Widget
id: widget_id
label: _('widget_label')
contentURL: self.data.url('lixian.ico')
contentScriptWhen: 'ready',
contentScriptFile: self.data.url('content/widget.js')
panel: task_panel
onClick: (view) ->
# tabs.open("http://lixian.vip.xunlei.com/task.html")
task_panel.port.emit 'show'
task_panel.port.on 'refresh', (page_index) ->
client.list_tasks_by 4, page_index, 10, (result) ->
if result.ok
task_panel.port.emit 'tasks', result
else
notify type: 'error', message: _('list_error', if result.detail?.length < 80 then result.detail else result.reason ? '')
console.log result.response
task_panel.port.on 'resize', ({width, height}) ->
if not width?
width = task_panel.width
if not height?
height = task_panel.height
task_panel.resize width, height
task_panel.port.on 'download', (task) ->
if task.type != 'bt'
download_with ok: true, tasks: [task]
else
client.list_bt task, (result) ->
if result.ok
download_with ok: true, tasks: result.files
else
download_with result
task_panel.port.on 'play', (task) ->
url = "http://vod.lixian.xunlei.com/share.html?from=lxweb&url=#{encodeURIComponent task.original_url}&filename=#{encodeURIComponent task.filename}&userid=#{client.get_id_from_cookie()}&gcid=#{task.gcid}&cid=#{task.cid}&isvip=1"
{Cc, Ci} = require("chrome")
io_service = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService)
referer = io_service.newURI('http://dynamic.cloud.vip.xunlei.com/user_task', null, null)
gBrowser = require('sdk/window/utils').getMostRecentBrowserWindow().gBrowser
gBrowser.selectedTab = gBrowser.addTab url, {referrerURI: referer}
task_panel.port.on 'delete', (id) ->
client.delete_task_by_id id, (result) ->
if result.ok
notify type: 'success', message: _('delete_ok')
task_panel.port.emit 'refresh'
else
notify type: 'error', message: _('delete_error', result.reason), detail: result.detail ? result.response
console.log result.response
#widget.port.on 'left-click', ->
# tabs.open("http://lixian.vip.xunlei.com/task.html")
widget.port.on 'right-click', ->
menu = widget_menu widget_id, 'options', [
label: _('widget_menu_download_tool')
items: [
id: 'download_tool_firefox'
label: _('widget_menu_download_tool_firefox')
type: 'radio'
command: ->
prefs.download_tool = 'firefox'
,
id: 'download_tool_dta'
label: _('widget_menu_download_tool_dta')
type: 'radio'
command: ->
prefs.download_tool = 'dta'
,
id: 'download_tool_flashgot'
label: _('widget_menu_download_tool_flashgot')
type: 'radio'
command: ->
prefs.download_tool = 'flashgot'
,
id: 'download_tool_xthunder'
label: _('widget_menu_download_tool_xthunder')
type: 'radio'
command: ->
prefs.download_tool = 'xthunder'
]
,
id: 'associate_types'
label: _('widget_menu_associate_type')
type: 'checkbox'
command: ->
prefs.associate_types = @getAttribute('checked') == 'true'
,
id: 'clear_user_info'
label: _('widget_menu_clear_user_info')
tooltip: _('widget_menu_clear_user_info_label')
command: ->
delete storage.username
delete storage.password
delete storage.save
,
label: _('widget_menu_web_site')
command: -> tabs.open("http://lixian.vip.xunlei.com/task.html")
,
label: _('widget_menu_project_site')
tooltip: _('widget_menu_project_site_label')
command: -> tabs.open("https://github.com/iambus/xunlei-lixian-web")
]
menu_download_tool_firefox = menu.find 'download_tool_firefox'
menu_download_tool_firefox.setAttribute 'checked', prefs.download_tool not in ['dta', 'flashgot', 'xthunder']
menu_download_tool_dta = menu.find 'download_tool_dta'
menu_download_tool_dta.setAttribute 'checked', prefs.download_tool == 'dta'
menu_download_tool_dta.setAttribute 'disabled', not download_tools.dta
menu_download_tool_flashgot = menu.find 'download_tool_flashgot'
menu_download_tool_flashgot.setAttribute 'checked', prefs.download_tool == 'flashgot'
menu_download_tool_flashgot.setAttribute 'disabled', not download_tools.flashgot
menu_download_tool_xthunder = menu.find 'download_tool_xthunder'
menu_download_tool_xthunder.setAttribute 'checked', prefs.download_tool == 'xthunder'
menu_download_tool_xthunder.setAttribute 'disabled', not download_tools.xthunder
menu_associate_types = menu.find 'associate_types'
menu_associate_types.setAttribute 'checked', prefs.associate_types
menu.show()
client = require('client').create()
client.username = storage.username
client.password = storage.password
client.require_login = require_login
client.require_verification_code = require_verification_code
client.auto_relogin = true
download_tools = require('download_tools')
download_with = ({ok, tasks, finished, skipped, reason, detail, response}) ->
download_tool = download_tools.get() # TODO: check download tool before requests
if ok
finished = finished ? (t for t in tasks when t.status_text == 'completed')
skipped = skipped ? (t for t in tasks when t.status_text != 'completed')
if finished.length > 0
notify type: 'success', message: _('download_status_done')
download_tool tasks
if skipped.length > 0
notify type: 'warning', message: _('download_warning_skipped')
else
if tasks.length > 0
notify type: 'warning', message: _('download_error_task_not_ready')
else
notify type: 'error', message: _('download_error_task_not_found'), detail: detail ? response
else
notify type: 'error', message: _('download_error', if detail?.length < 80 then detail else reason ? ''), detail: detail ? response
console.log response
download = (urls) ->
if Object.prototype.toString.call(urls) == '[object String]'
urls = [urls]
if urls?.length > 0
client.super_get urls, download_with
download_bt = (url) ->
client.super_get_bt url, download_with
context_menu.Item
label: _('context_menu_download_link')
image: self.data.url('lixian.ico')
context: context_menu.SelectorContext('a[href]')
contentScriptFile: self.data.url('content/menu/link.js')
onMessage: (url) ->
if url.match /\.torrent$/i
download_bt url
else
download [url]
context_menu.Item
label: _('context_menu_download_selection')
image: self.data.url('lixian.ico')
context: context_menu.SelectionContext()
contentScriptFile: self.data.url('content/menu/text.js')
onMessage: (urls) ->
download urls
API =
download_url: (url) -> download [url]
require('api') API
require('protocol').setup()
#exports.onUnload = ->
| 167397 |
{Widget} = require("sdk/widget")
{Panel} = require("sdk/panel")
tabs = require("sdk/tabs")
self = require("sdk/self")
context_menu = require("sdk/context-menu")
notify = require("notify")
{storage} = require("sdk/simple-storage")
{encypt_password} = require('lixian').utils
{prefs} = require("sdk/simple-prefs")
_ = require('sdk/l10n').get
widget_menu = require 'widget_menu'
login_panel = Panel
width: 200
height: 180
contentURL: self.data.url('content/login.html')
contentScriptFile: self.data.url('content/login.js')
verification_code_panel = Panel
width: 200
height: 140
contentURL: self.data.url('content/verification_code.html')
contentScriptFile: self.data.url('content/verification_code.js')
task_panel = Panel
width: 200
height: 220
contentURL: self.data.url('content/task.html')
contentScriptFile: self.data.url('content/task.js')
login_panel.port.on 'login', ({username, password, save, verification_code}) ->
if password
password = <PASSWORD>
if save
storage.username = username
storage.password = <PASSWORD>
storage.save = save
callback = login_panel.callback
login_panel.callback = undefined
login_panel.hide()
callback? username: username, password: <PASSWORD>, verification_code: verification_code
require_login = ({username, password, verification_code}, callback) ->
if not username
if storage.save
username = storage.username
if not password
if storage.save
password = <PASSWORD>
save = storage.save
username = username or client.get_cookie('.xunlei.com', 'usernewno') or client.last_username
login_panel.callback = callback
login_panel.port.emit 'login', username: username, password: <PASSWORD>, save: save, verification_code: verification_code
login_panel.show()
verification_code_panel.port.on 'verify', (verification_code) ->
callback = verification_code_panel.callback
verification_code_panel.callback = undefined
verification_code_panel.hide()
callback? verification_code
require_verification_code = (callback) ->
verification_code_panel.callback = callback
verification_code_panel.port.emit 'verify'
verification_code_panel.show()
widget_id = 'iambus-xunlei-lixian-web-firefox'
widget = Widget
id: widget_id
label: _('widget_label')
contentURL: self.data.url('lixian.ico')
contentScriptWhen: 'ready',
contentScriptFile: self.data.url('content/widget.js')
panel: task_panel
onClick: (view) ->
# tabs.open("http://lixian.vip.xunlei.com/task.html")
task_panel.port.emit 'show'
task_panel.port.on 'refresh', (page_index) ->
client.list_tasks_by 4, page_index, 10, (result) ->
if result.ok
task_panel.port.emit 'tasks', result
else
notify type: 'error', message: _('list_error', if result.detail?.length < 80 then result.detail else result.reason ? '')
console.log result.response
task_panel.port.on 'resize', ({width, height}) ->
if not width?
width = task_panel.width
if not height?
height = task_panel.height
task_panel.resize width, height
task_panel.port.on 'download', (task) ->
if task.type != 'bt'
download_with ok: true, tasks: [task]
else
client.list_bt task, (result) ->
if result.ok
download_with ok: true, tasks: result.files
else
download_with result
task_panel.port.on 'play', (task) ->
url = "http://vod.lixian.xunlei.com/share.html?from=lxweb&url=#{encodeURIComponent task.original_url}&filename=#{encodeURIComponent task.filename}&userid=#{client.get_id_from_cookie()}&gcid=#{task.gcid}&cid=#{task.cid}&isvip=1"
{Cc, Ci} = require("chrome")
io_service = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService)
referer = io_service.newURI('http://dynamic.cloud.vip.xunlei.com/user_task', null, null)
gBrowser = require('sdk/window/utils').getMostRecentBrowserWindow().gBrowser
gBrowser.selectedTab = gBrowser.addTab url, {referrerURI: referer}
task_panel.port.on 'delete', (id) ->
client.delete_task_by_id id, (result) ->
if result.ok
notify type: 'success', message: _('delete_ok')
task_panel.port.emit 'refresh'
else
notify type: 'error', message: _('delete_error', result.reason), detail: result.detail ? result.response
console.log result.response
#widget.port.on 'left-click', ->
# tabs.open("http://lixian.vip.xunlei.com/task.html")
widget.port.on 'right-click', ->
menu = widget_menu widget_id, 'options', [
label: _('widget_menu_download_tool')
items: [
id: 'download_tool_firefox'
label: _('widget_menu_download_tool_firefox')
type: 'radio'
command: ->
prefs.download_tool = 'firefox'
,
id: 'download_tool_dta'
label: _('widget_menu_download_tool_dta')
type: 'radio'
command: ->
prefs.download_tool = 'dta'
,
id: 'download_tool_flashgot'
label: _('widget_menu_download_tool_flashgot')
type: 'radio'
command: ->
prefs.download_tool = 'flashgot'
,
id: 'download_tool_xthunder'
label: _('widget_menu_download_tool_xthunder')
type: 'radio'
command: ->
prefs.download_tool = 'xthunder'
]
,
id: 'associate_types'
label: _('widget_menu_associate_type')
type: 'checkbox'
command: ->
prefs.associate_types = @getAttribute('checked') == 'true'
,
id: 'clear_user_info'
label: _('widget_menu_clear_user_info')
tooltip: _('widget_menu_clear_user_info_label')
command: ->
delete storage.username
delete storage.password
delete storage.save
,
label: _('widget_menu_web_site')
command: -> tabs.open("http://lixian.vip.xunlei.com/task.html")
,
label: _('widget_menu_project_site')
tooltip: _('widget_menu_project_site_label')
command: -> tabs.open("https://github.com/iambus/xunlei-lixian-web")
]
menu_download_tool_firefox = menu.find 'download_tool_firefox'
menu_download_tool_firefox.setAttribute 'checked', prefs.download_tool not in ['dta', 'flashgot', 'xthunder']
menu_download_tool_dta = menu.find 'download_tool_dta'
menu_download_tool_dta.setAttribute 'checked', prefs.download_tool == 'dta'
menu_download_tool_dta.setAttribute 'disabled', not download_tools.dta
menu_download_tool_flashgot = menu.find 'download_tool_flashgot'
menu_download_tool_flashgot.setAttribute 'checked', prefs.download_tool == 'flashgot'
menu_download_tool_flashgot.setAttribute 'disabled', not download_tools.flashgot
menu_download_tool_xthunder = menu.find 'download_tool_xthunder'
menu_download_tool_xthunder.setAttribute 'checked', prefs.download_tool == 'xthunder'
menu_download_tool_xthunder.setAttribute 'disabled', not download_tools.xthunder
menu_associate_types = menu.find 'associate_types'
menu_associate_types.setAttribute 'checked', prefs.associate_types
menu.show()
client = require('client').create()
client.username = storage.username
client.password = <PASSWORD>
client.require_login = require_login
client.require_verification_code = require_verification_code
client.auto_relogin = true
download_tools = require('download_tools')
download_with = ({ok, tasks, finished, skipped, reason, detail, response}) ->
download_tool = download_tools.get() # TODO: check download tool before requests
if ok
finished = finished ? (t for t in tasks when t.status_text == 'completed')
skipped = skipped ? (t for t in tasks when t.status_text != 'completed')
if finished.length > 0
notify type: 'success', message: _('download_status_done')
download_tool tasks
if skipped.length > 0
notify type: 'warning', message: _('download_warning_skipped')
else
if tasks.length > 0
notify type: 'warning', message: _('download_error_task_not_ready')
else
notify type: 'error', message: _('download_error_task_not_found'), detail: detail ? response
else
notify type: 'error', message: _('download_error', if detail?.length < 80 then detail else reason ? ''), detail: detail ? response
console.log response
download = (urls) ->
if Object.prototype.toString.call(urls) == '[object String]'
urls = [urls]
if urls?.length > 0
client.super_get urls, download_with
download_bt = (url) ->
client.super_get_bt url, download_with
context_menu.Item
label: _('context_menu_download_link')
image: self.data.url('lixian.ico')
context: context_menu.SelectorContext('a[href]')
contentScriptFile: self.data.url('content/menu/link.js')
onMessage: (url) ->
if url.match /\.torrent$/i
download_bt url
else
download [url]
context_menu.Item
label: _('context_menu_download_selection')
image: self.data.url('lixian.ico')
context: context_menu.SelectionContext()
contentScriptFile: self.data.url('content/menu/text.js')
onMessage: (urls) ->
download urls
API =
download_url: (url) -> download [url]
require('api') API
require('protocol').setup()
#exports.onUnload = ->
| true |
{Widget} = require("sdk/widget")
{Panel} = require("sdk/panel")
tabs = require("sdk/tabs")
self = require("sdk/self")
context_menu = require("sdk/context-menu")
notify = require("notify")
{storage} = require("sdk/simple-storage")
{encypt_password} = require('lixian').utils
{prefs} = require("sdk/simple-prefs")
_ = require('sdk/l10n').get
widget_menu = require 'widget_menu'
login_panel = Panel
width: 200
height: 180
contentURL: self.data.url('content/login.html')
contentScriptFile: self.data.url('content/login.js')
verification_code_panel = Panel
width: 200
height: 140
contentURL: self.data.url('content/verification_code.html')
contentScriptFile: self.data.url('content/verification_code.js')
task_panel = Panel
width: 200
height: 220
contentURL: self.data.url('content/task.html')
contentScriptFile: self.data.url('content/task.js')
login_panel.port.on 'login', ({username, password, save, verification_code}) ->
if password
password = PI:PASSWORD:<PASSWORD>END_PI
if save
storage.username = username
storage.password = PI:PASSWORD:<PASSWORD>END_PI
storage.save = save
callback = login_panel.callback
login_panel.callback = undefined
login_panel.hide()
callback? username: username, password: PI:PASSWORD:<PASSWORD>END_PI, verification_code: verification_code
require_login = ({username, password, verification_code}, callback) ->
if not username
if storage.save
username = storage.username
if not password
if storage.save
password = PI:PASSWORD:<PASSWORD>END_PI
save = storage.save
username = username or client.get_cookie('.xunlei.com', 'usernewno') or client.last_username
login_panel.callback = callback
login_panel.port.emit 'login', username: username, password: PI:PASSWORD:<PASSWORD>END_PI, save: save, verification_code: verification_code
login_panel.show()
verification_code_panel.port.on 'verify', (verification_code) ->
callback = verification_code_panel.callback
verification_code_panel.callback = undefined
verification_code_panel.hide()
callback? verification_code
require_verification_code = (callback) ->
verification_code_panel.callback = callback
verification_code_panel.port.emit 'verify'
verification_code_panel.show()
widget_id = 'iambus-xunlei-lixian-web-firefox'
widget = Widget
id: widget_id
label: _('widget_label')
contentURL: self.data.url('lixian.ico')
contentScriptWhen: 'ready',
contentScriptFile: self.data.url('content/widget.js')
panel: task_panel
onClick: (view) ->
# tabs.open("http://lixian.vip.xunlei.com/task.html")
task_panel.port.emit 'show'
task_panel.port.on 'refresh', (page_index) ->
client.list_tasks_by 4, page_index, 10, (result) ->
if result.ok
task_panel.port.emit 'tasks', result
else
notify type: 'error', message: _('list_error', if result.detail?.length < 80 then result.detail else result.reason ? '')
console.log result.response
task_panel.port.on 'resize', ({width, height}) ->
if not width?
width = task_panel.width
if not height?
height = task_panel.height
task_panel.resize width, height
task_panel.port.on 'download', (task) ->
if task.type != 'bt'
download_with ok: true, tasks: [task]
else
client.list_bt task, (result) ->
if result.ok
download_with ok: true, tasks: result.files
else
download_with result
task_panel.port.on 'play', (task) ->
url = "http://vod.lixian.xunlei.com/share.html?from=lxweb&url=#{encodeURIComponent task.original_url}&filename=#{encodeURIComponent task.filename}&userid=#{client.get_id_from_cookie()}&gcid=#{task.gcid}&cid=#{task.cid}&isvip=1"
{Cc, Ci} = require("chrome")
io_service = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService)
referer = io_service.newURI('http://dynamic.cloud.vip.xunlei.com/user_task', null, null)
gBrowser = require('sdk/window/utils').getMostRecentBrowserWindow().gBrowser
gBrowser.selectedTab = gBrowser.addTab url, {referrerURI: referer}
task_panel.port.on 'delete', (id) ->
client.delete_task_by_id id, (result) ->
if result.ok
notify type: 'success', message: _('delete_ok')
task_panel.port.emit 'refresh'
else
notify type: 'error', message: _('delete_error', result.reason), detail: result.detail ? result.response
console.log result.response
#widget.port.on 'left-click', ->
# tabs.open("http://lixian.vip.xunlei.com/task.html")
widget.port.on 'right-click', ->
menu = widget_menu widget_id, 'options', [
label: _('widget_menu_download_tool')
items: [
id: 'download_tool_firefox'
label: _('widget_menu_download_tool_firefox')
type: 'radio'
command: ->
prefs.download_tool = 'firefox'
,
id: 'download_tool_dta'
label: _('widget_menu_download_tool_dta')
type: 'radio'
command: ->
prefs.download_tool = 'dta'
,
id: 'download_tool_flashgot'
label: _('widget_menu_download_tool_flashgot')
type: 'radio'
command: ->
prefs.download_tool = 'flashgot'
,
id: 'download_tool_xthunder'
label: _('widget_menu_download_tool_xthunder')
type: 'radio'
command: ->
prefs.download_tool = 'xthunder'
]
,
id: 'associate_types'
label: _('widget_menu_associate_type')
type: 'checkbox'
command: ->
prefs.associate_types = @getAttribute('checked') == 'true'
,
id: 'clear_user_info'
label: _('widget_menu_clear_user_info')
tooltip: _('widget_menu_clear_user_info_label')
command: ->
delete storage.username
delete storage.password
delete storage.save
,
label: _('widget_menu_web_site')
command: -> tabs.open("http://lixian.vip.xunlei.com/task.html")
,
label: _('widget_menu_project_site')
tooltip: _('widget_menu_project_site_label')
command: -> tabs.open("https://github.com/iambus/xunlei-lixian-web")
]
menu_download_tool_firefox = menu.find 'download_tool_firefox'
menu_download_tool_firefox.setAttribute 'checked', prefs.download_tool not in ['dta', 'flashgot', 'xthunder']
menu_download_tool_dta = menu.find 'download_tool_dta'
menu_download_tool_dta.setAttribute 'checked', prefs.download_tool == 'dta'
menu_download_tool_dta.setAttribute 'disabled', not download_tools.dta
menu_download_tool_flashgot = menu.find 'download_tool_flashgot'
menu_download_tool_flashgot.setAttribute 'checked', prefs.download_tool == 'flashgot'
menu_download_tool_flashgot.setAttribute 'disabled', not download_tools.flashgot
menu_download_tool_xthunder = menu.find 'download_tool_xthunder'
menu_download_tool_xthunder.setAttribute 'checked', prefs.download_tool == 'xthunder'
menu_download_tool_xthunder.setAttribute 'disabled', not download_tools.xthunder
menu_associate_types = menu.find 'associate_types'
menu_associate_types.setAttribute 'checked', prefs.associate_types
menu.show()
client = require('client').create()
client.username = storage.username
client.password = PI:PASSWORD:<PASSWORD>END_PI
client.require_login = require_login
client.require_verification_code = require_verification_code
client.auto_relogin = true
download_tools = require('download_tools')
download_with = ({ok, tasks, finished, skipped, reason, detail, response}) ->
download_tool = download_tools.get() # TODO: check download tool before requests
if ok
finished = finished ? (t for t in tasks when t.status_text == 'completed')
skipped = skipped ? (t for t in tasks when t.status_text != 'completed')
if finished.length > 0
notify type: 'success', message: _('download_status_done')
download_tool tasks
if skipped.length > 0
notify type: 'warning', message: _('download_warning_skipped')
else
if tasks.length > 0
notify type: 'warning', message: _('download_error_task_not_ready')
else
notify type: 'error', message: _('download_error_task_not_found'), detail: detail ? response
else
notify type: 'error', message: _('download_error', if detail?.length < 80 then detail else reason ? ''), detail: detail ? response
console.log response
download = (urls) ->
if Object.prototype.toString.call(urls) == '[object String]'
urls = [urls]
if urls?.length > 0
client.super_get urls, download_with
download_bt = (url) ->
client.super_get_bt url, download_with
context_menu.Item
label: _('context_menu_download_link')
image: self.data.url('lixian.ico')
context: context_menu.SelectorContext('a[href]')
contentScriptFile: self.data.url('content/menu/link.js')
onMessage: (url) ->
if url.match /\.torrent$/i
download_bt url
else
download [url]
context_menu.Item
label: _('context_menu_download_selection')
image: self.data.url('lixian.ico')
context: context_menu.SelectionContext()
contentScriptFile: self.data.url('content/menu/text.js')
onMessage: (urls) ->
download urls
API =
download_url: (url) -> download [url]
require('api') API
require('protocol').setup()
#exports.onUnload = ->
|
[
{
"context": "t with fewer words.\n \"\"\")\n bot.reply(\"my name is Bob\", \"Nice to meet you, bob.\")\n bot.reply(\"bob told",
"end": 888,
"score": 0.997733473777771,
"start": 885,
"tag": "NAME",
"value": "Bob"
},
{
"context": ")\n bot.reply(\"my name is Bob\", \"Nice to meet you, bob.\")\n bot.reply(\"bob told me to say hi\", \"Why did ",
"end": 913,
"score": 0.9958867430686951,
"start": 910,
"tag": "NAME",
"value": "bob"
},
{
"context": "b.\")\n bot.reply(\"bob told me to say hi\", \"Why did bob tell you to say hi?\")\n bot.reply(\"i am 5 years o",
"end": 966,
"score": 0.9694066643714905,
"start": 963,
"tag": "NAME",
"value": "bob"
},
{
"context": " ^ dark blue|light blue\n\n + what color is my (@colors) *\n - Your <star2> is <star1>.\n\n + what col",
"end": 2798,
"score": 0.691007137298584,
"start": 2790,
"tag": "USERNAME",
"value": "(@colors"
},
{
"context": " ! array nothing = nothing||not a thing\n\n + [*] @hello [*]\n - Oh hello there.\n\n + *\n - Anything",
"end": 5395,
"score": 0.7243310213088989,
"start": 5389,
"tag": "USERNAME",
"value": "@hello"
},
{
"context": "come /hi|hey|sup|yo|bye|goodbye|byebye/\n + [*] (@test2|@test4|@test3) [*]\n - Multi-array match\n\n /",
"end": 8835,
"score": 0.948223352432251,
"start": 8828,
"tag": "USERNAME",
"value": "(@test2"
},
{
"context": "hey|sup|yo|bye|goodbye|byebye/\n + [*] (@test2|@test4|@test3) [*]\n - Multi-array match\n\n // Norma",
"end": 8842,
"score": 0.7963017225265503,
"start": 8837,
"tag": "USERNAME",
"value": "test4"
},
{
"context": "array match\n\n // Normal array trigger\n + [*] (@test1) [*]\n - Test1 array match\n\n \"\"\")\n\n # We also",
"end": 8925,
"score": 0.9910638332366943,
"start": 8918,
"tag": "USERNAME",
"value": "(@test1"
}
] | test/test-triggers.coffee | cemali/myChatBots | 1 | TestCase = require("./test-base")
################################################################################
# Trigger Tests
################################################################################
exports.test_atomic_triggers = (test) ->
bot = new TestCase(test, """
+ hello bot
- Hello human.
+ what are you
- I am a RiveScript bot.
""")
bot.reply("Hello bot", "Hello human.")
bot.reply("What are you?", "I am a RiveScript bot.")
test.done()
exports.test_wildcard_triggers = (test) ->
bot = new TestCase(test, """
+ my name is *
- Nice to meet you, <star>.
+ * told me to say *
- Why did <star1> tell you to say <star2>?
+ i am # years old
- A lot of people are <star>.
+ i am _ years old
- Say that with numbers.
+ i am * years old
- Say that with fewer words.
""")
bot.reply("my name is Bob", "Nice to meet you, bob.")
bot.reply("bob told me to say hi", "Why did bob tell you to say hi?")
bot.reply("i am 5 years old", "A lot of people are 5.")
bot.reply("i am five years old", "Say that with numbers.")
bot.reply("i am twenty five years old", "Say that with fewer words.")
test.done()
exports.test_alternatives_and_optionals = (test) ->
bot = new TestCase(test, """
+ what (are|is) you
- I am a robot.
+ what is your (home|office|cell) [phone] number
- It is 555-1234.
+ [please|can you] ask me a question
- Why is the sky blue?
+ (aa|bb|cc) [bogus]
- Matched.
+ (yo|hi) [computer|bot] *
- Matched.
""")
bot.reply("What are you?", "I am a robot.")
bot.reply("What is you?", "I am a robot.")
bot.reply("What is your home phone number?", "It is 555-1234.")
bot.reply("What is your home number?", "It is 555-1234.")
bot.reply("What is your cell phone number?", "It is 555-1234.")
bot.reply("What is your office number?", "It is 555-1234.")
bot.reply("Can you ask me a question?", "Why is the sky blue?")
bot.reply("Please ask me a question?", "Why is the sky blue?")
bot.reply("Ask me a question.", "Why is the sky blue?")
bot.reply("aa", "Matched.")
bot.reply("bb", "Matched.")
bot.reply("aa bogus", "Matched.")
bot.reply("aabogus", "ERR: No Reply Matched")
bot.reply("bogus", "ERR: No Reply Matched")
bot.reply("hi Aiden", "Matched.")
bot.reply("hi bot how are you?", "Matched.")
bot.reply("yo computer what time is it?", "Matched.")
bot.reply("yoghurt is yummy", "ERR: No Reply Matched")
bot.reply("hide and seek is fun", "ERR: No Reply Matched")
bot.reply("hip hip hurrah", "ERR: No Reply Matched")
test.done()
exports.test_trigger_arrays = (test) ->
bot = new TestCase(test, """
! array colors = red blue green yellow white
^ dark blue|light blue
+ what color is my (@colors) *
- Your <star2> is <star1>.
+ what color was * (@colors) *
- It was <star2>.
+ i have a @colors *
- Tell me more about your <star>.
""")
bot.reply("What color is my red shirt?", "Your shirt is red.")
bot.reply("What color is my blue car?", "Your car is blue.")
bot.reply("What color is my pink house?", "ERR: No Reply Matched")
bot.reply("What color is my dark blue jacket?", "Your jacket is dark blue.")
bot.reply("What color was Napoleoan's white horse?", "It was white.")
bot.reply("What color was my red shirt?", "It was red.")
bot.reply("I have a blue car.", "Tell me more about your car.")
bot.reply("I have a cyan car.", "ERR: No Reply Matched")
test.done()
exports.test_weighted_triggers = (test) ->
bot = new TestCase(test, """
+ * or something{weight=10}
- Or something. <@>
+ can you run a google search for *
- Sure!
+ hello *{weight=20}
- Hi there!
// Test that spaces before or after the {weight} tag are gobbled up along
// with the {weight} tag itself.
+ something{weight=100}
- Weighted something
+ something
- Unweighted something
+ nothing {weight=100}
- Weighted nothing
+ nothing
- Unweighted nothing
+ {weight=100}everything
- Weighted everything
+ everything
- Unweighted everything
+ {weight=100} blank
- Weighted blank
+ blank
- Unweighted blank
""")
bot.reply("Hello robot.", "Hi there!")
bot.reply("Hello or something.", "Hi there!")
bot.reply("Can you run a Google search for Node", "Sure!")
bot.reply("Can you run a Google search for Node or something", "Or something. Sure!")
bot.reply("something", "Weighted something")
bot.reply("nothing", "Weighted nothing")
bot.reply("everything", "Weighted everything")
bot.reply("blank", "Weighted blank")
test.done()
exports.test_empty_piped_arrays = (test) ->
errors = []
expected_errors = [
'Syntax error: Piped arrays can\'t begin or end with a | at stream() line 1 near ! array hello = hi|hey|sup|yo| (in topic random)'
'Syntax error: Piped arrays can\'t begin or end with a | at stream() line 2 near ! array something = |something|some thing (in topic random)'
'Syntax error: Piped arrays can\'t include blank entries at stream() line 3 near ! array nothing = nothing||not a thing (in topic random)'
]
console.error = (text)->
errors.push(text)
bot = new TestCase(test, """
! array hello = hi|hey|sup|yo|
! array something = |something|some thing
! array nothing = nothing||not a thing
+ [*] @hello [*]
- Oh hello there.
+ *
- Anything else?
""")
# Check that errors were thrown
test.deepEqual(errors, expected_errors)
# We also fix these, so these should also work
bot.reply("Hey!", "Oh hello there.")
bot.reply("sup", "Oh hello there.")
bot.reply("Bye!", "Anything else?")
bot.reply("Love you", "Anything else?")
test.done()
exports.test_empty_piped_alternations = (test) ->
errors = []
expected_errors = [
'Syntax error: Piped alternations can\'t begin or end with a | at stream() line 1 near + [*] (hi|hey|sup|yo|) [*] (in topic random)'
'Syntax error: Piped alternations can\'t begin or end with a | at stream() line 4 near + [*] (|good|great|nice) [*] (in topic random)'
'Syntax error: Piped alternations can\'t include blank entries at stream() line 7 near + [*] (mild|warm||hot) [*] (in topic random)'
]
console.error = (text)->
errors.push(text)
bot = new TestCase(test, """
+ [*] (hi|hey|sup|yo|) [*]
- Oh hello there.
+ [*] (|good|great|nice) [*]
- Oh nice!
+ [*] (mild|warm||hot) [*]
- Purrfect.
+ *
- Anything else?
""")
# Check that errors were thrown
test.deepEqual(errors, expected_errors)
# We also fix these, so these should also work
bot.reply("Hey!", "Oh hello there.")
bot.reply("sup", "Oh hello there.")
bot.reply("that's nice to hear", "Oh nice!")
bot.reply("so good", "Oh nice!")
bot.reply("You're hot!", "Purrfect.")
bot.reply("Bye!", "Anything else?")
bot.reply("Love you", "Anything else?")
test.done()
exports.test_empty_piped_optionals = (test) ->
errors = []
expected_errors = [
'Syntax error: Piped optionals can\'t begin or end with a | at stream() line 1 near + bot [*] [hi|hey|sup|yo|] [*] to me (in topic random)'
'Syntax error: Piped optionals can\'t begin or end with a | at stream() line 4 near + dog [*] [|good|great|nice] [*] to me (in topic random)'
'Syntax error: Piped optionals can\'t include blank entries at stream() line 7 near + cat [*] [mild|warm||hot] [*] to me (in topic random)'
]
console.error = (text)->
errors.push(text)
bot = new TestCase(test, """
+ bot [*] [hi|hey|sup|yo|] [*] to me
- Oh hello there.
+ dog [*] [|good|great|nice] [*] to me
- Oh nice!
+ cat [*] [mild|warm||hot] [*] to me
- Purrfect.
+ *
- Anything else?
""")
# Check that errors were thrown
test.deepEqual(errors, expected_errors)
# We also fix these, so these should also work
bot.reply("Bot say hey to me", "Oh hello there.")
bot.reply("bot w hi to me", "Oh hello there.")
bot.reply("dog be nice to me", "Oh nice!")
bot.reply("Dog don't be good to me", "Oh nice!")
bot.reply("Cat should not feel warm to me", "Purrfect.")
bot.reply("Bye!", "Anything else?")
bot.reply("Love you", "Anything else?")
test.done()
exports.test_empty_piped_missing_arrays = (test) ->
# Test case where an array reference is missing, and check that
# compiled regexp does not render as accidental wildcard of `||`
bot = new TestCase(test, """
! array test1 = hi|hey|sup|yo
! array test2 = yes|yeah|yep
! array test3 = bye|goodbye||byebye
// This trigger has an array reference that does not exist
// Check that new code prevents accidental double-pipe wildcard match
// e.g. /hi|hey|sup|yo||bye|goodbye|byebye/
// should become /hi|hey|sup|yo|bye|goodbye|byebye/
+ [*] (@test2|@test4|@test3) [*]
- Multi-array match
// Normal array trigger
+ [*] (@test1) [*]
- Test1 array match
""")
# We also fix these, so these should also work
bot.reply("Test One: hi", "Test1 array match")
bot.reply("Test Two: yeah", "Multi-array match")
test.done()
| 49180 | TestCase = require("./test-base")
################################################################################
# Trigger Tests
################################################################################
exports.test_atomic_triggers = (test) ->
bot = new TestCase(test, """
+ hello bot
- Hello human.
+ what are you
- I am a RiveScript bot.
""")
bot.reply("Hello bot", "Hello human.")
bot.reply("What are you?", "I am a RiveScript bot.")
test.done()
exports.test_wildcard_triggers = (test) ->
bot = new TestCase(test, """
+ my name is *
- Nice to meet you, <star>.
+ * told me to say *
- Why did <star1> tell you to say <star2>?
+ i am # years old
- A lot of people are <star>.
+ i am _ years old
- Say that with numbers.
+ i am * years old
- Say that with fewer words.
""")
bot.reply("my name is <NAME>", "Nice to meet you, <NAME>.")
bot.reply("bob told me to say hi", "Why did <NAME> tell you to say hi?")
bot.reply("i am 5 years old", "A lot of people are 5.")
bot.reply("i am five years old", "Say that with numbers.")
bot.reply("i am twenty five years old", "Say that with fewer words.")
test.done()
exports.test_alternatives_and_optionals = (test) ->
bot = new TestCase(test, """
+ what (are|is) you
- I am a robot.
+ what is your (home|office|cell) [phone] number
- It is 555-1234.
+ [please|can you] ask me a question
- Why is the sky blue?
+ (aa|bb|cc) [bogus]
- Matched.
+ (yo|hi) [computer|bot] *
- Matched.
""")
bot.reply("What are you?", "I am a robot.")
bot.reply("What is you?", "I am a robot.")
bot.reply("What is your home phone number?", "It is 555-1234.")
bot.reply("What is your home number?", "It is 555-1234.")
bot.reply("What is your cell phone number?", "It is 555-1234.")
bot.reply("What is your office number?", "It is 555-1234.")
bot.reply("Can you ask me a question?", "Why is the sky blue?")
bot.reply("Please ask me a question?", "Why is the sky blue?")
bot.reply("Ask me a question.", "Why is the sky blue?")
bot.reply("aa", "Matched.")
bot.reply("bb", "Matched.")
bot.reply("aa bogus", "Matched.")
bot.reply("aabogus", "ERR: No Reply Matched")
bot.reply("bogus", "ERR: No Reply Matched")
bot.reply("hi Aiden", "Matched.")
bot.reply("hi bot how are you?", "Matched.")
bot.reply("yo computer what time is it?", "Matched.")
bot.reply("yoghurt is yummy", "ERR: No Reply Matched")
bot.reply("hide and seek is fun", "ERR: No Reply Matched")
bot.reply("hip hip hurrah", "ERR: No Reply Matched")
test.done()
exports.test_trigger_arrays = (test) ->
bot = new TestCase(test, """
! array colors = red blue green yellow white
^ dark blue|light blue
+ what color is my (@colors) *
- Your <star2> is <star1>.
+ what color was * (@colors) *
- It was <star2>.
+ i have a @colors *
- Tell me more about your <star>.
""")
bot.reply("What color is my red shirt?", "Your shirt is red.")
bot.reply("What color is my blue car?", "Your car is blue.")
bot.reply("What color is my pink house?", "ERR: No Reply Matched")
bot.reply("What color is my dark blue jacket?", "Your jacket is dark blue.")
bot.reply("What color was Napoleoan's white horse?", "It was white.")
bot.reply("What color was my red shirt?", "It was red.")
bot.reply("I have a blue car.", "Tell me more about your car.")
bot.reply("I have a cyan car.", "ERR: No Reply Matched")
test.done()
exports.test_weighted_triggers = (test) ->
bot = new TestCase(test, """
+ * or something{weight=10}
- Or something. <@>
+ can you run a google search for *
- Sure!
+ hello *{weight=20}
- Hi there!
// Test that spaces before or after the {weight} tag are gobbled up along
// with the {weight} tag itself.
+ something{weight=100}
- Weighted something
+ something
- Unweighted something
+ nothing {weight=100}
- Weighted nothing
+ nothing
- Unweighted nothing
+ {weight=100}everything
- Weighted everything
+ everything
- Unweighted everything
+ {weight=100} blank
- Weighted blank
+ blank
- Unweighted blank
""")
bot.reply("Hello robot.", "Hi there!")
bot.reply("Hello or something.", "Hi there!")
bot.reply("Can you run a Google search for Node", "Sure!")
bot.reply("Can you run a Google search for Node or something", "Or something. Sure!")
bot.reply("something", "Weighted something")
bot.reply("nothing", "Weighted nothing")
bot.reply("everything", "Weighted everything")
bot.reply("blank", "Weighted blank")
test.done()
exports.test_empty_piped_arrays = (test) ->
errors = []
expected_errors = [
'Syntax error: Piped arrays can\'t begin or end with a | at stream() line 1 near ! array hello = hi|hey|sup|yo| (in topic random)'
'Syntax error: Piped arrays can\'t begin or end with a | at stream() line 2 near ! array something = |something|some thing (in topic random)'
'Syntax error: Piped arrays can\'t include blank entries at stream() line 3 near ! array nothing = nothing||not a thing (in topic random)'
]
console.error = (text)->
errors.push(text)
bot = new TestCase(test, """
! array hello = hi|hey|sup|yo|
! array something = |something|some thing
! array nothing = nothing||not a thing
+ [*] @hello [*]
- Oh hello there.
+ *
- Anything else?
""")
# Check that errors were thrown
test.deepEqual(errors, expected_errors)
# We also fix these, so these should also work
bot.reply("Hey!", "Oh hello there.")
bot.reply("sup", "Oh hello there.")
bot.reply("Bye!", "Anything else?")
bot.reply("Love you", "Anything else?")
test.done()
exports.test_empty_piped_alternations = (test) ->
errors = []
expected_errors = [
'Syntax error: Piped alternations can\'t begin or end with a | at stream() line 1 near + [*] (hi|hey|sup|yo|) [*] (in topic random)'
'Syntax error: Piped alternations can\'t begin or end with a | at stream() line 4 near + [*] (|good|great|nice) [*] (in topic random)'
'Syntax error: Piped alternations can\'t include blank entries at stream() line 7 near + [*] (mild|warm||hot) [*] (in topic random)'
]
console.error = (text)->
errors.push(text)
bot = new TestCase(test, """
+ [*] (hi|hey|sup|yo|) [*]
- Oh hello there.
+ [*] (|good|great|nice) [*]
- Oh nice!
+ [*] (mild|warm||hot) [*]
- Purrfect.
+ *
- Anything else?
""")
# Check that errors were thrown
test.deepEqual(errors, expected_errors)
# We also fix these, so these should also work
bot.reply("Hey!", "Oh hello there.")
bot.reply("sup", "Oh hello there.")
bot.reply("that's nice to hear", "Oh nice!")
bot.reply("so good", "Oh nice!")
bot.reply("You're hot!", "Purrfect.")
bot.reply("Bye!", "Anything else?")
bot.reply("Love you", "Anything else?")
test.done()
exports.test_empty_piped_optionals = (test) ->
errors = []
expected_errors = [
'Syntax error: Piped optionals can\'t begin or end with a | at stream() line 1 near + bot [*] [hi|hey|sup|yo|] [*] to me (in topic random)'
'Syntax error: Piped optionals can\'t begin or end with a | at stream() line 4 near + dog [*] [|good|great|nice] [*] to me (in topic random)'
'Syntax error: Piped optionals can\'t include blank entries at stream() line 7 near + cat [*] [mild|warm||hot] [*] to me (in topic random)'
]
console.error = (text)->
errors.push(text)
bot = new TestCase(test, """
+ bot [*] [hi|hey|sup|yo|] [*] to me
- Oh hello there.
+ dog [*] [|good|great|nice] [*] to me
- Oh nice!
+ cat [*] [mild|warm||hot] [*] to me
- Purrfect.
+ *
- Anything else?
""")
# Check that errors were thrown
test.deepEqual(errors, expected_errors)
# We also fix these, so these should also work
bot.reply("Bot say hey to me", "Oh hello there.")
bot.reply("bot w hi to me", "Oh hello there.")
bot.reply("dog be nice to me", "Oh nice!")
bot.reply("Dog don't be good to me", "Oh nice!")
bot.reply("Cat should not feel warm to me", "Purrfect.")
bot.reply("Bye!", "Anything else?")
bot.reply("Love you", "Anything else?")
test.done()
exports.test_empty_piped_missing_arrays = (test) ->
# Test case where an array reference is missing, and check that
# compiled regexp does not render as accidental wildcard of `||`
bot = new TestCase(test, """
! array test1 = hi|hey|sup|yo
! array test2 = yes|yeah|yep
! array test3 = bye|goodbye||byebye
// This trigger has an array reference that does not exist
// Check that new code prevents accidental double-pipe wildcard match
// e.g. /hi|hey|sup|yo||bye|goodbye|byebye/
// should become /hi|hey|sup|yo|bye|goodbye|byebye/
+ [*] (@test2|@test4|@test3) [*]
- Multi-array match
// Normal array trigger
+ [*] (@test1) [*]
- Test1 array match
""")
# We also fix these, so these should also work
bot.reply("Test One: hi", "Test1 array match")
bot.reply("Test Two: yeah", "Multi-array match")
test.done()
| true | TestCase = require("./test-base")
################################################################################
# Trigger Tests
################################################################################
exports.test_atomic_triggers = (test) ->
bot = new TestCase(test, """
+ hello bot
- Hello human.
+ what are you
- I am a RiveScript bot.
""")
bot.reply("Hello bot", "Hello human.")
bot.reply("What are you?", "I am a RiveScript bot.")
test.done()
exports.test_wildcard_triggers = (test) ->
bot = new TestCase(test, """
+ my name is *
- Nice to meet you, <star>.
+ * told me to say *
- Why did <star1> tell you to say <star2>?
+ i am # years old
- A lot of people are <star>.
+ i am _ years old
- Say that with numbers.
+ i am * years old
- Say that with fewer words.
""")
bot.reply("my name is PI:NAME:<NAME>END_PI", "Nice to meet you, PI:NAME:<NAME>END_PI.")
bot.reply("bob told me to say hi", "Why did PI:NAME:<NAME>END_PI tell you to say hi?")
bot.reply("i am 5 years old", "A lot of people are 5.")
bot.reply("i am five years old", "Say that with numbers.")
bot.reply("i am twenty five years old", "Say that with fewer words.")
test.done()
exports.test_alternatives_and_optionals = (test) ->
bot = new TestCase(test, """
+ what (are|is) you
- I am a robot.
+ what is your (home|office|cell) [phone] number
- It is 555-1234.
+ [please|can you] ask me a question
- Why is the sky blue?
+ (aa|bb|cc) [bogus]
- Matched.
+ (yo|hi) [computer|bot] *
- Matched.
""")
bot.reply("What are you?", "I am a robot.")
bot.reply("What is you?", "I am a robot.")
bot.reply("What is your home phone number?", "It is 555-1234.")
bot.reply("What is your home number?", "It is 555-1234.")
bot.reply("What is your cell phone number?", "It is 555-1234.")
bot.reply("What is your office number?", "It is 555-1234.")
bot.reply("Can you ask me a question?", "Why is the sky blue?")
bot.reply("Please ask me a question?", "Why is the sky blue?")
bot.reply("Ask me a question.", "Why is the sky blue?")
bot.reply("aa", "Matched.")
bot.reply("bb", "Matched.")
bot.reply("aa bogus", "Matched.")
bot.reply("aabogus", "ERR: No Reply Matched")
bot.reply("bogus", "ERR: No Reply Matched")
bot.reply("hi Aiden", "Matched.")
bot.reply("hi bot how are you?", "Matched.")
bot.reply("yo computer what time is it?", "Matched.")
bot.reply("yoghurt is yummy", "ERR: No Reply Matched")
bot.reply("hide and seek is fun", "ERR: No Reply Matched")
bot.reply("hip hip hurrah", "ERR: No Reply Matched")
test.done()
exports.test_trigger_arrays = (test) ->
bot = new TestCase(test, """
! array colors = red blue green yellow white
^ dark blue|light blue
+ what color is my (@colors) *
- Your <star2> is <star1>.
+ what color was * (@colors) *
- It was <star2>.
+ i have a @colors *
- Tell me more about your <star>.
""")
bot.reply("What color is my red shirt?", "Your shirt is red.")
bot.reply("What color is my blue car?", "Your car is blue.")
bot.reply("What color is my pink house?", "ERR: No Reply Matched")
bot.reply("What color is my dark blue jacket?", "Your jacket is dark blue.")
bot.reply("What color was Napoleoan's white horse?", "It was white.")
bot.reply("What color was my red shirt?", "It was red.")
bot.reply("I have a blue car.", "Tell me more about your car.")
bot.reply("I have a cyan car.", "ERR: No Reply Matched")
test.done()
exports.test_weighted_triggers = (test) ->
bot = new TestCase(test, """
+ * or something{weight=10}
- Or something. <@>
+ can you run a google search for *
- Sure!
+ hello *{weight=20}
- Hi there!
// Test that spaces before or after the {weight} tag are gobbled up along
// with the {weight} tag itself.
+ something{weight=100}
- Weighted something
+ something
- Unweighted something
+ nothing {weight=100}
- Weighted nothing
+ nothing
- Unweighted nothing
+ {weight=100}everything
- Weighted everything
+ everything
- Unweighted everything
+ {weight=100} blank
- Weighted blank
+ blank
- Unweighted blank
""")
bot.reply("Hello robot.", "Hi there!")
bot.reply("Hello or something.", "Hi there!")
bot.reply("Can you run a Google search for Node", "Sure!")
bot.reply("Can you run a Google search for Node or something", "Or something. Sure!")
bot.reply("something", "Weighted something")
bot.reply("nothing", "Weighted nothing")
bot.reply("everything", "Weighted everything")
bot.reply("blank", "Weighted blank")
test.done()
exports.test_empty_piped_arrays = (test) ->
errors = []
expected_errors = [
'Syntax error: Piped arrays can\'t begin or end with a | at stream() line 1 near ! array hello = hi|hey|sup|yo| (in topic random)'
'Syntax error: Piped arrays can\'t begin or end with a | at stream() line 2 near ! array something = |something|some thing (in topic random)'
'Syntax error: Piped arrays can\'t include blank entries at stream() line 3 near ! array nothing = nothing||not a thing (in topic random)'
]
console.error = (text)->
errors.push(text)
bot = new TestCase(test, """
! array hello = hi|hey|sup|yo|
! array something = |something|some thing
! array nothing = nothing||not a thing
+ [*] @hello [*]
- Oh hello there.
+ *
- Anything else?
""")
# Check that errors were thrown
test.deepEqual(errors, expected_errors)
# We also fix these, so these should also work
bot.reply("Hey!", "Oh hello there.")
bot.reply("sup", "Oh hello there.")
bot.reply("Bye!", "Anything else?")
bot.reply("Love you", "Anything else?")
test.done()
exports.test_empty_piped_alternations = (test) ->
errors = []
expected_errors = [
'Syntax error: Piped alternations can\'t begin or end with a | at stream() line 1 near + [*] (hi|hey|sup|yo|) [*] (in topic random)'
'Syntax error: Piped alternations can\'t begin or end with a | at stream() line 4 near + [*] (|good|great|nice) [*] (in topic random)'
'Syntax error: Piped alternations can\'t include blank entries at stream() line 7 near + [*] (mild|warm||hot) [*] (in topic random)'
]
console.error = (text)->
errors.push(text)
bot = new TestCase(test, """
+ [*] (hi|hey|sup|yo|) [*]
- Oh hello there.
+ [*] (|good|great|nice) [*]
- Oh nice!
+ [*] (mild|warm||hot) [*]
- Purrfect.
+ *
- Anything else?
""")
# Check that errors were thrown
test.deepEqual(errors, expected_errors)
# We also fix these, so these should also work
bot.reply("Hey!", "Oh hello there.")
bot.reply("sup", "Oh hello there.")
bot.reply("that's nice to hear", "Oh nice!")
bot.reply("so good", "Oh nice!")
bot.reply("You're hot!", "Purrfect.")
bot.reply("Bye!", "Anything else?")
bot.reply("Love you", "Anything else?")
test.done()
exports.test_empty_piped_optionals = (test) ->
errors = []
expected_errors = [
'Syntax error: Piped optionals can\'t begin or end with a | at stream() line 1 near + bot [*] [hi|hey|sup|yo|] [*] to me (in topic random)'
'Syntax error: Piped optionals can\'t begin or end with a | at stream() line 4 near + dog [*] [|good|great|nice] [*] to me (in topic random)'
'Syntax error: Piped optionals can\'t include blank entries at stream() line 7 near + cat [*] [mild|warm||hot] [*] to me (in topic random)'
]
console.error = (text)->
errors.push(text)
bot = new TestCase(test, """
+ bot [*] [hi|hey|sup|yo|] [*] to me
- Oh hello there.
+ dog [*] [|good|great|nice] [*] to me
- Oh nice!
+ cat [*] [mild|warm||hot] [*] to me
- Purrfect.
+ *
- Anything else?
""")
# Check that errors were thrown
test.deepEqual(errors, expected_errors)
# We also fix these, so these should also work
bot.reply("Bot say hey to me", "Oh hello there.")
bot.reply("bot w hi to me", "Oh hello there.")
bot.reply("dog be nice to me", "Oh nice!")
bot.reply("Dog don't be good to me", "Oh nice!")
bot.reply("Cat should not feel warm to me", "Purrfect.")
bot.reply("Bye!", "Anything else?")
bot.reply("Love you", "Anything else?")
test.done()
exports.test_empty_piped_missing_arrays = (test) ->
# Test case where an array reference is missing, and check that
# compiled regexp does not render as accidental wildcard of `||`
bot = new TestCase(test, """
! array test1 = hi|hey|sup|yo
! array test2 = yes|yeah|yep
! array test3 = bye|goodbye||byebye
// This trigger has an array reference that does not exist
// Check that new code prevents accidental double-pipe wildcard match
// e.g. /hi|hey|sup|yo||bye|goodbye|byebye/
// should become /hi|hey|sup|yo|bye|goodbye|byebye/
+ [*] (@test2|@test4|@test3) [*]
- Multi-array match
// Normal array trigger
+ [*] (@test1) [*]
- Test1 array match
""")
# We also fix these, so these should also work
bot.reply("Test One: hi", "Test1 array match")
bot.reply("Test Two: yeah", "Multi-array match")
test.done()
|
[
{
"context": "###\nCopyright 2016-2017 Balena\n\nLicensed under the Apache License, Version 2.",
"end": 27,
"score": 0.9346790313720703,
"start": 24,
"tag": "NAME",
"value": "Bal"
},
{
"context": " please check the README here: https://github.com/balena-io/balena-cli\n\n\tUse this command to push your local ",
"end": 1142,
"score": 0.9991821050643921,
"start": 1133,
"tag": "USERNAME",
"value": "balena-io"
},
{
"context": " local push --verbose false\n\t\t$ balena local push 192.168.2.10 --source . --destination /usr/src/app\n\t\t$ balena ",
"end": 2618,
"score": 0.9996176362037659,
"start": 2606,
"tag": "IP_ADDRESS",
"value": "192.168.2.10"
},
{
"context": " --destination /usr/src/app\n\t\t$ balena local push 192.168.2.10 -s /home/user/balenaProject -d /usr/src/app --bef",
"end": 2691,
"score": 0.9996418952941895,
"start": 2679,
"tag": "IP_ADDRESS",
"value": "192.168.2.10"
}
] | lib/actions/local/push.coffee | edmooney/balena-cli | 0 | ###
Copyright 2016-2017 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.
###
# Loads '.balena-sync.yml' configuration from 'source' directory.
# Returns the configuration object on success
#
_ = require('lodash')
balenaPush = require('balena-sync').capitano('balena-toolbox')
# TODO: This is a temporary workaround to reuse the existing `rdt push`
# capitano frontend in `balena local push`.
balenaPushHelp = '''
Warning: 'balena local push' requires an openssh-compatible client and 'rsync' to
be correctly installed in your shell environment. For more information (including
Windows support) please check the README here: https://github.com/balena-io/balena-cli
Use this command to push your local changes to a container on a LAN-accessible balenaOS device on the fly.
If `Dockerfile` or any file in the 'build-triggers' list is changed,
a new container will be built and run on your device.
If not, changes will simply be synced with `rsync` into the application container.
After every 'balena local push' the updated settings will be saved in
'<source>/.balena-sync.yml' and will be used in later invocations. You can
also change any option by editing '.balena-sync.yml' directly.
Here is an example '.balena-sync.yml' :
$ cat $PWD/.balena-sync.yml
local_balenaos:
app-name: local-app
build-triggers:
- Dockerfile: file-hash-abcdefabcdefabcdefabcdefabcdefabcdef
- package.json: file-hash-abcdefabcdefabcdefabcdefabcdefabcdef
environment:
- MY_VARIABLE=123
Command line options have precedence over the ones saved in '.balena-sync.yml'.
If '.gitignore' is found in the source directory then all explicitly listed files will be
excluded when using rsync to update the container. You can choose to change this default behavior with the
'--skip-gitignore' option.
Examples:
$ balena local push
$ balena local push --app-name test-server --build-triggers package.json,requirements.txt
$ balena local push --force-build
$ balena local push --force-build --skip-logs
$ balena local push --ignore lib/
$ balena local push --verbose false
$ balena local push 192.168.2.10 --source . --destination /usr/src/app
$ balena local push 192.168.2.10 -s /home/user/balenaProject -d /usr/src/app --before 'echo Hello' --after 'echo Done'
'''
module.exports = _.assign balenaPush,
signature: 'local push [deviceIp]'
help: balenaPushHelp
primary: true
root: true
| 55898 | ###
Copyright 2016-2017 <NAME>ena
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.
###
# Loads '.balena-sync.yml' configuration from 'source' directory.
# Returns the configuration object on success
#
_ = require('lodash')
balenaPush = require('balena-sync').capitano('balena-toolbox')
# TODO: This is a temporary workaround to reuse the existing `rdt push`
# capitano frontend in `balena local push`.
balenaPushHelp = '''
Warning: 'balena local push' requires an openssh-compatible client and 'rsync' to
be correctly installed in your shell environment. For more information (including
Windows support) please check the README here: https://github.com/balena-io/balena-cli
Use this command to push your local changes to a container on a LAN-accessible balenaOS device on the fly.
If `Dockerfile` or any file in the 'build-triggers' list is changed,
a new container will be built and run on your device.
If not, changes will simply be synced with `rsync` into the application container.
After every 'balena local push' the updated settings will be saved in
'<source>/.balena-sync.yml' and will be used in later invocations. You can
also change any option by editing '.balena-sync.yml' directly.
Here is an example '.balena-sync.yml' :
$ cat $PWD/.balena-sync.yml
local_balenaos:
app-name: local-app
build-triggers:
- Dockerfile: file-hash-abcdefabcdefabcdefabcdefabcdefabcdef
- package.json: file-hash-abcdefabcdefabcdefabcdefabcdefabcdef
environment:
- MY_VARIABLE=123
Command line options have precedence over the ones saved in '.balena-sync.yml'.
If '.gitignore' is found in the source directory then all explicitly listed files will be
excluded when using rsync to update the container. You can choose to change this default behavior with the
'--skip-gitignore' option.
Examples:
$ balena local push
$ balena local push --app-name test-server --build-triggers package.json,requirements.txt
$ balena local push --force-build
$ balena local push --force-build --skip-logs
$ balena local push --ignore lib/
$ balena local push --verbose false
$ balena local push 192.168.2.10 --source . --destination /usr/src/app
$ balena local push 192.168.2.10 -s /home/user/balenaProject -d /usr/src/app --before 'echo Hello' --after 'echo Done'
'''
module.exports = _.assign balenaPush,
signature: 'local push [deviceIp]'
help: balenaPushHelp
primary: true
root: true
| true | ###
Copyright 2016-2017 PI:NAME:<NAME>END_PIena
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.
###
# Loads '.balena-sync.yml' configuration from 'source' directory.
# Returns the configuration object on success
#
_ = require('lodash')
balenaPush = require('balena-sync').capitano('balena-toolbox')
# TODO: This is a temporary workaround to reuse the existing `rdt push`
# capitano frontend in `balena local push`.
balenaPushHelp = '''
Warning: 'balena local push' requires an openssh-compatible client and 'rsync' to
be correctly installed in your shell environment. For more information (including
Windows support) please check the README here: https://github.com/balena-io/balena-cli
Use this command to push your local changes to a container on a LAN-accessible balenaOS device on the fly.
If `Dockerfile` or any file in the 'build-triggers' list is changed,
a new container will be built and run on your device.
If not, changes will simply be synced with `rsync` into the application container.
After every 'balena local push' the updated settings will be saved in
'<source>/.balena-sync.yml' and will be used in later invocations. You can
also change any option by editing '.balena-sync.yml' directly.
Here is an example '.balena-sync.yml' :
$ cat $PWD/.balena-sync.yml
local_balenaos:
app-name: local-app
build-triggers:
- Dockerfile: file-hash-abcdefabcdefabcdefabcdefabcdefabcdef
- package.json: file-hash-abcdefabcdefabcdefabcdefabcdefabcdef
environment:
- MY_VARIABLE=123
Command line options have precedence over the ones saved in '.balena-sync.yml'.
If '.gitignore' is found in the source directory then all explicitly listed files will be
excluded when using rsync to update the container. You can choose to change this default behavior with the
'--skip-gitignore' option.
Examples:
$ balena local push
$ balena local push --app-name test-server --build-triggers package.json,requirements.txt
$ balena local push --force-build
$ balena local push --force-build --skip-logs
$ balena local push --ignore lib/
$ balena local push --verbose false
$ balena local push 192.168.2.10 --source . --destination /usr/src/app
$ balena local push 192.168.2.10 -s /home/user/balenaProject -d /usr/src/app --before 'echo Hello' --after 'echo Done'
'''
module.exports = _.assign balenaPush,
signature: 'local push [deviceIp]'
help: balenaPushHelp
primary: true
root: true
|
[
{
"context": "/graylog.example.com)\n# GRAYLOG_API_TOKEN (e.g. 098f6bcd4621d373cade4e832627b4f6)\n# GRAYLOG_SEPARATOR (e.g. ','. Default: \"\\n\")\n",
"end": 254,
"score": 0.6019664406776428,
"start": 222,
"tag": "KEY",
"value": "098f6bcd4621d373cade4e832627b4f6"
},
{
"context": "# requires hubot-auth be present\n#\n# Author:\n# gfjohnson\n\nfs = require 'fs'\nmoment = require 'moment'\nCIDR",
"end": 430,
"score": 0.9997026324272156,
"start": 421,
"tag": "USERNAME",
"value": "gfjohnson"
},
{
"context": " 7\n 24 * 30\n]\n\nUA_Network = new CIDRMatcher [\n '137.229.0.0/16'\n '199.165.64.0/18'\n '10.0.0.0/8'\n '172.16.",
"end": 1503,
"score": 0.9997360110282898,
"start": 1492,
"tag": "IP_ADDRESS",
"value": "137.229.0.0"
},
{
"context": "Network = new CIDRMatcher [\n '137.229.0.0/16'\n '199.165.64.0/18'\n '10.0.0.0/8'\n '172.16.0.0/12'\n '192.168.0",
"end": 1523,
"score": 0.9997273087501526,
"start": 1511,
"tag": "IP_ADDRESS",
"value": "199.165.64.0"
},
{
"context": "tcher [\n '137.229.0.0/16'\n '199.165.64.0/18'\n '10.0.0.0/8'\n '172.16.0.0/12'\n '192.168.0.0/16'\n]\n\nlist_n",
"end": 1539,
"score": 0.9996811747550964,
"start": 1531,
"tag": "IP_ADDRESS",
"value": "10.0.0.0"
},
{
"context": "229.0.0/16'\n '199.165.64.0/18'\n '10.0.0.0/8'\n '172.16.0.0/12'\n '192.168.0.0/16'\n]\n\nlist_names = [\n 'black",
"end": 1556,
"score": 0.9997297525405884,
"start": 1546,
"tag": "IP_ADDRESS",
"value": "172.16.0.0"
},
{
"context": ".165.64.0/18'\n '10.0.0.0/8'\n '172.16.0.0/12'\n '192.168.0.0/16'\n]\n\nlist_names = [\n 'blacklist'\n 'whitelist'",
"end": 1575,
"score": 0.9997194409370422,
"start": 1564,
"tag": "IP_ADDRESS",
"value": "192.168.0.0"
},
{
"context": "\n]\n\nrobotRef = false\nfwdata = false\n\nfwnames =\n '10.9.0.252': 'Fairbanks-1'\n '10.9.0.253': 'Fairbanks-2'\n '",
"end": 1940,
"score": 0.9997555613517761,
"start": 1930,
"tag": "IP_ADDRESS",
"value": "10.9.0.252"
},
{
"context": "false\n\nfwnames =\n '10.9.0.252': 'Fairbanks-1'\n '10.9.0.253': 'Fairbanks-2'\n '10.9.128.10': 'Anchorage-1'\n ",
"end": 1970,
"score": 0.9997552633285522,
"start": 1960,
"tag": "IP_ADDRESS",
"value": "10.9.0.253"
},
{
"context": "': 'Fairbanks-1'\n '10.9.0.253': 'Fairbanks-2'\n '10.9.128.10': 'Anchorage-1'\n '10.9.128.11': 'Anchorage-2'\n ",
"end": 2001,
"score": 0.9997538924217224,
"start": 1990,
"tag": "IP_ADDRESS",
"value": "10.9.128.10"
},
{
"context": ": 'Fairbanks-2'\n '10.9.128.10': 'Anchorage-1'\n '10.9.128.11': 'Anchorage-2'\n '10.9.192.10': 'Juneau-1'\n '10",
"end": 2032,
"score": 0.9997454285621643,
"start": 2021,
"tag": "IP_ADDRESS",
"value": "10.9.128.11"
},
{
"context": ": 'Anchorage-1'\n '10.9.128.11': 'Anchorage-2'\n '10.9.192.10': 'Juneau-1'\n '10.9.192.11': 'Juneau-2'\n\nif proc",
"end": 2063,
"score": 0.9997537732124329,
"start": 2052,
"tag": "IP_ADDRESS",
"value": "10.9.192.10"
},
{
"context": "11': 'Anchorage-2'\n '10.9.192.10': 'Juneau-1'\n '10.9.192.11': 'Juneau-2'\n\nif process.env.HUBOT_AUTH_ADMIN\n h",
"end": 2091,
"score": 0.9997491240501404,
"start": 2080,
"tag": "IP_ADDRESS",
"value": "10.9.192.11"
},
{
"context": "ms\n params.path = \"/devices/entry[@name='#{params.device}']#{params.path}\"\n return panGetConfig par",
"end": 5265,
"score": 0.751915454864502,
"start": 5265,
"tag": "EMAIL",
"value": ""
},
{
"context": "eturn false unless isObject params\n for key in ['fqdn','cmd']\n return \"#{func_name}: missing requi",
"end": 7429,
"score": 0.5122842788696289,
"start": 7427,
"tag": "KEY",
"value": "fq"
},
{
"context": "ess attackAutoBanEnabled\n entry = \n creator: \"robot\"\n list: list_name\n created: moment().format",
"end": 12618,
"score": 0.994260311126709,
"start": 12613,
"tag": "USERNAME",
"value": "robot"
},
{
"context": "H:mm:ss')\n params =\n Bucket: s3bucket\n Key: \"#{s3pathPrefix}/#{filename}\"\n ContentType: \"text/#{type}\"\n Body: body\n ",
"end": 13664,
"score": 0.9324366450309753,
"start": 13635,
"tag": "KEY",
"value": "\"#{s3pathPrefix}/#{filename}\""
},
{
"context": " args\n return unless is2fa msg\n\n keys =\n N: 'name'\n f: 'from'\n t: 'to'\n s: 'src'\n d: 'd",
"end": 19469,
"score": 0.5798593759536743,
"start": 19465,
"tag": "KEY",
"value": "name"
},
{
"context": " \" -i <ip or cidr> Address or cidr entry, e.g. 127.0.0.1/8\"\n \" -d <domain> Domain entry, e.g. exa",
"end": 23787,
"score": 0.9996206760406494,
"start": 23778,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " Search string, must only match one entry; e.g. 127.0.0.1\"\n \" -e <expiration> Expiration, e.g. -12h, +",
"end": 32443,
"score": 0.9996874332427979,
"start": 32434,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " \" -i <ip or cidr> Address or cidr entry, e.g. 127.0.0.1/8\"\n \" -d <domain> Domain entry, e.g. exa",
"end": 36882,
"score": 0.9996843338012695,
"start": 36873,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | src/uapanfw.coffee | gsfjohnson/hubut-uapanfw | 0 | # Description:
# Manage black/white lists for UA PA FW.
#
# Dependencies:
# moment
#
# Configuration:
# xxxxxxxxxxx [required] - API KEY
# GRAYLOG_URL (e.g. https://graylog.example.com)
# GRAYLOG_API_TOKEN (e.g. 098f6bcd4621d373cade4e832627b4f6)
# GRAYLOG_SEPARATOR (e.g. ','. Default: "\n")
#
#
# Commands:
# hubot firewall - firewall commands
#
# Notes:
# requires hubot-auth be present
#
# Author:
# gfjohnson
fs = require 'fs'
moment = require 'moment'
CIDRMatcher = require 'cidr-matcher'
sprintf = require("sprintf-js").sprintf
AWS = require 'aws-sdk'
s3 = new AWS.S3()
request = require 'request'
parse = require 'yargs-parser'
modulename = 'fw'
data_file = modulename + ".json"
safety_fail_note = 'If this is time critical ask a human; otherwise please open a ticket.'
displayfmt = '%-4s %-50s %-15s %-10s %s'
timefmt = 'YYYY-MM-DD HH:mm:ss ZZ'
msOneMinute = 60 * 1000
msFiveMinutes = 300 * 1000
glApi = null;
s3bucket = 'ua-oit-security-pub'
s3pathPrefix = 'stats'
defaultNotifyAdmin = 'all' # normally null, for 'all'
defaultNotifySubscribers = 'all' # normally null, for 'all'
# enable or disable auto-banning
attackAutoBanEnabled = true
attackAutoBanNotifySubscribers = true
# auto-ban after X occurances
attackBanAfterOccurances = 5
# if no attacks detected in this duration, expire counter
attackExpirationHours = 6
# escalating ban durations for 2nd, 3rd, etc duration
attackBanHours = [
1
24
24 * 7
24 * 30
]
UA_Network = new CIDRMatcher [
'137.229.0.0/16'
'199.165.64.0/18'
'10.0.0.0/8'
'172.16.0.0/12'
'192.168.0.0/16'
]
list_names = [
'blacklist'
'whitelist'
'autoban'
]
list_types = [
'domain'
'cidr'
'url'
]
preventDomainBlacklist = [
[ 'alaska.edu', /alaska\.edu$/ ]
[ 'uaf.edu', /uaf\.edu$/ ]
]
preventUrlBlacklist = [
[ 'alaska.edu', /[^\/]+alaska.edu\// ]
[ 'uaf.edu', /[^\/]+uaf.edu\// ]
]
robotRef = false
fwdata = false
fwnames =
'10.9.0.252': 'Fairbanks-1'
'10.9.0.253': 'Fairbanks-2'
'10.9.128.10': 'Anchorage-1'
'10.9.128.11': 'Anchorage-2'
'10.9.192.10': 'Juneau-1'
'10.9.192.11': 'Juneau-2'
if process.env.HUBOT_AUTH_ADMIN
hubotAuthAdmin = process.env.HUBOT_AUTH_ADMIN.split ','
else
console.warn "#{modulename}: HUBOT_AUTH_ADMIN environment variable not set."
# borrowed from
# http://stackoverflow.com/questions/9796764/how-do-i-sort-an-array-with-coffeescript
sortBy = (key, a, b, r) ->
r = if r then 1 else -1
return -1*r if a[key] > b[key]
return +1*r if a[key] < b[key]
return 0
isArray = Array.isArray or (obj) -> toString.call(obj) == '[object Array]'
isString = (obj) -> toString.call(obj) == '[object String]'
isObject = (obj) -> toString.call(obj) == '[object Object]'
isAdmin = (msg, reply = true) ->
console.error 'bad robotRef' unless robotRef
who = msg.envelope.user.name
return true if who in hubotAuthAdmin
msg.reply "This requires administrator privilege." if reply
return false
isAuthorized = (msg, reply = true) ->
console.error 'bad robotRef' unless robotRef
u = msg.envelope.user
return true if robotRef.auth.hasRole(u,'fw')
msg.reply "Not authorized. Missing fw role." if reply
return false
is2fa = (msg, reply = true) ->
console.error 'bad robotRef' unless robotRef
u = msg.envelope.user
return true if robotRef.auth.is2fa(u)
msg.reply "2fa required. Use `auth 2fa` to validate identity." if reply
return false
isTerse = (who) ->
fwdata['terse'] = {} unless 'terse' of fwdata
return true if who of fwdata.terse && moment(fwdata.terse[who]).isAfter()
return false
isBanned = (ban_expires) ->
expires = moment(ban_expires)
return false unless expires.isValid()
return true if expires.isAfter()
return false
panConfigDevicesVsysRulebaseSecurityRule = (params, callback) ->
func_name = 'panConfigDevicesVsysRulebaseSecurityRule'
params = { name: params } if isString params
return false unless isObject params
return false unless 'name' of params
params.path = "/rulebase/security/rules/entry[@name='#{params.name}']"
return panConfigDevicesVsys params, callback
panConfigDeviceVsysAddress = (params, callback) ->
func_name = 'panConfigDeviceVsysAddress'
params = { name: params } if isString params
return false unless isObject params
for key in ['name']
return "#{func_name}: missing required param: #{key}" unless key of param
params.path = "/address/entry[@name='#{params.name}']"
return panConfigDevicesVsys params, callback
panConfigDevicesVsys = (params, callback) ->
func_name = 'panConfigDevicesVsys'
params = { path: params } if isString params
return false unless isObject params
for key in ['path']
return "#{func_name}: missing required param: #{key}" unless key of param
params.vsys = 'vsys1' unless 'vsys' of params
params.path = "/vsys/entry[@name='#{params.vsys}']/#{params.path}"
return panConfigDevices params, callback
panConfigDevices = (params, callback) ->
func_name = 'panConfigDevices'
params = { path: params } if isString params
return false unless isObject params
for key in ['path']
return "#{func_name}: missing required param: #{key}" unless key of param
params.device = 'localhost.localdomain' unless 'device' of params
params.path = "/devices/entry[@name='#{params.device}']#{params.path}"
return panGetConfig params, callback
panConfig = (params, callback) ->
func_name = 'panConfig'
return false unless isObject params
for key in ['fqdn','path','key']
return "#{func_name}: missing required param: #{key}" unless key of param
params.action = 'get' unless 'action' of params
unless params.action in ['get']
return "#{func_name}: invalid action param: #{params.action}"
q =
type: 'config'
action: params.action
xpath: "/config#{params.path}"
key: params.key
options =
url: "https://#{params.fqdn}/api/"
qs: q
strictSSL: false
accept: 'text/xml'
request.get options, (err, res, body) ->
return callback(null, err) if err
# XXX: convert xml2json
return callback(body)
return true
xmlVal = (name,val) ->
return '' unless name of obj
return "<#{name}>#{val}</#{name}>"
panOpTestSecurityPolicyMatch = (params, callback) ->
func_name = 'panOpTestSecurityPolicyMatch'
# cmd: <test><security-policy-match><from></from></security-policy-match></test>
#params = { path: params } if isString params
cmd = ''
return false unless isObject params
required = [
'destination'
'destination-port'
'protocol'
'source'
]
for key in required
return "#{func_name}: missing required param: #{key}" unless key of params
cmd += xmlVal key, params[key]
optional = [
'application'
'category'
'from'
'show-all'
'source-user'
'to'
]
for key in optional
if key of params
cmd += xmlVal key, params[key]
params.cmd = "<test><security-policy-match>#{cmd}</security-policy-match></test>"
return panOp params, callback
panCommit = (params, callback) ->
# cmd: <commit></commit>
#params = { path: params } if isString params
cmd = ''
return false unless isObject params
params.type = 'commit'
optional = [
'description'
]
for name in optional
if name of params
cmd += xmlVal name, params[name]
params.cmd = xmlVal 'commit', cmd
return panOp params, callback
panOp = (params, callback) ->
func_name = 'panOp'
return false unless isObject params
for key in ['fqdn','cmd']
return "#{func_name}: missing required param: #{key}" unless key of param
param.type = 'op' unless 'type' of params
unless params.type in ['op','commit']
return "#{func_name}: invalid param type: #{params.type}"
q =
type: 'op'
cmd: params.cmd
options =
url: "https://#{params.fqdn}/api/"
qs: q
strictSSL: false
accept: 'text/xml'
request.get options, (err, res, body) ->
return callback(null, err) if err
# XXX: convert xml2json
return callback(body)
return true
oneMinuteWorker = ->
queryAndProcessAttacks()
setTimeout oneMinuteWorker, msOneMinute
fiveMinuteWorker = ->
for list in ['autoban','blacklist','whitelist']
uploadReport list, 'all', 'list'
for type in ['url','cidr','domain']
continue if list is 'autoban' and type isnt 'cidr'
uploadReport list, type, 'terse'
expireAttackers()
preExpireNotify 'blacklist'
preExpireNotify 'whitelist'
expireEntriesFromList 'blacklist'
expireEntriesFromList 'whitelist'
expireEntriesFromList 'autoban'
setTimeout fiveMinuteWorker, msFiveMinutes
queryAndProcessCommits = ->
func_name = 'queryAndProcessCommits'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
console.log "#{log_date} #{func_name} --"
return if glApi is null
q =
query: 'logfile:SYSTEM\/general',
fields: 'message,source',
range: 60,
decorate: 'true'
glApi.query q
#console.log 'exec glApi.get() with glApi.options: ', JSON.stringify glApi.options, null, 2
glApi.get() (err, res, body) ->
unless res.statusCode is 200
return console.warn 'Error requesting Graylog url statusCode=', res.statusCode, 'err=', err, 'options=', glApi.options
glresponse = JSON.parse body
#console.log 'glApi returns body:', JSON.stringify jsonbody, null, 2
events = glresponse.messages.map (m) => m.message
for event in events
processCommit event
queryAndProcessAttacks = ->
func_name = 'queryAndProcessAttacks'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
console.log "#{log_date} #{func_name} --"
return if glApi is null
q =
query: 'logfile:THREAT\\/vulnerability',
fields: 'message,source,addrsrc,addrdst,action',
range: 60,
decorate: 'true'
glApi.query q
#console.log 'exec glApi.get() with glApi.options: ', JSON.stringify glApi.options, null, 2
glApi.get() (err, res, body) ->
unless res.statusCode is 200
return console.warn 'Error requesting Graylog url statusCode=', res.statusCode, 'err=', err, 'options=', glApi.options
glresponse = JSON.parse body
#console.log 'glApi returns body:', JSON.stringify jsonbody, null, 2
events = glresponse.messages.map (m) => m.message
for event in events
# skip if already on the attack list
#continue if fwdata.attackers[event.addrsrc] and fwdata.attackers[event.addrsrc].banned
# skip unless action
continue unless event.action in ['block-ip','drop','reset-both']
# skip if source is internal
continue if UA_Network.contains event.addrsrc
addAttackSource event
addAttackSource = (event) ->
func_name = 'addAttackSource'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
src = event.addrsrc
ldt = moment(event.timestamp).format('HH:mm:ss')
unless src of fwdata.attackers
console.log "#{log_date} #{func_name}: new source #{event.addrsrc}"
fwdata.attackers[src] =
attacks: 0
attacker: src
victims: []
created: moment().format()
banexpires: 0
msgs: []
fwdata.attackers[src].attacks++
fwdata.attackers[src].last = moment().format()
fwdata.attackers[src].msgs.push "#{ldt} / #{event.source} / #{event.message}"
if fwdata.attackers[src].msgs.length > attackBanAfterOccurances
fwdata.attackers[src].msgs.shift()
if event.addrdst not in fwdata.attackers[src].victims
fwdata.attackers[src].victims.push event.addrdst
# ban if attack count exceeds attackBanAfterOccurances value
if fwdata.attackers[src].attacks >= attackBanAfterOccurances
# do not ban if already banned
banAttackSource fwdata.attackers[src] unless isBanned fwdata.attackers[src].banexpires
banAttackSource = (attackSource) ->
func_name = 'banAttackSource'
#console.log 'banAttackSource --'
src = attackSource.attacker
msgs = attackSource.msgs.join "\n"
status = 'would have auto-banned'
status = 'auto-banning' if attackAutoBanEnabled
attackSource.bancount = 0 unless attackSource['bancount']
bc = fwdata.attackers[src].bancount
if attackSource.bancount >= (attackBanHours.length - 1)
bc = attackBanHours.length - 1
fwdata.attackers[src].bancount++
banHours = attackBanHours[bc]
attackSource.banexpires = moment().add(banHours,'hours').format()
usermsg = "#{modulename}_#{func_name}: #{status} `#{src}` for #{banHours} hours due to" +
" #{attackBanAfterOccurances} events since" +
" #{moment(attackSource.created).format('YYYY-MM-DD HH:mm:ss')}"
usermsg += " and #{bc} previous bans" if bc > 0
usermsg += ": ```#{msgs}```"
list_name = 'autoban'
notifySubscribers list_name, usermsg
# only notify unless enabled
return unless attackAutoBanEnabled
entry =
creator: "robot"
list: list_name
created: moment().format()
expires: attackSource.banexpires
type: 'cidr'
val: attackSource.attacker
reason: "#{attackSource.attacks} attacks\n#{msgs}"
result = addListEntry entry
if result isnt true
usermsg = "Failed to add `#{entry.val}` (#{entry.type}) to list" +
" #{list_name}. Error: `#{result}`"
notifySubscribers list_name, usermsg
#notifymsg = "#{entry.creator} added `#{entry.val}` (#{entry.type}) to list"
#notifymsg += " #{list_name}. Expires `#{entry.expires}`."
#notifySubscribers list_name, notifymsg
uploadReport = (list_name, list_type, list_style) ->
func_name = 'uploadReport'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
params =
type: list_type
r = buildList list_name, params
s3upload "#{list_name}-#{list_type}-#{list_style}", r[list_style]
s3upload = (filename,body,type='plain') ->
func_name = 's3upload'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
params =
Bucket: s3bucket
Key: "#{s3pathPrefix}/#{filename}"
ContentType: "text/#{type}"
Body: body
s3.putObject params, (err, data) ->
if err
return console.error "#{log_date} #{func_name}: #{err}"
console.log "#{log_date} #{func_name}: #{params.ContentType} #{params.Bucket}:#{params.Key} success"
expireAttackers = ->
func_name = 'expireAttackers'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
console.log "#{log_date} #{func_name} --"
for src of fwdata.attackers
attackSource = fwdata.attackers[src]
# skip if last seen in x duration
expire = moment(attackSource.last).isBefore( moment().subtract(attackExpirationHours,'hour') )
continue unless expire
# skip if currently banned
continue if attackSource['banexpires'] and isBanned attackSource.banexpires
# flush it
console.log "#{moment().format('YYYY-MM-DD HH:mm:ss')} #{func_name}: #{src} "+
"last seen: #{moment(fwdata.attackers[src].last).fromNow()}"
delete fwdata.attackers[src]
preExpireNotify = (list_name) ->
func_name = 'preExpireNotify'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
dt_hour_from_now = moment().add(1,'hours')
params =
expires: 'before'
when: dt_hour_from_now
expire_notify: true
r = buildList list_name, params
return unless r.lines > 0
expiring = r.list
usermsg = "fw: #{list_name} entries will expire soon: " +
"```#{expiring}```"
notifySubscribers list_name, usermsg
expireEntriesFromList = (list_name) ->
func_name = 'expireEntriesFromList'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
unless list_name of fwdata.lists
return console.error "#{log_date} #{func_name}: #{list_name} does not exist"
dt_now = moment()
params =
expires: 'before'
when: dt_now
r = buildList list_name, params
return unless r.lines > 0
deleted = r.list
removequeue = []
list = fwdata.lists[list_name]
for entry in list when moment(entry.expires).isBefore(dt_now)
removequeue.push entry
while removequeue.length > 0
entry = removequeue.shift()
list.splice(list.indexOf(entry), 1)
usermsg = "fw: #{list_name} entries expired and have been removed: " +
"```#{deleted}```"
notifySubscribers list_name, usermsg
writeData()
notifySubscribers = (list_name, usermsg, current_un = false, who = defaultNotifySubscribers) ->
func_name = 'notifySubscribers'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
return console.error "#{log_date} #{func_name}: bad robotRef" unless robotRef
return console.error "#{log_date} #{func_name}: bad list: #{list_name}" unless list_name in list_names
return console.error "#{log_date} #{func_name}: list not created: #{list_name}" unless list_name of fwdata.notify
return console.error "#{log_date} #{func_name}: list empty: #{list_name}" unless isArray fwdata.notify[list_name]
un_list = who if isArray who
un_list = [who] if isString who
un_list = fwdata.notify[list_name] if who == 'all' or who is null
return notifyUsers usermsg, current_un, un_list
notifyUsers = (usermsg, current_un = false, who = null) ->
func_name = 'notifyUsers'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
return console.error "#{log_date} #{func_name}: bad robotRef" unless robotRef
return console.error "#{log_date} #{func_name}: must specify who" if who is null
un_list = who if isArray who
un_list = [who] if isString who
for un in un_list
console.log "#{log_date} #{func_name} #{un}: #{usermsg}"
robotRef.send { room: un }, usermsg unless current_un && un == current_un
return un_list
notifyAdmins = (usermsg, current_un = false, who = defaultNotifyAdmin) ->
func_name = 'notifyAdmins'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
return console.error "#{log_date} #{func_name}: bad robotRef" unless robotRef
un_list = who if isArray who
un_list = [who] if isString who
un_list = hubotAuthAdmin if who == 'all' or who is null
for un in un_list when un.indexOf('U') != 0
console.log "#{log_date} #{func_name} #{un}: #{usermsg}"
robotRef.send { room: un }, usermsg unless current_un && un == current_un
return un_list
listShowAdmins = (robot, msg) ->
func_name = 'listShowAdmins'
fullcmd = String msg.match.shift()
who = msg.envelope.user.name
logmsg = "#{modulename}_#{func_name}: #{who} requested: #{fullcmd}"
robot.logger.info logmsg
msg.reply "#{modulename} admins: #{hubotAuthAdmin.join(', ')}"
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: " +
"provided list of admins"
robot.logger.info logmsg
ruleAddEntryHelp = (robot, msg) ->
func_name = 'ruleAddEntryHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} rule <options>"
""
"Required options:"
" -N, --name Rule name"
" -f, --from From zone, eg. Untrust"
" -t, --to To zone, e.g. DMZ"
" -s, --src Source address"
" -d, --dst Dest address"
" -S, --svc Service, e.g. service-http"
" -a, --app Application, e.g. web-browse"
" -e, --erd URL to Firewall Access Diagram"
""
"Note: if rule name already exists, this will replace it!"
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
ruleAddEntry = (robot, msg) ->
func_name = 'ruleAddEntry'
fullcmd = String msg.match.shift()
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name}: #{who}: #{fullcmd}"
cmd = String msg.match.shift()
return ruleAddEntryHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
console.log "cmd: #{cmd} out: #{JSON.stringify args}"
return ruleAddEntryHelp(robot,msg) if 'h' of args
return ruleAddEntryHelp(robot,msg) if 'help' of args
return unless is2fa msg
keys =
N: 'name'
f: 'from'
t: 'to'
s: 'src'
d: 'dst'
S: 'svc'
a: 'app'
e: 'erd'
for key of keys
if key of args
args[ keys[key] ] = args[key]
delete args[key]
args.requestor = who
result = processRule args, who
unless result is true
errmsg = "Unable to submit request"
errmsg += ":```#{result}```" unless result is false
return msg.send errmsg
msg.send "Submitted rule for review!"
normType = (val) ->
return val.join ", " if isArray val
return val if isString val
return "unable to handle value"
normHttpPrefix = (val) ->
if val.toLowerCase().indexOf('http://') == 0
return val.replace(/http:\/\//i,'')
return val
processRule = (rule, who) ->
func_name = 'processRule'
return false unless isObject rule
required = [
'requestor'
'src'
'dst'
'name'
'erd'
]
for name in required
return "#{func_name}: missing required parameter: #{name}" unless name of rule
unless 'app' of rule or 'svc' of rule
return "#{func_name}: missing required parameter: app or svc"
# convert single values to array
for key in ['from','to','src','dst','app','svc']
continue unless key of rule # skip if not present
rule[key] = [ rule[key] ] unless isArray rule[key]
# check zones
# XXX: check against zone names
# check addresses
# XXX: check against address and address-group objects
# remove slack url prefixes from fqdn style object names
for key in ['src','dst']
newarray = []
for val in rule[key]
newarray.push normHttpPrefix val
rule[key] = newarray
# check app
# XXX: check against app names
# check svc
# XXX: check against service and service-group objects
# add or update request queue
dt_now = moment()
req =
id: "#{who[0..2]}#{dt_now.format('MMDDHHmmss')}"
by: who
type: 'rule'
when: dt_now.format()
request: rule
addUpdateRequestEntry req
return true
addUpdateRequestEntry = (req) ->
return false unless isObject req
return false unless 'id' of req
usermsg = markupRequest req
notifiedAdmins = notifyAdmins usermsg
notifyUsers usermsg, false, req.by unless req.by in notifiedAdmins
fwdata.requests[req.id] = req
writeData()
return true
deleteRequestEntry = (req, res) ->
return false unless isObject req
return false unless isObject res
return false unless 'id' of req
usermsg = markupRequest req, res
notifiedAdmins = notifyAdmins usermsg
notifyUsers usermsg, false, req.by unless req.by in notifiedAdmins
delete fwdata.requests[req.id]
writeData()
return true
markupRequest = (req, res = null) ->
type = req.type[0].toUpperCase() + req.type[1..-1].toLowerCase()
adminmsg = "#{type} requested by #{req.by}."
if res
adminmsg = "#{type} #{res.action} by #{res.by}."
adminmsg += "\n> *Comment* #{res.comment}" if 'comment' of res
adminmsg += "\nRequest metadata:"
for key of req
continue if key in ['request','type']
adminmsg += "\n> *#{key}* #{req[key]}"
adminmsg += "\nRequest:"
entry = req.request
for key of entry
adminmsg += "\n> *#{key}* #{entry[key]}"
return adminmsg
requestQueue_NotifyAdmin_list = (entry, who, comment = null, action = 'requested', notifyList = null) ->
adminmsg = "List #{action} by #{who}."
adminmsg += "\n> *Comment* #{comment}" unless comment is null
for key of entry
adminmsg += "\n> *#{key}* #{entry[key]}"
#adminmsg += "> *Name* #{entry.name}"
#adminmsg += "\n> *Value* #{normType entry.val}"
#adminmsg += "\n> *Type* #{normType entry.type}"
#adminmsg += "\n> *Expires* #{normType entry.expires}"
notifyAdmins adminmsg, false, notifyList
helperListName = (list_name) ->
return false unless isString list_name
return false unless list_name.length > 0
return 'whitelist' if list_name.indexOf('w') == 0
return 'blacklist' if list_name.indexOf('b') == 0
return 'autoban' if list_name.indexOf('a') == 0
if list_name of fwdata.lists
return list_name
return false
listAddEntryHelp = (robot, msg) ->
func_name = 'listAddEntryHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} list add -L <list> -i|-d|-u <value> [options]"
""
"Required options:"
" -L <list> List name; e.g. blacklist"
" -i <ip or cidr> Address or cidr entry, e.g. 127.0.0.1/8"
" -d <domain> Domain entry, e.g. example.com"
" -u <url> URL entry, e.g. example.com/phishing/page123"
""
"Optional:"
" -e <date> Expiration, e.g. +12h, +30d, +6m, +1y, 2021-10-21"
" -r Request; required if not authorized and 2fa enabled"
" -R <reason> Reason for entry, e.g. \"SR 12345\""
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
listAddEntry = (robot, msg) ->
func_name = 'listAddEntry'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
cmd = String msg.match[1]
return listAddEntryHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
console.log "#{log_date} #{func_name}: cmd: #{cmd} out: #{JSON.stringify args}"
return listAddEntryHelp(robot,msg) if 'h' of args
return listAddEntryHelp(robot,msg) if 'help' of args
entry =
creator: who
created: moment().format()
expires: moment().add(1, 'months').format()
unless 'L' of args
return msg.send "#{func_name}: must specify `-L <list>`"
entry.list = helperListName args['L']
unless entry.list
return msg.send "#{func_name}: invalid list: #{args['L']}"
if 'i' of args
addrs = false
if isArray args.i
addrs = args.i
if isString args.i
addrs = [args.i]
addrs = args.i.split(',') if args.i.indexOf(',') > 0
if addrs is false
usermsg = "#{func_name}: invalid ip-address or cidr"
logmsg = "#{modulename}_#{func_name}: #{who} request failed: #{usermsg}"
robot.logger.info logmsg
return msg.send usermsg
for addr in addrs
if extra = addr.match /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})((?:\/\d{1,2}|))$/
if extra[2] isnt '' and extra[2] > -1 and extra[2] < 16
usermsg = "#{func_name}: Blocking addresses with cidr less than /16 not allowed."
logmsg = "#{modulename}_#{func_name}: #{who} request failed: #{usermsg}"
robot.logger.info logmsg
msg.send usermsg unless isAdmin msg, false # no redundant admin notifications
return notifyAdmins logmsg
else
usermsg = "#{func_name}: invalid ip-address or cidr"
logmsg = "#{modulename}_#{func_name}: #{who} request failed: #{usermsg}"
robot.logger.info logmsg
return msg.send usermsg
if UA_Network.contains addr
usermsg = "Blocking addresses in the UA_Network is not allowed. #{safety_fail_note}"
logmsg = "#{modulename}_#{func_name}: #{who} request failed safety check: #{fullcmd}"
robot.logger.info logmsg
msg.send usermsg unless isAdmin msg, false # no redundant admin notifications
return notifyAdmins "#{logmsg}\nReason: #{usermsg}"
entry.type = 'cidr'
entry.val = addrs[0] if addrs.length == 1
entry.vals = addrs if addrs.length > 1
if 'd' of args
domain = normHttpPrefix args.d
for arr in preventDomainBlacklist when domain.toLowerCase().match arr[1]
usermsg = "Blocking `#{arr[0]}` is not allowed. #{safety_fail_note}"
logmsg = "#{modulename}_#{func_name}: #{who} request failed safety check: #{fullcmd}"
robot.logger.info logmsg
msg.send usermsg
return notifyAdmins "#{logmsg}\nReason: #{usermsg}"
entry.type = 'domain'
entry.val = domain
if 'u' of args
url = normHttpPrefix args.u
if url.toLowerCase().indexOf('https://') == 0
return msg.send "#{entry.list}ing of https links not supported."
for arr in preventUrlBlacklist when url.toLowerCase().match arr[1]
usermsg = "Blocking `#{arr[0]}` is not allowed. #{safety_fail_note}"
logmsg = "#{modulename}_#{func_name}: #{who} request failed safety check: #{fullcmd}"
robot.logger.info logmsg
msg.send usermsg
return notifyAdmins "#{logmsg}\nReason: #{usermsg}"
entry.type = 'url'
entry.val = url
unless 'type' of entry
return msg.send "#{modulename}_#{func_name}: must specify `-i <ip>`, `-d <domain>`, or `-u <url>`"
if 'e' of args
expires = args.e
if extra = expires.match /\+(\d+)([a-zA-Z]+)/
n = extra[1]
unit = extra[2]
unless unit in ['h','hours','d','days','w','weeks','M','months','Q','quarters','y','years']
usermsg = "Invalid unit `#{unit}` in expiration `#{expires}`. Use h or hours, d or days, w or weeks, M or months, Q or quarters, y or years."
return msg.send usermsg
entry.expires = moment().add(n,unit).format()
else if moment(expires).isValid()
entry.expires = moment(expires).format()
else
usermsg = "invalid expiration date: #{expires}"
return msg.send usermsg
# reason
if 'R' of args
entry.reason = args['R']
# request
if 'r' of args
dt_now = moment()
req =
id: "#{who[0..2]}#{dt_now.format('MMDDHHmmss')}"
by: who
type: 'list'
when: dt_now.format()
request: entry
addUpdateRequestEntry req
return msg.send "Queued request for review!"
unless isAuthorized msg
usermsg = "or specify `-r` to request listing"
logmsg = "#{modulename}_#{func_name}: #{who} listing failed: #{usermsg}"
robot.logger.info logmsg
return msg.send usermsg
unless is2fa msg
usermsg = "or specify `-r` to request listing"
logmsg = "#{modulename}_#{func_name}: #{who} listing failed: #{usermsg}"
robot.logger.info logmsg
return msg.send usermsg
result = addListEntry entry
if result isnt true
usermsg = "Failed to add to list #{entry.list}. Error: `#{result}`"
msg.send usermsg
usermsg = ''
usermsg += "#{entry.creator} added `#{entry.val}` (#{entry.type}) to *#{entry.list}*." if 'val' of entry
if 'vals' of entry
usermsg += "#{entry.creator} added *#{entry.vals.length}* #{entry.type} entries to *#{entry.list}*."
usermsg += "```#{entry.vals.join ', '}```"
usermsg += " Expires #{entry.expires}." if expires isnt 'undefined'
usermsg += " Reason: ```#{entry.reason}```" if 'reason' of entry
notifySubscribers entry.list, usermsg, who
usermsg += " Change will be applied in < 5 minutes." unless isTerse who
msg.send usermsg
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: "
logmsg += "added entry to #{entry.list}" if 'val' of entry
logmsg += "added #{entry.vals.length} entries to #{entry.list}" if 'vals' of entry
robot.logger.info logmsg
# be terse after the first utterance
fwdata.terse[who] = moment().add(30,'minutes').format()
addListEntry = (entry) ->
func_name = 'addListEntry'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
vals = false
console.log "#{JSON.stringify entry}"
# validate correct list_name
return "parameter not object" unless isObject entry
return "must specify: list" unless 'list' of entry
return "must specify: creator" unless 'creator' or entry
return "must specify: created" unless 'created' of entry
return "must specify: type" unless 'type' of entry
return "must specify: expires" unless 'expires' of entry
vals = [entry.val] if 'val' of entry
vals = entry.vals if 'vals' of entry
return "must specify: val or vals" if vals is false
return "invalid list #{entry.list}" unless entry.list in list_names
logmsg = "#{modulename}_#{func_name}: #{entry.creator} requested:"
logmsg += " #{entry.list} #{entry.type} #{entry.val}" if 'val' of entry
logmsg += " #{entry.list} #{entry.type} #{entry.vals.length} entries" if 'vals' of entry
logmsg += " expires #{moment(entry.expires).format(timefmt)}"
logmsg += " reason #{entry.reason}" if 'reason' of entry
robotRef.logger.info logmsg
fwdata.lists[entry.list] = [] unless entry.list of fwdata.lists
for val in vals
e =
creator: entry.creator
created: entry.created
expires: entry.expires
list: entry.list
type: entry.type
val: val
e.reason = entry.reason if 'reason' of entry
logmsg = "#{modulename}_#{func_name}: #{e.creator} added"
logmsg += " #{e.list} #{e.type} #{e.val}"
logmsg += " expires #{moment(e.expires).fromNow()}"
logmsg += " reason #{e.reason}" if 'reason' of e
robotRef.logger.info logmsg
fwdata.lists[entry.list].push e
writeData()
return true
listUpdateEntryHelp = (robot, msg) ->
func_name = 'listUpdateEntryHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} list update -L <list> -s <searchstring> -e|-R <value>"
""
"Required options:"
" -L <list> List name; e.g. blacklist"
" -s <string> Search string, must only match one entry; e.g. 127.0.0.1"
" -e <expiration> Expiration, e.g. -12h, +36h, -1d, +30d, +6m, +1y, 2021-10-21, etc"
" -R <reason> Reason for entry, e.g. \"SR 12345\""
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
listUpdateEntry = (robot, msg) ->
func_name = 'listUpdateEntry'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name}: #{who}: #{fullcmd}"
cmd = String msg.match[1]
return listUpdateEntryHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
return listUpdateEntryHelp(robot,msg) if 'h' of args
return listUpdateEntryHelp(robot,msg) if 'help' of args
unless 'L' of args
return msg.send "#{func_name}: must specify `-L <list>`"
list_name = helperListName args['L']
unless list_name
return msg.send "#{func_name}: invalid list: #{args['L']}"
unless 's' of args
return msg.send "#{func_name}: must specify `-s <searchstring>`"
l_search = args.s
if l_search.toLowerCase().indexOf('https://') == 0
usermsg = "#{list_name}ing of https links not supported."
return msg.reply usermsg
if l_search.toLowerCase().indexOf('http://') == 0
l_search = l_search.replace(/http:\/\//i,'')
logmsg = "#{modulename}_#{func_name}: #{who} requested: #{list_name} update #{l_search}"
robot.logger.info logmsg
# check for matches
matches = 0
entry = undefined
for e in fwdata.lists[list_name] when e.val.indexOf(l_search) > -1
#console.log "e.type: [#{e.type}] l_search: [#{l_search}] e.val: [#{e.val}]"
if e.val.indexOf(l_search) > -1
#console.log "l_search: [#{l_search}] MATCHED e.val: [#{e.val}]"
matches++
entry = e
if matches != 1
usermsg = "search matched zero or more than a single entry; " +
"improve search term and try again"
return msg.reply usermsg
#console.log e
if 'e' of args
expires = args['e']
if extra = expires.match /(-|\+|)(\d+)([a-zA-Z])/
direction = extra.shift()
n = extra.shift()
unit = extra.shift()
unless unit in ['h','hours','d','days','w','weeks','M','months','Q','quarters','y','years']
usermsg = "Invalid unit `#{unit}` in expiration `#{expires}`. Use h or hours, d or days, w or weeks, M or months, Q or quarters, y or years."
return msg.send usermsg
if direction == '+'
entry.expires = moment(entry.expires).add(n,unit).format()
else if direction == '-'
entry.expires = moment(entry.expires).subtract(n,unit).format()
else
entry.expires = moment().add(n,unit).format()
else if moment(expires).isValid()
entry.expires = moment(expires).format()
else
usermsg = "invalid expiration date: #{expires}"
return msg.send usermsg
entry.expire_notified = false
logmsg = "#{modulename}_#{func_name}: #{who} requested: " +
"#{list_name} #{entry.type} #{entry.val} new expiration #{moment(entry.expires).format(timefmt)}"
robot.logger.info logmsg
usermsg = "#{who} updated `#{entry.val}` in *#{list_name}*.\n"
usermsg += "Old expiration: ```#{old_expiration}```\n"
usermsg += "New expiration: ```#{entry.expires}```\n"
else if 'R' of args
old_reason = 'none'
old_reason = entry.reason if 'reason' of entry
entry.reason = args['R']
logmsg = "#{modulename}_#{func_name}: #{who} requested: " +
"#{list_name} #{entry.type} #{entry.val} update reason: '#{old_reason}' -> '#{entry.reason}'"
robot.logger.info logmsg
usermsg = "#{who} updated `#{entry.val}` in *#{list_name}*.\n"
usermsg += "Old reason: ```#{old_reason}```\n"
usermsg += "New reason: ```#{entry.reason}```\n"
else
usermsg = "must specify new expiration or reason"
return msg.reply usermsg
writeData()
msg.reply usermsg
notifySubscribers list_name, usermsg, who
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: " +
"updated entry in #{list_name}"
robot.logger.info logmsg
listDeleteEntryHelp = (robot, msg) ->
func_name = 'listDeleteEntryHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} list delete -L <list> -s|-i|-d|-u <value> [options]"
""
"Required options:"
" -L <list> List name; e.g. blacklist"
" -i <ip or cidr> Address or cidr entry, e.g. 127.0.0.1/8"
" -d <domain> Domain entry, e.g. example.com"
" -u <url> URL entry, e.g. example.com/phishing/page123"
""
"Optional:"
" -r Request; required if not authorized and 2fa enabled"
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
listDeleteEntry = (robot, msg) ->
func_name = 'listDeleteEntry'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name} #{who} requested: #{fullcmd}"
cmd = String msg.match[1]
return listDeleteEntryHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
return listDeleteEntryHelp(robot,msg) if 'h' of args
return listDeleteEntryHelp(robot,msg) if 'help' of args
q =
axis: 0
unless 'L' of args
return msg.send "#{func_name}: must specify `-L <list>`"
q.list = helperListName args['L']
unless q.list
return msg.send "#{func_name}: invalid list: #{q.list}"
required = 0
if 's' of args
required++
q.search = args.s
if q.search.toLowerCase().indexOf('https://') == 0
return msg.reply "https links not supported"
if args.s.toLowerCase().indexOf('http://') == 0
q.search = args.s.replace(/http:\/\//i,'')
q.axis += 1
if 'i' of args
required++
addrs = false
if isArray args.i
addrs = args.i
if isString args.i
addrs = [args.i]
addrs = args.i.split(',') if args.i.indexOf(',') > 0
if addrs is false
usermsg = "#{func_name}: invalid ip-address or cidr"
logmsg = "#{modulename}_#{func_name}: #{who} request failed: #{usermsg}"
robot.logger.info logmsg
return msg.send usermsg
q.axis += 2
q.type = 'cidr'
q.addrs = addrs
# display help unless one of the rquired parameter is specified
return listDeleteEntryHelp(robot,msg) unless required > 0
searched = 0
deleted = []
new_listdata = []
listdata = fwdata.lists[q.list]
deleted.push sprintf displayfmt, 'Type', 'Value', 'Expiration', 'Creator', 'Reason'
for e in listdata
axis = 0
#console.log "#{log_date} #{func_name}: #{JSON.stringify e}"
# if not a match, add it to the keepers
if 'type' of q
test = q.type == e.type
#console.log "#{log_date} #{func_name}: TYPE e.type|#{e.type} == q.type|#{q.type} = test|#{test}"
if test
axis++
#console.log "#{log_date} #{func_name}: incremented axis: #{axis}"
if 'search' of q
test = e.val.indexOf(q.search) == -1
#console.log "#{log_date} #{func_name}: SEARCH e.val|#{e.val} q.search|#{q.search} test|#{test}"
if test
axis++
#console.log "#{log_date} #{func_name}: incremented axis: #{axis}"
if 'addrs' of q
test = e.val in q.addrs
#console.log "#{log_date} #{func_name}: ADDRS e.val|#{e.val} q.addrs|#{q.addrs} test|#{test}"
if test
axis++
#console.log "#{log_date} #{func_name}: incremented axis: #{axis}"
if axis < q.axis
#console.log "#{log_date} #{func_name}: axis|#{axis} < q.axis|#{q.axis} = NOT ENOUGH AXIS, keeping entry"
new_listdata.push e
continue
#console.log "#{log_date} #{func_name}: axis|#{axis} >= q.axis|#{q.axis} = ENOUGH AXIS, deleting entry"
expires = moment(e.expires)
#if expires.isBefore() # now
# new_listdata.push e
# continue
# display
reason = ''
if 'reason' of e
unless e.reason.indexOf("\n") > 0
reason = e.reason
else
reason = e.reason.split("\n").shift().substring(0,20)
deleted.push sprintf displayfmt, e.type, e.val,
expires.fromNow(), e.creator, reason
deltaN = listdata.length - new_listdata.length
if deltaN > 0
usermsg = "#{who} removed *#{deltaN}* entries from *#{q.list}*"
usermsg += "```"+ deleted.join("\n") + "```"
fwdata.lists[q.list] = new_listdata
writeData()
else
usermsg = "#{q.list} delete request did not match any records."
msg.send usermsg
logmsg = "#{modulename}_#{func_name} #{who} response: " +
"removed #{deltaN} entries from #{q.list}"
robot.logger.info logmsg
if deltaN > 0
notifySubscribers q.list, usermsg, who
listShow = (robot, msg) ->
func_name = 'listShow'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name} #{who} requested: #{fullcmd}"
list_name = helperListName String(msg.match[1])
unless list_name
return msg.send "#{func_name}: invalid list: #{list_name}"
l_type = false
l_search = false
if msg.match[2]?
l_search = String(msg.match[2])
unless list_name of fwdata.lists and fwdata.lists[list_name].length > 0
return msg.send "No entries on list #{list_name}."
params = {}
params.type = l_type if l_type
params.search = l_search if l_search
r = buildList list_name, params
maxLinesViaChat = 10
if r.lines == 1
msg.send r.single
if r.lines > 1 and r.lines <= maxLinesViaChat
msg.send "*#{list_name}* #{r.lines} entries.\n```#{r.list}```"
if r.lines > maxLinesViaChat
msg.send "*#{list_name}* #{r.lines} entries.\n"+
">List too long to display through chat. Try this:\n"+
">https://s3-us-west-2.amazonaws.com/"+
"#{s3bucket}/#{s3pathPrefix}/#{list_name}-all-list"
logmsg = "#{modulename}_#{func_name}: robot responded to #{msg.envelope.user.name}: " +
"displayed #{list_name} items and expirations"
robot.logger.info logmsg
requestShowHelp = (robot, msg) ->
func_name = 'requestShowHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} request show -a|-i <id>|-n <name>|-t <type>"
""
"Options:"
" -a All requests"
" -i Request id"
" -n Requestor name"
" -t Request type"
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
requestShow = (robot, msg) ->
func_name = 'requestShow'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name}: #{who}: #{fullcmd}"
cmd = String msg.match[1]
return requestShowHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
return requestShowHelp(robot,msg) if 'h' of args
return requestShowHelp(robot,msg) if 'help' of args
if 'i' of args
unless args.i of fwdata.requests
msg.send "#{func_name}: request does not exist: id=#{args.i}"
usermsg = markupRequest fwdata.requests[args.i]
msg.send usermsg
logmsg = "#{modulename}_#{func_name}: responded to #{who}: " +
"displaying id #{args.i}"
return robot.logger.info logmsg
out = ''
requestCount = 0
for key of fwdata.requests
req = fwdata.requests[key]
continue if 'u' of args and req.by isnt args.u
continue if 't' of args and req.type isnt args.t
requestCount += 1
out += "type=#{req.type} id=#{req.id} by=#{req.by} when=#{req.when}\n"
if requestCount > 0
msg.send "Requests:\n```#{out}```"
else
msg.send "No requests in queue; nice work!"
logmsg = "#{modulename}_#{func_name}: responded to #{who}: " +
"displayed #{requestCount} requests"
robot.logger.info logmsg
requestApproveHelp = (robot, msg) ->
func_name = 'requestApproveHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} request approve -i <id> -m \"<message>\""
""
"Required options:"
" -i Request id"
" -m Approval message"
""
"Note: immediate upon approval the request will be applied!"
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
requestApprove = (robot, msg) ->
func_name = 'requestApprove'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name}: #{who}: #{fullcmd}"
cmd = String msg.match[1]
return requestDeclineHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
return requestDeclineHelp(robot,msg) if 'h' of args
return requestDeclineHelp(robot,msg) if 'help' of args
console.log "#{log_date} #{func_name}: cmd: #{cmd} out: #{JSON.stringify args}"
return unless is2fa msg
unless 'i' of args
return msg.send "#{func_name}: missing required parameter: `-i <id>`"
id = args.i
unless 'm' of args
return msg.send "#{func_name}: missing required parameter: `-m \"<msg>\"`"
message = args.m
unless id of fwdata.requests
return msg.send "#{func_name}: request not found: id=#{id}"
req = fwdata.requests[id]
result = false
if req.type is 'list'
result = addListEntry(req.request)
else
result = "unable to process request type: #{req.type}"
unless result is true
return msg.send "Failed to apply #{req.type}. Error: ```#{result}```"
res =
by: who
action: 'approved'
comment: args.m
deleteRequestEntry req, res
#msg.send "Request #{id} approved with message: ```#{message}```"
logmsg = "#{modulename}_#{func_name}: responded to #{who}: " +
"request #{id} approved with message: #{message}"
robot.logger.info logmsg
requestDeclineHelp = (robot, msg) ->
func_name = 'requestDeclineHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} request decline -i <id> -m <message>"
""
"Required options:"
" -i Request id"
" -m Decline message"
""
"Note: immediate upon decline the request is removed and notification sent."
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
requestDecline = (robot, msg) ->
func_name = 'requestDecline'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name}: #{who}: #{fullcmd}"
cmd = String msg.match[1]
return requestDeclineHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
return requestDeclineHelp(robot,msg) if 'h' of args
return requestDeclineHelp(robot,msg) if 'help' of args
console.log "#{log_date} #{func_name}: cmd: #{cmd} out: #{JSON.stringify args}"
return unless is2fa msg
unless 'i' of args
return msg.send "#{func_name}: missing required parameter: `-i <id>`"
id = args.i
unless 'm' of args
return msg.send "#{func_name}: missing required parameter: `-m \"<msg>\"`"
message = args.m
unless id of fwdata.requests
return msg.send "#{func_name}: request not found: id=#{id}"
req = fwdata.requests[id]
res =
by: who
action: 'declined'
comment: args.m
deleteRequestEntry req, res
#msg.send "Request #{id} declined with message: ```#{message}```"
logmsg = "#{modulename}_#{func_name}: responded to #{who}: " +
"request #{id} declined with message: #{message}"
robot.logger.info logmsg
buildList = (list_name, params = {}) ->
func_name = 'buildList'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
lines = 0 # entries
out_terse = '' # string
delete params.type if 'type' of params and params.type is 'all'
out_list = sprintf "#{displayfmt}\n", 'Type', 'Value', 'Expiration', 'Creator', 'Reason'
for e in fwdata.lists[list_name]
bool_expires = false
dt_expires = moment(e.expires)
if 'expires' of params
dt = moment() unless 'when' of params
dt = moment(params.when) if 'when' of params
bool_expires = dt_expires.isBefore(dt)
bool_expires = dt_expires.isBefore(dt) if params.expires == 'before' and dt_expires.isBefore(dt)
bool_expires = dt_expires.isAfter(dt) if params.expires == 'after' and dt_expires.isAfter(dt)
#console.log "#{log_date} #{func_name} #{dt_expires.fromNow()} / #{dt_expires.format()} #{params.expires} #{dt.format()} #{bool_expires}"
continue unless bool_expires
else
continue if dt_expires.isBefore() # skip expired
continue if 'type' of params and params.type != e.type
continue if 'search' of params and e.val.indexOf(params.search) == -1
if 'expire_notify' of params # if pre-expiration notify, only do it once
continue if 'expire_notified' of e and e.expire_notified
e.expire_notified = true
reason = ''
reason = e.reason if 'reason' of e
if reason.indexOf("\n") > 0
reason = e.reason.split("\n").shift().substring(0,20)
vals = [e.val] if 'val' of e
vals = e.vals if 'vals' of e
for val in vals
lines++
out_terse += "#{val}\n"
out_list += sprintf "#{displayfmt}\n", e.type, val, dt_expires.fromNow(), e.creator, reason
out_single = "#{e.creator} added `#{val}` (#{e.type}) to list"
out_single += " #{list_name}. Expires #{moment(e.expires).fromNow()}."
out_single += " Reason: ```#{e.reason}```" if 'reason' of e
output =
single: out_single
terse: out_terse
list: out_list
lines: lines
return output
listSubscribe = (robot, msg) ->
func_name = 'listSubscribe'
user = msg.envelope.user
list_name = msg.match[1]
list_name = 'whitelist' if list_name.indexOf('w') == 0
list_name = 'blacklist' if list_name.indexOf('b') == 0
list_name = 'autoban' if list_name.indexOf('a') == 0
who = user.name
who = msg.match[2] if msg.match[2]
logmsg = "#{modulename}_#{func_name}: #{user.name} requested: subscribe #{list_name} #{who}"
robot.logger.info logmsg
fwdata.notify[list_name] = [] unless list_name of fwdata.notify
fwdata.notify[list_name].push who unless who in fwdata.notify[list_name]
usermsg = "Added #{who} to list #{list_name}."
msg.send usermsg
logmsg = "#{modulename}_#{func_name}: robot responded to #{user.name}: " +
"added #{who} to list #{list_name}"
robot.logger.info logmsg
writeData()
listUnsubscribe = (robot, msg) ->
func_name = 'listUnsubscribe'
user = msg.envelope.user
list_name = msg.match[1]
list_name = 'whitelist' if list_name.indexOf('w') == 0
list_name = 'blacklist' if list_name.indexOf('b') == 0
list_name = 'autoban' if list_name.indexOf('a') == 0
who = msg.envelope.user.name
who = msg.match[2] if msg.match[2]
logmsg = "#{modulename}_#{func_name}: #{user.name} requested: unsubscribe #{list_name} #{who}"
robot.logger.info logmsg
unless list_name of fwdata.notify
usermsg = "No such list #{list_name}."
return msg.reply usermsg
n = fwdata.notify[list_name].indexOf(who)
unless n > -1
usermsg = "`#{who}` not a member of list #{list_name}."
return msg.reply usermsg
fwdata.notify[list_name].splice(n, 1)
usermsg = "Removed #{who} from list #{list_name}."
msg.send usermsg
logmsg = "#{modulename}_#{func_name}: robot responded to #{user.name}: " +
"removed #{who} from list #{list_name}"
robot.logger.info logmsg
writeData()
listShowSubscribers = (robot, msg) ->
func_name = 'listShowSubscribers'
who = msg.envelope.user.name
list_name = ''
list_name = msg.match[1] if msg.match[1]
list_name = 'whitelist' if list_name.indexOf('w') == 0
list_name = 'blacklist' if list_name.indexOf('b') == 0
list_name = 'autoban' if list_name.indexOf('a') == 0
logmsg = "#{modulename}_#{func_name}: #{who} requested subscribers"
logmsg += " for list #{list_name}" if list_name
robot.logger.info logmsg
usermsg = ""
for list of fwdata.notify
continue if list_name and list != list_name
continue unless isArray(fwdata.notify[list]) and fwdata.notify[list].length > 0
usermsg += "Subscribers for #{list}: `"+ fwdata.notify[list].join('`, `') + "`\n\n"
if usermsg
msg.reply usermsg
logmsg = "#{modulename}_#{func_name}: displayed subscribers to #{who}"
robot.logger.info logmsg
httpGetHelp = (robot, req, res) ->
func_name = 'httpGetHelp'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
clientip = req.connection.remoteAddress || req.socket.remoteAddress ||
req.connection.socket.remoteAddress
logmsg = "#{modulename}_#{func_name}: web request from #{clientip}"
robot.logger.info logmsg
arr = ["<html>\n<body>\n<pre>\n"]
for list in list_names
for type in list_types
arr.push "<a href='#{list}/#{type}'>#{list}/#{type}</a>\n"
arr.push "</pre>\n</body>\n</html>\n"
res.setHeader 'content-type', 'text/html'
res.end arr.join "\n"
logmsg = "#{modulename}_#{func_name}: robot responded to web request"
robot.logger.info logmsg
httpGetList = (robot, req, res, list_name, list_type) ->
func_name = 'httpGetList'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
clientip = req.connection.remoteAddress || req.socket.remoteAddress ||
req.connection.socket.remoteAddress
rememberCheckin clientip, list_name, list_type
logmsg = "#{modulename}_#{func_name}: web request from #{clientip}: get #{list_type} #{list_name}"
robot.logger.info logmsg
params =
type: list_type
r = buildList list_name, params
content = '# nothing here yet! #'
content = r.terse if r.lines > 0
res.setHeader 'content-type', 'text/plain'
res.end content
logmsg = "#{modulename}_#{func_name}: robot responded to web request: sent #{list_type} #{list_name}"
robot.logger.info logmsg
listShowFirewallCheckins = (robot, msg) ->
who = msg.envelope.user.name
logmsg = "#{modulename}_#{func_name}: #{who} requested: checkins"
robot.logger.info logmsg
arr = []
for obj in fwdata.firewalls
obj.checkin = moment(obj.checkin) if typeof(obj.checkin) is 'string'
arr.push sprintf '%-16s %-10s %-10s %-15s', obj.name, obj.list, obj.type,
obj.checkin.fromNow()
usermsg = "Expected firewall check times: ```"+ arr.join("\n") + "```"
msg.send usermsg
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: checkins"
robot.logger.info logmsg
rememberCheckin = (clientip,list_name,l_type) ->
return unless fwname = fwnames[clientip] # skip non-firewalls
for obj in fwdata.firewalls
if obj.ip is clientip and obj.type is l_type and obj.list is list_name
obj.checkin = moment().add(5,'minutes')
writeData()
return
# otherwise create new object
obj =
ip: clientip
name: fwname
list: list_name
type: l_type
checkin: moment().add(5,'minutes')
fwdata.firewalls.push obj
if fwdata.firewalls.length > 1
fwdata.firewalls = fwdata.firewalls.sort (a,b) ->
sortBy('name',a,b) or sortBy('list',a,b) or sortBy('type',a,b)
writeData()
moduleHelp = (robot, msg) ->
func_name = 'moduleHelp'
who = msg.envelope.user.name
admin = isAdmin msg
arr = [
"#{modulename} list show <list> [searchterm]"
"#{modulename} list add -h"
"#{modulename} list del -h"
"#{modulename} list update -h"
"#{modulename} list subscribe <list> [username] - subscribe to change notifications"
"#{modulename} list unsubscribe <list> [username]"
"#{modulename} list subscribers [list]"
"#{modulename} rule <options>"
]
arr.push "#{modulename} request show [options]" if admin
arr.push "#{modulename} request approve <options>" if admin
out = arr.join "\n"
msg.send "```#{out}```"
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: " +
"displayed #{modulename} help"
robot.logger.info logmsg
listHelp = (robot, msg) ->
func_name = 'listHelp'
who = msg.envelope.user.name
admin = isAdmin msg
arr = [
"#{modulename} list show <list> [searchterm]"
"#{modulename} list add -h"
"#{modulename} list del -h"
"#{modulename} list update -h"
"#{modulename} list subscribe <list> [username] - subscribe to change notifications"
"#{modulename} list unsubscribe <list> [username]"
"#{modulename} list subscribers [list]"
]
out = arr.join "\n"
msg.send "```#{out}```"
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: " +
"displayed #{modulename} help"
robot.logger.info logmsg
writeData = ->
func_name = 'writeData'
fs.writeFileSync data_file, JSON.stringify(fwdata), 'utf-8'
logmsg = "#{modulename}_#{func_name}: wrote #{data_file}"
robotRef.logger.info logmsg
module.exports = (robot) ->
robotRef = robot
if process.env.HUBOT_GRAYLOG_URL && process.env.HUBOT_GRAYLOG_TOKEN
glApi = robot.http process.env.HUBOT_GRAYLOG_URL
glApi.auth process.env.HUBOT_GRAYLOG_TOKEN, 'token'
glApi.path 'api/search/universal/relative'
glApi.header 'Accept', 'application/json'
else
console.warn "#{modulename}: HUBOT_GRAYLOG_URL and HUBOT_GRAYLOG_TOKEN" +
" environment variables not set."
setTimeout oneMinuteWorker, 5 * 1000
setTimeout fiveMinuteWorker, 15 * 1000
try
fwdata = JSON.parse fs.readFileSync data_file, 'utf-8'
robot.logger.info "#{modulename}: read #{data_file}" if robot.logger
fwdata = {} unless isObject fwdata
fwdata['notify'] = {} unless isObject fwdata['notify']
fwdata['lists'] = {} unless isObject fwdata['lists']
fwdata['firewalls'] = [] unless isArray fwdata['firewalls']
fwdata['terse'] = {} unless isObject fwdata['terse']
fwdata['attackers'] = {} unless isObject fwdata['attackers']
fwdata['requests'] = {} unless isObject fwdata['requests']
catch error
unless error.code is 'ENOENT'
console.log("#{modulename}: unable to read #{data_file}: ", error)
robot.router.get "/#{robot.name}/#{modulename}", (req, res) ->
return httpGetHelp robot, req, res
robot.router.get "/#{robot.name}/#{modulename}/blacklist/url", (req, res) ->
return httpGetList robot, req, res, 'blacklist', 'url'
robot.router.get "/#{robot.name}/#{modulename}/blacklist/cidr", (req, res) ->
return httpGetList robot, req, res, 'blacklist', 'cidr'
robot.router.get "/#{robot.name}/#{modulename}/blacklist/domain", (req, res) ->
return httpGetList robot, req, res, 'blacklist', 'domain'
robot.router.get "/#{robot.name}/#{modulename}/whitelist/url", (req, res) ->
return httpGetList robot, req, res, 'whitelist', 'url'
robot.router.get "/#{robot.name}/#{modulename}/whitelist/cidr", (req, res) ->
return httpGetList robot, req, res, 'whitelist', 'cidr'
robot.router.get "/#{robot.name}/#{modulename}/whitelist/domain", (req, res) ->
return httpGetList robot, req, res, 'whitelist', 'domain'
robot.router.get "/#{robot.name}/#{modulename}/autoban/cidr", (req, res) ->
return httpGetList robot, req, res, 'autoban', 'cidr'
robot.respond /(?:firewall|fw)(?: help| h|)$/, (msg) ->
return moduleHelp robot, msg
robot.respond /(?:firewall|fw) list(?: help| h|)$/, (msg) ->
return listHelp robot, msg
robot.respond /(?:firewall|fw) list show admins$/i, (msg) ->
return listShowAdmins robot, msg
robot.respond /(?:firewall|fw) list show (?:checkins|firewalls|fw)$/i, (msg) ->
return listShowFirewallCheckins robot, msg
robot.respond /(?:firewall|fw) list subscribers(?: (.+)|)$/i, (msg) ->
return listShowSubscribers robot, msg
robot.respond /(?:firewall|fw) list show ([^ ]+)(?: (.+)|)$/i, (msg) ->
return listShow robot, msg
robot.respond /(?:firewall|fw) list (?:add|a)(?: (.+)|)$/i, (msg) ->
return listAddEntry robot, msg
robot.respond /(?:firewall|fw) list (?:delete|del|d)(?: (.+)|)$/i, (msg) ->
return unless isAuthorized msg
return unless is2fa msg
return listDeleteEntry robot, msg
robot.respond /(?:firewall|fw) list (?:update|upd|up|u)(?: (.+)|)$/i, (msg) ->
return unless isAuthorized msg
return unless is2fa msg
return listUpdateEntry robot, msg
robot.respond /(?:firewall|fw) list (?:subscribe|sub) ([^ ]+)(?: ([^ ]+)|)$/i, (msg) ->
return listSubscribe robot, msg
robot.respond /(?:firewall|fw) list (?:unsubscribe|unsub) ([^ ]+)(?: ([^ ]+)|)$/i, (msg) ->
return listUnsubscribe robot, msg
robot.respond /(?:firewall|fw) (?:rule|r)(?: (.+)|)$/i, (msg) ->
return unless isAuthorized msg
return ruleAddEntry robot, msg
robot.respond /(?:firewall|fw) (?:request|req) show(?: (.+)|)$/i, (msg) ->
return unless isAdmin msg
return requestShow robot, msg
robot.respond /(?:firewall|fw) (?:request|req) (?:approve|app|a)(?: (.+)|)$/i, (msg) ->
return unless isAdmin msg
return requestApprove robot, msg
robot.respond /(?:firewall|fw) (?:request|req) (?:decline|dec|d)(?: (.+)|)$/i, (msg) ->
return unless isAdmin msg
return requestDecline robot, msg
| 135289 | # Description:
# Manage black/white lists for UA PA FW.
#
# Dependencies:
# moment
#
# Configuration:
# xxxxxxxxxxx [required] - API KEY
# GRAYLOG_URL (e.g. https://graylog.example.com)
# GRAYLOG_API_TOKEN (e.g. <KEY>)
# GRAYLOG_SEPARATOR (e.g. ','. Default: "\n")
#
#
# Commands:
# hubot firewall - firewall commands
#
# Notes:
# requires hubot-auth be present
#
# Author:
# gfjohnson
fs = require 'fs'
moment = require 'moment'
CIDRMatcher = require 'cidr-matcher'
sprintf = require("sprintf-js").sprintf
AWS = require 'aws-sdk'
s3 = new AWS.S3()
request = require 'request'
parse = require 'yargs-parser'
modulename = 'fw'
data_file = modulename + ".json"
safety_fail_note = 'If this is time critical ask a human; otherwise please open a ticket.'
displayfmt = '%-4s %-50s %-15s %-10s %s'
timefmt = 'YYYY-MM-DD HH:mm:ss ZZ'
msOneMinute = 60 * 1000
msFiveMinutes = 300 * 1000
glApi = null;
s3bucket = 'ua-oit-security-pub'
s3pathPrefix = 'stats'
defaultNotifyAdmin = 'all' # normally null, for 'all'
defaultNotifySubscribers = 'all' # normally null, for 'all'
# enable or disable auto-banning
attackAutoBanEnabled = true
attackAutoBanNotifySubscribers = true
# auto-ban after X occurances
attackBanAfterOccurances = 5
# if no attacks detected in this duration, expire counter
attackExpirationHours = 6
# escalating ban durations for 2nd, 3rd, etc duration
attackBanHours = [
1
24
24 * 7
24 * 30
]
UA_Network = new CIDRMatcher [
'192.168.3.11/16'
'172.16.58.3/18'
'10.0.0.0/8'
'172.16.0.0/12'
'192.168.0.0/16'
]
list_names = [
'blacklist'
'whitelist'
'autoban'
]
list_types = [
'domain'
'cidr'
'url'
]
preventDomainBlacklist = [
[ 'alaska.edu', /alaska\.edu$/ ]
[ 'uaf.edu', /uaf\.edu$/ ]
]
preventUrlBlacklist = [
[ 'alaska.edu', /[^\/]+alaska.edu\// ]
[ 'uaf.edu', /[^\/]+uaf.edu\// ]
]
robotRef = false
fwdata = false
fwnames =
'10.9.0.252': 'Fairbanks-1'
'10.9.0.253': 'Fairbanks-2'
'10.9.128.10': 'Anchorage-1'
'10.9.128.11': 'Anchorage-2'
'10.9.192.10': 'Juneau-1'
'10.9.192.11': 'Juneau-2'
if process.env.HUBOT_AUTH_ADMIN
hubotAuthAdmin = process.env.HUBOT_AUTH_ADMIN.split ','
else
console.warn "#{modulename}: HUBOT_AUTH_ADMIN environment variable not set."
# borrowed from
# http://stackoverflow.com/questions/9796764/how-do-i-sort-an-array-with-coffeescript
sortBy = (key, a, b, r) ->
r = if r then 1 else -1
return -1*r if a[key] > b[key]
return +1*r if a[key] < b[key]
return 0
isArray = Array.isArray or (obj) -> toString.call(obj) == '[object Array]'
isString = (obj) -> toString.call(obj) == '[object String]'
isObject = (obj) -> toString.call(obj) == '[object Object]'
isAdmin = (msg, reply = true) ->
console.error 'bad robotRef' unless robotRef
who = msg.envelope.user.name
return true if who in hubotAuthAdmin
msg.reply "This requires administrator privilege." if reply
return false
isAuthorized = (msg, reply = true) ->
console.error 'bad robotRef' unless robotRef
u = msg.envelope.user
return true if robotRef.auth.hasRole(u,'fw')
msg.reply "Not authorized. Missing fw role." if reply
return false
is2fa = (msg, reply = true) ->
console.error 'bad robotRef' unless robotRef
u = msg.envelope.user
return true if robotRef.auth.is2fa(u)
msg.reply "2fa required. Use `auth 2fa` to validate identity." if reply
return false
isTerse = (who) ->
fwdata['terse'] = {} unless 'terse' of fwdata
return true if who of fwdata.terse && moment(fwdata.terse[who]).isAfter()
return false
isBanned = (ban_expires) ->
expires = moment(ban_expires)
return false unless expires.isValid()
return true if expires.isAfter()
return false
panConfigDevicesVsysRulebaseSecurityRule = (params, callback) ->
func_name = 'panConfigDevicesVsysRulebaseSecurityRule'
params = { name: params } if isString params
return false unless isObject params
return false unless 'name' of params
params.path = "/rulebase/security/rules/entry[@name='#{params.name}']"
return panConfigDevicesVsys params, callback
panConfigDeviceVsysAddress = (params, callback) ->
func_name = 'panConfigDeviceVsysAddress'
params = { name: params } if isString params
return false unless isObject params
for key in ['name']
return "#{func_name}: missing required param: #{key}" unless key of param
params.path = "/address/entry[@name='#{params.name}']"
return panConfigDevicesVsys params, callback
panConfigDevicesVsys = (params, callback) ->
func_name = 'panConfigDevicesVsys'
params = { path: params } if isString params
return false unless isObject params
for key in ['path']
return "#{func_name}: missing required param: #{key}" unless key of param
params.vsys = 'vsys1' unless 'vsys' of params
params.path = "/vsys/entry[@name='#{params.vsys}']/#{params.path}"
return panConfigDevices params, callback
panConfigDevices = (params, callback) ->
func_name = 'panConfigDevices'
params = { path: params } if isString params
return false unless isObject params
for key in ['path']
return "#{func_name}: missing required param: #{key}" unless key of param
params.device = 'localhost.localdomain' unless 'device' of params
params.path = "/devices/entry[@name='#{params<EMAIL>.device}']#{params.path}"
return panGetConfig params, callback
panConfig = (params, callback) ->
func_name = 'panConfig'
return false unless isObject params
for key in ['fqdn','path','key']
return "#{func_name}: missing required param: #{key}" unless key of param
params.action = 'get' unless 'action' of params
unless params.action in ['get']
return "#{func_name}: invalid action param: #{params.action}"
q =
type: 'config'
action: params.action
xpath: "/config#{params.path}"
key: params.key
options =
url: "https://#{params.fqdn}/api/"
qs: q
strictSSL: false
accept: 'text/xml'
request.get options, (err, res, body) ->
return callback(null, err) if err
# XXX: convert xml2json
return callback(body)
return true
xmlVal = (name,val) ->
return '' unless name of obj
return "<#{name}>#{val}</#{name}>"
panOpTestSecurityPolicyMatch = (params, callback) ->
func_name = 'panOpTestSecurityPolicyMatch'
# cmd: <test><security-policy-match><from></from></security-policy-match></test>
#params = { path: params } if isString params
cmd = ''
return false unless isObject params
required = [
'destination'
'destination-port'
'protocol'
'source'
]
for key in required
return "#{func_name}: missing required param: #{key}" unless key of params
cmd += xmlVal key, params[key]
optional = [
'application'
'category'
'from'
'show-all'
'source-user'
'to'
]
for key in optional
if key of params
cmd += xmlVal key, params[key]
params.cmd = "<test><security-policy-match>#{cmd}</security-policy-match></test>"
return panOp params, callback
panCommit = (params, callback) ->
# cmd: <commit></commit>
#params = { path: params } if isString params
cmd = ''
return false unless isObject params
params.type = 'commit'
optional = [
'description'
]
for name in optional
if name of params
cmd += xmlVal name, params[name]
params.cmd = xmlVal 'commit', cmd
return panOp params, callback
panOp = (params, callback) ->
func_name = 'panOp'
return false unless isObject params
for key in ['<KEY>dn','cmd']
return "#{func_name}: missing required param: #{key}" unless key of param
param.type = 'op' unless 'type' of params
unless params.type in ['op','commit']
return "#{func_name}: invalid param type: #{params.type}"
q =
type: 'op'
cmd: params.cmd
options =
url: "https://#{params.fqdn}/api/"
qs: q
strictSSL: false
accept: 'text/xml'
request.get options, (err, res, body) ->
return callback(null, err) if err
# XXX: convert xml2json
return callback(body)
return true
oneMinuteWorker = ->
queryAndProcessAttacks()
setTimeout oneMinuteWorker, msOneMinute
fiveMinuteWorker = ->
for list in ['autoban','blacklist','whitelist']
uploadReport list, 'all', 'list'
for type in ['url','cidr','domain']
continue if list is 'autoban' and type isnt 'cidr'
uploadReport list, type, 'terse'
expireAttackers()
preExpireNotify 'blacklist'
preExpireNotify 'whitelist'
expireEntriesFromList 'blacklist'
expireEntriesFromList 'whitelist'
expireEntriesFromList 'autoban'
setTimeout fiveMinuteWorker, msFiveMinutes
queryAndProcessCommits = ->
func_name = 'queryAndProcessCommits'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
console.log "#{log_date} #{func_name} --"
return if glApi is null
q =
query: 'logfile:SYSTEM\/general',
fields: 'message,source',
range: 60,
decorate: 'true'
glApi.query q
#console.log 'exec glApi.get() with glApi.options: ', JSON.stringify glApi.options, null, 2
glApi.get() (err, res, body) ->
unless res.statusCode is 200
return console.warn 'Error requesting Graylog url statusCode=', res.statusCode, 'err=', err, 'options=', glApi.options
glresponse = JSON.parse body
#console.log 'glApi returns body:', JSON.stringify jsonbody, null, 2
events = glresponse.messages.map (m) => m.message
for event in events
processCommit event
queryAndProcessAttacks = ->
func_name = 'queryAndProcessAttacks'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
console.log "#{log_date} #{func_name} --"
return if glApi is null
q =
query: 'logfile:THREAT\\/vulnerability',
fields: 'message,source,addrsrc,addrdst,action',
range: 60,
decorate: 'true'
glApi.query q
#console.log 'exec glApi.get() with glApi.options: ', JSON.stringify glApi.options, null, 2
glApi.get() (err, res, body) ->
unless res.statusCode is 200
return console.warn 'Error requesting Graylog url statusCode=', res.statusCode, 'err=', err, 'options=', glApi.options
glresponse = JSON.parse body
#console.log 'glApi returns body:', JSON.stringify jsonbody, null, 2
events = glresponse.messages.map (m) => m.message
for event in events
# skip if already on the attack list
#continue if fwdata.attackers[event.addrsrc] and fwdata.attackers[event.addrsrc].banned
# skip unless action
continue unless event.action in ['block-ip','drop','reset-both']
# skip if source is internal
continue if UA_Network.contains event.addrsrc
addAttackSource event
addAttackSource = (event) ->
func_name = 'addAttackSource'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
src = event.addrsrc
ldt = moment(event.timestamp).format('HH:mm:ss')
unless src of fwdata.attackers
console.log "#{log_date} #{func_name}: new source #{event.addrsrc}"
fwdata.attackers[src] =
attacks: 0
attacker: src
victims: []
created: moment().format()
banexpires: 0
msgs: []
fwdata.attackers[src].attacks++
fwdata.attackers[src].last = moment().format()
fwdata.attackers[src].msgs.push "#{ldt} / #{event.source} / #{event.message}"
if fwdata.attackers[src].msgs.length > attackBanAfterOccurances
fwdata.attackers[src].msgs.shift()
if event.addrdst not in fwdata.attackers[src].victims
fwdata.attackers[src].victims.push event.addrdst
# ban if attack count exceeds attackBanAfterOccurances value
if fwdata.attackers[src].attacks >= attackBanAfterOccurances
# do not ban if already banned
banAttackSource fwdata.attackers[src] unless isBanned fwdata.attackers[src].banexpires
banAttackSource = (attackSource) ->
func_name = 'banAttackSource'
#console.log 'banAttackSource --'
src = attackSource.attacker
msgs = attackSource.msgs.join "\n"
status = 'would have auto-banned'
status = 'auto-banning' if attackAutoBanEnabled
attackSource.bancount = 0 unless attackSource['bancount']
bc = fwdata.attackers[src].bancount
if attackSource.bancount >= (attackBanHours.length - 1)
bc = attackBanHours.length - 1
fwdata.attackers[src].bancount++
banHours = attackBanHours[bc]
attackSource.banexpires = moment().add(banHours,'hours').format()
usermsg = "#{modulename}_#{func_name}: #{status} `#{src}` for #{banHours} hours due to" +
" #{attackBanAfterOccurances} events since" +
" #{moment(attackSource.created).format('YYYY-MM-DD HH:mm:ss')}"
usermsg += " and #{bc} previous bans" if bc > 0
usermsg += ": ```#{msgs}```"
list_name = 'autoban'
notifySubscribers list_name, usermsg
# only notify unless enabled
return unless attackAutoBanEnabled
entry =
creator: "robot"
list: list_name
created: moment().format()
expires: attackSource.banexpires
type: 'cidr'
val: attackSource.attacker
reason: "#{attackSource.attacks} attacks\n#{msgs}"
result = addListEntry entry
if result isnt true
usermsg = "Failed to add `#{entry.val}` (#{entry.type}) to list" +
" #{list_name}. Error: `#{result}`"
notifySubscribers list_name, usermsg
#notifymsg = "#{entry.creator} added `#{entry.val}` (#{entry.type}) to list"
#notifymsg += " #{list_name}. Expires `#{entry.expires}`."
#notifySubscribers list_name, notifymsg
uploadReport = (list_name, list_type, list_style) ->
func_name = 'uploadReport'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
params =
type: list_type
r = buildList list_name, params
s3upload "#{list_name}-#{list_type}-#{list_style}", r[list_style]
s3upload = (filename,body,type='plain') ->
func_name = 's3upload'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
params =
Bucket: s3bucket
Key: <KEY>
ContentType: "text/#{type}"
Body: body
s3.putObject params, (err, data) ->
if err
return console.error "#{log_date} #{func_name}: #{err}"
console.log "#{log_date} #{func_name}: #{params.ContentType} #{params.Bucket}:#{params.Key} success"
expireAttackers = ->
func_name = 'expireAttackers'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
console.log "#{log_date} #{func_name} --"
for src of fwdata.attackers
attackSource = fwdata.attackers[src]
# skip if last seen in x duration
expire = moment(attackSource.last).isBefore( moment().subtract(attackExpirationHours,'hour') )
continue unless expire
# skip if currently banned
continue if attackSource['banexpires'] and isBanned attackSource.banexpires
# flush it
console.log "#{moment().format('YYYY-MM-DD HH:mm:ss')} #{func_name}: #{src} "+
"last seen: #{moment(fwdata.attackers[src].last).fromNow()}"
delete fwdata.attackers[src]
preExpireNotify = (list_name) ->
func_name = 'preExpireNotify'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
dt_hour_from_now = moment().add(1,'hours')
params =
expires: 'before'
when: dt_hour_from_now
expire_notify: true
r = buildList list_name, params
return unless r.lines > 0
expiring = r.list
usermsg = "fw: #{list_name} entries will expire soon: " +
"```#{expiring}```"
notifySubscribers list_name, usermsg
expireEntriesFromList = (list_name) ->
func_name = 'expireEntriesFromList'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
unless list_name of fwdata.lists
return console.error "#{log_date} #{func_name}: #{list_name} does not exist"
dt_now = moment()
params =
expires: 'before'
when: dt_now
r = buildList list_name, params
return unless r.lines > 0
deleted = r.list
removequeue = []
list = fwdata.lists[list_name]
for entry in list when moment(entry.expires).isBefore(dt_now)
removequeue.push entry
while removequeue.length > 0
entry = removequeue.shift()
list.splice(list.indexOf(entry), 1)
usermsg = "fw: #{list_name} entries expired and have been removed: " +
"```#{deleted}```"
notifySubscribers list_name, usermsg
writeData()
notifySubscribers = (list_name, usermsg, current_un = false, who = defaultNotifySubscribers) ->
func_name = 'notifySubscribers'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
return console.error "#{log_date} #{func_name}: bad robotRef" unless robotRef
return console.error "#{log_date} #{func_name}: bad list: #{list_name}" unless list_name in list_names
return console.error "#{log_date} #{func_name}: list not created: #{list_name}" unless list_name of fwdata.notify
return console.error "#{log_date} #{func_name}: list empty: #{list_name}" unless isArray fwdata.notify[list_name]
un_list = who if isArray who
un_list = [who] if isString who
un_list = fwdata.notify[list_name] if who == 'all' or who is null
return notifyUsers usermsg, current_un, un_list
notifyUsers = (usermsg, current_un = false, who = null) ->
func_name = 'notifyUsers'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
return console.error "#{log_date} #{func_name}: bad robotRef" unless robotRef
return console.error "#{log_date} #{func_name}: must specify who" if who is null
un_list = who if isArray who
un_list = [who] if isString who
for un in un_list
console.log "#{log_date} #{func_name} #{un}: #{usermsg}"
robotRef.send { room: un }, usermsg unless current_un && un == current_un
return un_list
notifyAdmins = (usermsg, current_un = false, who = defaultNotifyAdmin) ->
func_name = 'notifyAdmins'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
return console.error "#{log_date} #{func_name}: bad robotRef" unless robotRef
un_list = who if isArray who
un_list = [who] if isString who
un_list = hubotAuthAdmin if who == 'all' or who is null
for un in un_list when un.indexOf('U') != 0
console.log "#{log_date} #{func_name} #{un}: #{usermsg}"
robotRef.send { room: un }, usermsg unless current_un && un == current_un
return un_list
listShowAdmins = (robot, msg) ->
func_name = 'listShowAdmins'
fullcmd = String msg.match.shift()
who = msg.envelope.user.name
logmsg = "#{modulename}_#{func_name}: #{who} requested: #{fullcmd}"
robot.logger.info logmsg
msg.reply "#{modulename} admins: #{hubotAuthAdmin.join(', ')}"
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: " +
"provided list of admins"
robot.logger.info logmsg
ruleAddEntryHelp = (robot, msg) ->
func_name = 'ruleAddEntryHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} rule <options>"
""
"Required options:"
" -N, --name Rule name"
" -f, --from From zone, eg. Untrust"
" -t, --to To zone, e.g. DMZ"
" -s, --src Source address"
" -d, --dst Dest address"
" -S, --svc Service, e.g. service-http"
" -a, --app Application, e.g. web-browse"
" -e, --erd URL to Firewall Access Diagram"
""
"Note: if rule name already exists, this will replace it!"
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
ruleAddEntry = (robot, msg) ->
func_name = 'ruleAddEntry'
fullcmd = String msg.match.shift()
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name}: #{who}: #{fullcmd}"
cmd = String msg.match.shift()
return ruleAddEntryHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
console.log "cmd: #{cmd} out: #{JSON.stringify args}"
return ruleAddEntryHelp(robot,msg) if 'h' of args
return ruleAddEntryHelp(robot,msg) if 'help' of args
return unless is2fa msg
keys =
N: '<KEY>'
f: 'from'
t: 'to'
s: 'src'
d: 'dst'
S: 'svc'
a: 'app'
e: 'erd'
for key of keys
if key of args
args[ keys[key] ] = args[key]
delete args[key]
args.requestor = who
result = processRule args, who
unless result is true
errmsg = "Unable to submit request"
errmsg += ":```#{result}```" unless result is false
return msg.send errmsg
msg.send "Submitted rule for review!"
normType = (val) ->
return val.join ", " if isArray val
return val if isString val
return "unable to handle value"
normHttpPrefix = (val) ->
if val.toLowerCase().indexOf('http://') == 0
return val.replace(/http:\/\//i,'')
return val
processRule = (rule, who) ->
func_name = 'processRule'
return false unless isObject rule
required = [
'requestor'
'src'
'dst'
'name'
'erd'
]
for name in required
return "#{func_name}: missing required parameter: #{name}" unless name of rule
unless 'app' of rule or 'svc' of rule
return "#{func_name}: missing required parameter: app or svc"
# convert single values to array
for key in ['from','to','src','dst','app','svc']
continue unless key of rule # skip if not present
rule[key] = [ rule[key] ] unless isArray rule[key]
# check zones
# XXX: check against zone names
# check addresses
# XXX: check against address and address-group objects
# remove slack url prefixes from fqdn style object names
for key in ['src','dst']
newarray = []
for val in rule[key]
newarray.push normHttpPrefix val
rule[key] = newarray
# check app
# XXX: check against app names
# check svc
# XXX: check against service and service-group objects
# add or update request queue
dt_now = moment()
req =
id: "#{who[0..2]}#{dt_now.format('MMDDHHmmss')}"
by: who
type: 'rule'
when: dt_now.format()
request: rule
addUpdateRequestEntry req
return true
addUpdateRequestEntry = (req) ->
return false unless isObject req
return false unless 'id' of req
usermsg = markupRequest req
notifiedAdmins = notifyAdmins usermsg
notifyUsers usermsg, false, req.by unless req.by in notifiedAdmins
fwdata.requests[req.id] = req
writeData()
return true
deleteRequestEntry = (req, res) ->
return false unless isObject req
return false unless isObject res
return false unless 'id' of req
usermsg = markupRequest req, res
notifiedAdmins = notifyAdmins usermsg
notifyUsers usermsg, false, req.by unless req.by in notifiedAdmins
delete fwdata.requests[req.id]
writeData()
return true
markupRequest = (req, res = null) ->
type = req.type[0].toUpperCase() + req.type[1..-1].toLowerCase()
adminmsg = "#{type} requested by #{req.by}."
if res
adminmsg = "#{type} #{res.action} by #{res.by}."
adminmsg += "\n> *Comment* #{res.comment}" if 'comment' of res
adminmsg += "\nRequest metadata:"
for key of req
continue if key in ['request','type']
adminmsg += "\n> *#{key}* #{req[key]}"
adminmsg += "\nRequest:"
entry = req.request
for key of entry
adminmsg += "\n> *#{key}* #{entry[key]}"
return adminmsg
requestQueue_NotifyAdmin_list = (entry, who, comment = null, action = 'requested', notifyList = null) ->
adminmsg = "List #{action} by #{who}."
adminmsg += "\n> *Comment* #{comment}" unless comment is null
for key of entry
adminmsg += "\n> *#{key}* #{entry[key]}"
#adminmsg += "> *Name* #{entry.name}"
#adminmsg += "\n> *Value* #{normType entry.val}"
#adminmsg += "\n> *Type* #{normType entry.type}"
#adminmsg += "\n> *Expires* #{normType entry.expires}"
notifyAdmins adminmsg, false, notifyList
helperListName = (list_name) ->
return false unless isString list_name
return false unless list_name.length > 0
return 'whitelist' if list_name.indexOf('w') == 0
return 'blacklist' if list_name.indexOf('b') == 0
return 'autoban' if list_name.indexOf('a') == 0
if list_name of fwdata.lists
return list_name
return false
listAddEntryHelp = (robot, msg) ->
func_name = 'listAddEntryHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} list add -L <list> -i|-d|-u <value> [options]"
""
"Required options:"
" -L <list> List name; e.g. blacklist"
" -i <ip or cidr> Address or cidr entry, e.g. 127.0.0.1/8"
" -d <domain> Domain entry, e.g. example.com"
" -u <url> URL entry, e.g. example.com/phishing/page123"
""
"Optional:"
" -e <date> Expiration, e.g. +12h, +30d, +6m, +1y, 2021-10-21"
" -r Request; required if not authorized and 2fa enabled"
" -R <reason> Reason for entry, e.g. \"SR 12345\""
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
listAddEntry = (robot, msg) ->
func_name = 'listAddEntry'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
cmd = String msg.match[1]
return listAddEntryHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
console.log "#{log_date} #{func_name}: cmd: #{cmd} out: #{JSON.stringify args}"
return listAddEntryHelp(robot,msg) if 'h' of args
return listAddEntryHelp(robot,msg) if 'help' of args
entry =
creator: who
created: moment().format()
expires: moment().add(1, 'months').format()
unless 'L' of args
return msg.send "#{func_name}: must specify `-L <list>`"
entry.list = helperListName args['L']
unless entry.list
return msg.send "#{func_name}: invalid list: #{args['L']}"
if 'i' of args
addrs = false
if isArray args.i
addrs = args.i
if isString args.i
addrs = [args.i]
addrs = args.i.split(',') if args.i.indexOf(',') > 0
if addrs is false
usermsg = "#{func_name}: invalid ip-address or cidr"
logmsg = "#{modulename}_#{func_name}: #{who} request failed: #{usermsg}"
robot.logger.info logmsg
return msg.send usermsg
for addr in addrs
if extra = addr.match /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})((?:\/\d{1,2}|))$/
if extra[2] isnt '' and extra[2] > -1 and extra[2] < 16
usermsg = "#{func_name}: Blocking addresses with cidr less than /16 not allowed."
logmsg = "#{modulename}_#{func_name}: #{who} request failed: #{usermsg}"
robot.logger.info logmsg
msg.send usermsg unless isAdmin msg, false # no redundant admin notifications
return notifyAdmins logmsg
else
usermsg = "#{func_name}: invalid ip-address or cidr"
logmsg = "#{modulename}_#{func_name}: #{who} request failed: #{usermsg}"
robot.logger.info logmsg
return msg.send usermsg
if UA_Network.contains addr
usermsg = "Blocking addresses in the UA_Network is not allowed. #{safety_fail_note}"
logmsg = "#{modulename}_#{func_name}: #{who} request failed safety check: #{fullcmd}"
robot.logger.info logmsg
msg.send usermsg unless isAdmin msg, false # no redundant admin notifications
return notifyAdmins "#{logmsg}\nReason: #{usermsg}"
entry.type = 'cidr'
entry.val = addrs[0] if addrs.length == 1
entry.vals = addrs if addrs.length > 1
if 'd' of args
domain = normHttpPrefix args.d
for arr in preventDomainBlacklist when domain.toLowerCase().match arr[1]
usermsg = "Blocking `#{arr[0]}` is not allowed. #{safety_fail_note}"
logmsg = "#{modulename}_#{func_name}: #{who} request failed safety check: #{fullcmd}"
robot.logger.info logmsg
msg.send usermsg
return notifyAdmins "#{logmsg}\nReason: #{usermsg}"
entry.type = 'domain'
entry.val = domain
if 'u' of args
url = normHttpPrefix args.u
if url.toLowerCase().indexOf('https://') == 0
return msg.send "#{entry.list}ing of https links not supported."
for arr in preventUrlBlacklist when url.toLowerCase().match arr[1]
usermsg = "Blocking `#{arr[0]}` is not allowed. #{safety_fail_note}"
logmsg = "#{modulename}_#{func_name}: #{who} request failed safety check: #{fullcmd}"
robot.logger.info logmsg
msg.send usermsg
return notifyAdmins "#{logmsg}\nReason: #{usermsg}"
entry.type = 'url'
entry.val = url
unless 'type' of entry
return msg.send "#{modulename}_#{func_name}: must specify `-i <ip>`, `-d <domain>`, or `-u <url>`"
if 'e' of args
expires = args.e
if extra = expires.match /\+(\d+)([a-zA-Z]+)/
n = extra[1]
unit = extra[2]
unless unit in ['h','hours','d','days','w','weeks','M','months','Q','quarters','y','years']
usermsg = "Invalid unit `#{unit}` in expiration `#{expires}`. Use h or hours, d or days, w or weeks, M or months, Q or quarters, y or years."
return msg.send usermsg
entry.expires = moment().add(n,unit).format()
else if moment(expires).isValid()
entry.expires = moment(expires).format()
else
usermsg = "invalid expiration date: #{expires}"
return msg.send usermsg
# reason
if 'R' of args
entry.reason = args['R']
# request
if 'r' of args
dt_now = moment()
req =
id: "#{who[0..2]}#{dt_now.format('MMDDHHmmss')}"
by: who
type: 'list'
when: dt_now.format()
request: entry
addUpdateRequestEntry req
return msg.send "Queued request for review!"
unless isAuthorized msg
usermsg = "or specify `-r` to request listing"
logmsg = "#{modulename}_#{func_name}: #{who} listing failed: #{usermsg}"
robot.logger.info logmsg
return msg.send usermsg
unless is2fa msg
usermsg = "or specify `-r` to request listing"
logmsg = "#{modulename}_#{func_name}: #{who} listing failed: #{usermsg}"
robot.logger.info logmsg
return msg.send usermsg
result = addListEntry entry
if result isnt true
usermsg = "Failed to add to list #{entry.list}. Error: `#{result}`"
msg.send usermsg
usermsg = ''
usermsg += "#{entry.creator} added `#{entry.val}` (#{entry.type}) to *#{entry.list}*." if 'val' of entry
if 'vals' of entry
usermsg += "#{entry.creator} added *#{entry.vals.length}* #{entry.type} entries to *#{entry.list}*."
usermsg += "```#{entry.vals.join ', '}```"
usermsg += " Expires #{entry.expires}." if expires isnt 'undefined'
usermsg += " Reason: ```#{entry.reason}```" if 'reason' of entry
notifySubscribers entry.list, usermsg, who
usermsg += " Change will be applied in < 5 minutes." unless isTerse who
msg.send usermsg
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: "
logmsg += "added entry to #{entry.list}" if 'val' of entry
logmsg += "added #{entry.vals.length} entries to #{entry.list}" if 'vals' of entry
robot.logger.info logmsg
# be terse after the first utterance
fwdata.terse[who] = moment().add(30,'minutes').format()
addListEntry = (entry) ->
func_name = 'addListEntry'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
vals = false
console.log "#{JSON.stringify entry}"
# validate correct list_name
return "parameter not object" unless isObject entry
return "must specify: list" unless 'list' of entry
return "must specify: creator" unless 'creator' or entry
return "must specify: created" unless 'created' of entry
return "must specify: type" unless 'type' of entry
return "must specify: expires" unless 'expires' of entry
vals = [entry.val] if 'val' of entry
vals = entry.vals if 'vals' of entry
return "must specify: val or vals" if vals is false
return "invalid list #{entry.list}" unless entry.list in list_names
logmsg = "#{modulename}_#{func_name}: #{entry.creator} requested:"
logmsg += " #{entry.list} #{entry.type} #{entry.val}" if 'val' of entry
logmsg += " #{entry.list} #{entry.type} #{entry.vals.length} entries" if 'vals' of entry
logmsg += " expires #{moment(entry.expires).format(timefmt)}"
logmsg += " reason #{entry.reason}" if 'reason' of entry
robotRef.logger.info logmsg
fwdata.lists[entry.list] = [] unless entry.list of fwdata.lists
for val in vals
e =
creator: entry.creator
created: entry.created
expires: entry.expires
list: entry.list
type: entry.type
val: val
e.reason = entry.reason if 'reason' of entry
logmsg = "#{modulename}_#{func_name}: #{e.creator} added"
logmsg += " #{e.list} #{e.type} #{e.val}"
logmsg += " expires #{moment(e.expires).fromNow()}"
logmsg += " reason #{e.reason}" if 'reason' of e
robotRef.logger.info logmsg
fwdata.lists[entry.list].push e
writeData()
return true
listUpdateEntryHelp = (robot, msg) ->
func_name = 'listUpdateEntryHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} list update -L <list> -s <searchstring> -e|-R <value>"
""
"Required options:"
" -L <list> List name; e.g. blacklist"
" -s <string> Search string, must only match one entry; e.g. 127.0.0.1"
" -e <expiration> Expiration, e.g. -12h, +36h, -1d, +30d, +6m, +1y, 2021-10-21, etc"
" -R <reason> Reason for entry, e.g. \"SR 12345\""
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
listUpdateEntry = (robot, msg) ->
func_name = 'listUpdateEntry'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name}: #{who}: #{fullcmd}"
cmd = String msg.match[1]
return listUpdateEntryHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
return listUpdateEntryHelp(robot,msg) if 'h' of args
return listUpdateEntryHelp(robot,msg) if 'help' of args
unless 'L' of args
return msg.send "#{func_name}: must specify `-L <list>`"
list_name = helperListName args['L']
unless list_name
return msg.send "#{func_name}: invalid list: #{args['L']}"
unless 's' of args
return msg.send "#{func_name}: must specify `-s <searchstring>`"
l_search = args.s
if l_search.toLowerCase().indexOf('https://') == 0
usermsg = "#{list_name}ing of https links not supported."
return msg.reply usermsg
if l_search.toLowerCase().indexOf('http://') == 0
l_search = l_search.replace(/http:\/\//i,'')
logmsg = "#{modulename}_#{func_name}: #{who} requested: #{list_name} update #{l_search}"
robot.logger.info logmsg
# check for matches
matches = 0
entry = undefined
for e in fwdata.lists[list_name] when e.val.indexOf(l_search) > -1
#console.log "e.type: [#{e.type}] l_search: [#{l_search}] e.val: [#{e.val}]"
if e.val.indexOf(l_search) > -1
#console.log "l_search: [#{l_search}] MATCHED e.val: [#{e.val}]"
matches++
entry = e
if matches != 1
usermsg = "search matched zero or more than a single entry; " +
"improve search term and try again"
return msg.reply usermsg
#console.log e
if 'e' of args
expires = args['e']
if extra = expires.match /(-|\+|)(\d+)([a-zA-Z])/
direction = extra.shift()
n = extra.shift()
unit = extra.shift()
unless unit in ['h','hours','d','days','w','weeks','M','months','Q','quarters','y','years']
usermsg = "Invalid unit `#{unit}` in expiration `#{expires}`. Use h or hours, d or days, w or weeks, M or months, Q or quarters, y or years."
return msg.send usermsg
if direction == '+'
entry.expires = moment(entry.expires).add(n,unit).format()
else if direction == '-'
entry.expires = moment(entry.expires).subtract(n,unit).format()
else
entry.expires = moment().add(n,unit).format()
else if moment(expires).isValid()
entry.expires = moment(expires).format()
else
usermsg = "invalid expiration date: #{expires}"
return msg.send usermsg
entry.expire_notified = false
logmsg = "#{modulename}_#{func_name}: #{who} requested: " +
"#{list_name} #{entry.type} #{entry.val} new expiration #{moment(entry.expires).format(timefmt)}"
robot.logger.info logmsg
usermsg = "#{who} updated `#{entry.val}` in *#{list_name}*.\n"
usermsg += "Old expiration: ```#{old_expiration}```\n"
usermsg += "New expiration: ```#{entry.expires}```\n"
else if 'R' of args
old_reason = 'none'
old_reason = entry.reason if 'reason' of entry
entry.reason = args['R']
logmsg = "#{modulename}_#{func_name}: #{who} requested: " +
"#{list_name} #{entry.type} #{entry.val} update reason: '#{old_reason}' -> '#{entry.reason}'"
robot.logger.info logmsg
usermsg = "#{who} updated `#{entry.val}` in *#{list_name}*.\n"
usermsg += "Old reason: ```#{old_reason}```\n"
usermsg += "New reason: ```#{entry.reason}```\n"
else
usermsg = "must specify new expiration or reason"
return msg.reply usermsg
writeData()
msg.reply usermsg
notifySubscribers list_name, usermsg, who
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: " +
"updated entry in #{list_name}"
robot.logger.info logmsg
listDeleteEntryHelp = (robot, msg) ->
func_name = 'listDeleteEntryHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} list delete -L <list> -s|-i|-d|-u <value> [options]"
""
"Required options:"
" -L <list> List name; e.g. blacklist"
" -i <ip or cidr> Address or cidr entry, e.g. 127.0.0.1/8"
" -d <domain> Domain entry, e.g. example.com"
" -u <url> URL entry, e.g. example.com/phishing/page123"
""
"Optional:"
" -r Request; required if not authorized and 2fa enabled"
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
listDeleteEntry = (robot, msg) ->
func_name = 'listDeleteEntry'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name} #{who} requested: #{fullcmd}"
cmd = String msg.match[1]
return listDeleteEntryHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
return listDeleteEntryHelp(robot,msg) if 'h' of args
return listDeleteEntryHelp(robot,msg) if 'help' of args
q =
axis: 0
unless 'L' of args
return msg.send "#{func_name}: must specify `-L <list>`"
q.list = helperListName args['L']
unless q.list
return msg.send "#{func_name}: invalid list: #{q.list}"
required = 0
if 's' of args
required++
q.search = args.s
if q.search.toLowerCase().indexOf('https://') == 0
return msg.reply "https links not supported"
if args.s.toLowerCase().indexOf('http://') == 0
q.search = args.s.replace(/http:\/\//i,'')
q.axis += 1
if 'i' of args
required++
addrs = false
if isArray args.i
addrs = args.i
if isString args.i
addrs = [args.i]
addrs = args.i.split(',') if args.i.indexOf(',') > 0
if addrs is false
usermsg = "#{func_name}: invalid ip-address or cidr"
logmsg = "#{modulename}_#{func_name}: #{who} request failed: #{usermsg}"
robot.logger.info logmsg
return msg.send usermsg
q.axis += 2
q.type = 'cidr'
q.addrs = addrs
# display help unless one of the rquired parameter is specified
return listDeleteEntryHelp(robot,msg) unless required > 0
searched = 0
deleted = []
new_listdata = []
listdata = fwdata.lists[q.list]
deleted.push sprintf displayfmt, 'Type', 'Value', 'Expiration', 'Creator', 'Reason'
for e in listdata
axis = 0
#console.log "#{log_date} #{func_name}: #{JSON.stringify e}"
# if not a match, add it to the keepers
if 'type' of q
test = q.type == e.type
#console.log "#{log_date} #{func_name}: TYPE e.type|#{e.type} == q.type|#{q.type} = test|#{test}"
if test
axis++
#console.log "#{log_date} #{func_name}: incremented axis: #{axis}"
if 'search' of q
test = e.val.indexOf(q.search) == -1
#console.log "#{log_date} #{func_name}: SEARCH e.val|#{e.val} q.search|#{q.search} test|#{test}"
if test
axis++
#console.log "#{log_date} #{func_name}: incremented axis: #{axis}"
if 'addrs' of q
test = e.val in q.addrs
#console.log "#{log_date} #{func_name}: ADDRS e.val|#{e.val} q.addrs|#{q.addrs} test|#{test}"
if test
axis++
#console.log "#{log_date} #{func_name}: incremented axis: #{axis}"
if axis < q.axis
#console.log "#{log_date} #{func_name}: axis|#{axis} < q.axis|#{q.axis} = NOT ENOUGH AXIS, keeping entry"
new_listdata.push e
continue
#console.log "#{log_date} #{func_name}: axis|#{axis} >= q.axis|#{q.axis} = ENOUGH AXIS, deleting entry"
expires = moment(e.expires)
#if expires.isBefore() # now
# new_listdata.push e
# continue
# display
reason = ''
if 'reason' of e
unless e.reason.indexOf("\n") > 0
reason = e.reason
else
reason = e.reason.split("\n").shift().substring(0,20)
deleted.push sprintf displayfmt, e.type, e.val,
expires.fromNow(), e.creator, reason
deltaN = listdata.length - new_listdata.length
if deltaN > 0
usermsg = "#{who} removed *#{deltaN}* entries from *#{q.list}*"
usermsg += "```"+ deleted.join("\n") + "```"
fwdata.lists[q.list] = new_listdata
writeData()
else
usermsg = "#{q.list} delete request did not match any records."
msg.send usermsg
logmsg = "#{modulename}_#{func_name} #{who} response: " +
"removed #{deltaN} entries from #{q.list}"
robot.logger.info logmsg
if deltaN > 0
notifySubscribers q.list, usermsg, who
listShow = (robot, msg) ->
func_name = 'listShow'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name} #{who} requested: #{fullcmd}"
list_name = helperListName String(msg.match[1])
unless list_name
return msg.send "#{func_name}: invalid list: #{list_name}"
l_type = false
l_search = false
if msg.match[2]?
l_search = String(msg.match[2])
unless list_name of fwdata.lists and fwdata.lists[list_name].length > 0
return msg.send "No entries on list #{list_name}."
params = {}
params.type = l_type if l_type
params.search = l_search if l_search
r = buildList list_name, params
maxLinesViaChat = 10
if r.lines == 1
msg.send r.single
if r.lines > 1 and r.lines <= maxLinesViaChat
msg.send "*#{list_name}* #{r.lines} entries.\n```#{r.list}```"
if r.lines > maxLinesViaChat
msg.send "*#{list_name}* #{r.lines} entries.\n"+
">List too long to display through chat. Try this:\n"+
">https://s3-us-west-2.amazonaws.com/"+
"#{s3bucket}/#{s3pathPrefix}/#{list_name}-all-list"
logmsg = "#{modulename}_#{func_name}: robot responded to #{msg.envelope.user.name}: " +
"displayed #{list_name} items and expirations"
robot.logger.info logmsg
requestShowHelp = (robot, msg) ->
func_name = 'requestShowHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} request show -a|-i <id>|-n <name>|-t <type>"
""
"Options:"
" -a All requests"
" -i Request id"
" -n Requestor name"
" -t Request type"
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
requestShow = (robot, msg) ->
func_name = 'requestShow'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name}: #{who}: #{fullcmd}"
cmd = String msg.match[1]
return requestShowHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
return requestShowHelp(robot,msg) if 'h' of args
return requestShowHelp(robot,msg) if 'help' of args
if 'i' of args
unless args.i of fwdata.requests
msg.send "#{func_name}: request does not exist: id=#{args.i}"
usermsg = markupRequest fwdata.requests[args.i]
msg.send usermsg
logmsg = "#{modulename}_#{func_name}: responded to #{who}: " +
"displaying id #{args.i}"
return robot.logger.info logmsg
out = ''
requestCount = 0
for key of fwdata.requests
req = fwdata.requests[key]
continue if 'u' of args and req.by isnt args.u
continue if 't' of args and req.type isnt args.t
requestCount += 1
out += "type=#{req.type} id=#{req.id} by=#{req.by} when=#{req.when}\n"
if requestCount > 0
msg.send "Requests:\n```#{out}```"
else
msg.send "No requests in queue; nice work!"
logmsg = "#{modulename}_#{func_name}: responded to #{who}: " +
"displayed #{requestCount} requests"
robot.logger.info logmsg
requestApproveHelp = (robot, msg) ->
func_name = 'requestApproveHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} request approve -i <id> -m \"<message>\""
""
"Required options:"
" -i Request id"
" -m Approval message"
""
"Note: immediate upon approval the request will be applied!"
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
requestApprove = (robot, msg) ->
func_name = 'requestApprove'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name}: #{who}: #{fullcmd}"
cmd = String msg.match[1]
return requestDeclineHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
return requestDeclineHelp(robot,msg) if 'h' of args
return requestDeclineHelp(robot,msg) if 'help' of args
console.log "#{log_date} #{func_name}: cmd: #{cmd} out: #{JSON.stringify args}"
return unless is2fa msg
unless 'i' of args
return msg.send "#{func_name}: missing required parameter: `-i <id>`"
id = args.i
unless 'm' of args
return msg.send "#{func_name}: missing required parameter: `-m \"<msg>\"`"
message = args.m
unless id of fwdata.requests
return msg.send "#{func_name}: request not found: id=#{id}"
req = fwdata.requests[id]
result = false
if req.type is 'list'
result = addListEntry(req.request)
else
result = "unable to process request type: #{req.type}"
unless result is true
return msg.send "Failed to apply #{req.type}. Error: ```#{result}```"
res =
by: who
action: 'approved'
comment: args.m
deleteRequestEntry req, res
#msg.send "Request #{id} approved with message: ```#{message}```"
logmsg = "#{modulename}_#{func_name}: responded to #{who}: " +
"request #{id} approved with message: #{message}"
robot.logger.info logmsg
requestDeclineHelp = (robot, msg) ->
func_name = 'requestDeclineHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} request decline -i <id> -m <message>"
""
"Required options:"
" -i Request id"
" -m Decline message"
""
"Note: immediate upon decline the request is removed and notification sent."
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
requestDecline = (robot, msg) ->
func_name = 'requestDecline'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name}: #{who}: #{fullcmd}"
cmd = String msg.match[1]
return requestDeclineHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
return requestDeclineHelp(robot,msg) if 'h' of args
return requestDeclineHelp(robot,msg) if 'help' of args
console.log "#{log_date} #{func_name}: cmd: #{cmd} out: #{JSON.stringify args}"
return unless is2fa msg
unless 'i' of args
return msg.send "#{func_name}: missing required parameter: `-i <id>`"
id = args.i
unless 'm' of args
return msg.send "#{func_name}: missing required parameter: `-m \"<msg>\"`"
message = args.m
unless id of fwdata.requests
return msg.send "#{func_name}: request not found: id=#{id}"
req = fwdata.requests[id]
res =
by: who
action: 'declined'
comment: args.m
deleteRequestEntry req, res
#msg.send "Request #{id} declined with message: ```#{message}```"
logmsg = "#{modulename}_#{func_name}: responded to #{who}: " +
"request #{id} declined with message: #{message}"
robot.logger.info logmsg
buildList = (list_name, params = {}) ->
func_name = 'buildList'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
lines = 0 # entries
out_terse = '' # string
delete params.type if 'type' of params and params.type is 'all'
out_list = sprintf "#{displayfmt}\n", 'Type', 'Value', 'Expiration', 'Creator', 'Reason'
for e in fwdata.lists[list_name]
bool_expires = false
dt_expires = moment(e.expires)
if 'expires' of params
dt = moment() unless 'when' of params
dt = moment(params.when) if 'when' of params
bool_expires = dt_expires.isBefore(dt)
bool_expires = dt_expires.isBefore(dt) if params.expires == 'before' and dt_expires.isBefore(dt)
bool_expires = dt_expires.isAfter(dt) if params.expires == 'after' and dt_expires.isAfter(dt)
#console.log "#{log_date} #{func_name} #{dt_expires.fromNow()} / #{dt_expires.format()} #{params.expires} #{dt.format()} #{bool_expires}"
continue unless bool_expires
else
continue if dt_expires.isBefore() # skip expired
continue if 'type' of params and params.type != e.type
continue if 'search' of params and e.val.indexOf(params.search) == -1
if 'expire_notify' of params # if pre-expiration notify, only do it once
continue if 'expire_notified' of e and e.expire_notified
e.expire_notified = true
reason = ''
reason = e.reason if 'reason' of e
if reason.indexOf("\n") > 0
reason = e.reason.split("\n").shift().substring(0,20)
vals = [e.val] if 'val' of e
vals = e.vals if 'vals' of e
for val in vals
lines++
out_terse += "#{val}\n"
out_list += sprintf "#{displayfmt}\n", e.type, val, dt_expires.fromNow(), e.creator, reason
out_single = "#{e.creator} added `#{val}` (#{e.type}) to list"
out_single += " #{list_name}. Expires #{moment(e.expires).fromNow()}."
out_single += " Reason: ```#{e.reason}```" if 'reason' of e
output =
single: out_single
terse: out_terse
list: out_list
lines: lines
return output
listSubscribe = (robot, msg) ->
func_name = 'listSubscribe'
user = msg.envelope.user
list_name = msg.match[1]
list_name = 'whitelist' if list_name.indexOf('w') == 0
list_name = 'blacklist' if list_name.indexOf('b') == 0
list_name = 'autoban' if list_name.indexOf('a') == 0
who = user.name
who = msg.match[2] if msg.match[2]
logmsg = "#{modulename}_#{func_name}: #{user.name} requested: subscribe #{list_name} #{who}"
robot.logger.info logmsg
fwdata.notify[list_name] = [] unless list_name of fwdata.notify
fwdata.notify[list_name].push who unless who in fwdata.notify[list_name]
usermsg = "Added #{who} to list #{list_name}."
msg.send usermsg
logmsg = "#{modulename}_#{func_name}: robot responded to #{user.name}: " +
"added #{who} to list #{list_name}"
robot.logger.info logmsg
writeData()
listUnsubscribe = (robot, msg) ->
func_name = 'listUnsubscribe'
user = msg.envelope.user
list_name = msg.match[1]
list_name = 'whitelist' if list_name.indexOf('w') == 0
list_name = 'blacklist' if list_name.indexOf('b') == 0
list_name = 'autoban' if list_name.indexOf('a') == 0
who = msg.envelope.user.name
who = msg.match[2] if msg.match[2]
logmsg = "#{modulename}_#{func_name}: #{user.name} requested: unsubscribe #{list_name} #{who}"
robot.logger.info logmsg
unless list_name of fwdata.notify
usermsg = "No such list #{list_name}."
return msg.reply usermsg
n = fwdata.notify[list_name].indexOf(who)
unless n > -1
usermsg = "`#{who}` not a member of list #{list_name}."
return msg.reply usermsg
fwdata.notify[list_name].splice(n, 1)
usermsg = "Removed #{who} from list #{list_name}."
msg.send usermsg
logmsg = "#{modulename}_#{func_name}: robot responded to #{user.name}: " +
"removed #{who} from list #{list_name}"
robot.logger.info logmsg
writeData()
listShowSubscribers = (robot, msg) ->
func_name = 'listShowSubscribers'
who = msg.envelope.user.name
list_name = ''
list_name = msg.match[1] if msg.match[1]
list_name = 'whitelist' if list_name.indexOf('w') == 0
list_name = 'blacklist' if list_name.indexOf('b') == 0
list_name = 'autoban' if list_name.indexOf('a') == 0
logmsg = "#{modulename}_#{func_name}: #{who} requested subscribers"
logmsg += " for list #{list_name}" if list_name
robot.logger.info logmsg
usermsg = ""
for list of fwdata.notify
continue if list_name and list != list_name
continue unless isArray(fwdata.notify[list]) and fwdata.notify[list].length > 0
usermsg += "Subscribers for #{list}: `"+ fwdata.notify[list].join('`, `') + "`\n\n"
if usermsg
msg.reply usermsg
logmsg = "#{modulename}_#{func_name}: displayed subscribers to #{who}"
robot.logger.info logmsg
httpGetHelp = (robot, req, res) ->
func_name = 'httpGetHelp'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
clientip = req.connection.remoteAddress || req.socket.remoteAddress ||
req.connection.socket.remoteAddress
logmsg = "#{modulename}_#{func_name}: web request from #{clientip}"
robot.logger.info logmsg
arr = ["<html>\n<body>\n<pre>\n"]
for list in list_names
for type in list_types
arr.push "<a href='#{list}/#{type}'>#{list}/#{type}</a>\n"
arr.push "</pre>\n</body>\n</html>\n"
res.setHeader 'content-type', 'text/html'
res.end arr.join "\n"
logmsg = "#{modulename}_#{func_name}: robot responded to web request"
robot.logger.info logmsg
httpGetList = (robot, req, res, list_name, list_type) ->
func_name = 'httpGetList'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
clientip = req.connection.remoteAddress || req.socket.remoteAddress ||
req.connection.socket.remoteAddress
rememberCheckin clientip, list_name, list_type
logmsg = "#{modulename}_#{func_name}: web request from #{clientip}: get #{list_type} #{list_name}"
robot.logger.info logmsg
params =
type: list_type
r = buildList list_name, params
content = '# nothing here yet! #'
content = r.terse if r.lines > 0
res.setHeader 'content-type', 'text/plain'
res.end content
logmsg = "#{modulename}_#{func_name}: robot responded to web request: sent #{list_type} #{list_name}"
robot.logger.info logmsg
listShowFirewallCheckins = (robot, msg) ->
who = msg.envelope.user.name
logmsg = "#{modulename}_#{func_name}: #{who} requested: checkins"
robot.logger.info logmsg
arr = []
for obj in fwdata.firewalls
obj.checkin = moment(obj.checkin) if typeof(obj.checkin) is 'string'
arr.push sprintf '%-16s %-10s %-10s %-15s', obj.name, obj.list, obj.type,
obj.checkin.fromNow()
usermsg = "Expected firewall check times: ```"+ arr.join("\n") + "```"
msg.send usermsg
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: checkins"
robot.logger.info logmsg
rememberCheckin = (clientip,list_name,l_type) ->
return unless fwname = fwnames[clientip] # skip non-firewalls
for obj in fwdata.firewalls
if obj.ip is clientip and obj.type is l_type and obj.list is list_name
obj.checkin = moment().add(5,'minutes')
writeData()
return
# otherwise create new object
obj =
ip: clientip
name: fwname
list: list_name
type: l_type
checkin: moment().add(5,'minutes')
fwdata.firewalls.push obj
if fwdata.firewalls.length > 1
fwdata.firewalls = fwdata.firewalls.sort (a,b) ->
sortBy('name',a,b) or sortBy('list',a,b) or sortBy('type',a,b)
writeData()
moduleHelp = (robot, msg) ->
func_name = 'moduleHelp'
who = msg.envelope.user.name
admin = isAdmin msg
arr = [
"#{modulename} list show <list> [searchterm]"
"#{modulename} list add -h"
"#{modulename} list del -h"
"#{modulename} list update -h"
"#{modulename} list subscribe <list> [username] - subscribe to change notifications"
"#{modulename} list unsubscribe <list> [username]"
"#{modulename} list subscribers [list]"
"#{modulename} rule <options>"
]
arr.push "#{modulename} request show [options]" if admin
arr.push "#{modulename} request approve <options>" if admin
out = arr.join "\n"
msg.send "```#{out}```"
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: " +
"displayed #{modulename} help"
robot.logger.info logmsg
listHelp = (robot, msg) ->
func_name = 'listHelp'
who = msg.envelope.user.name
admin = isAdmin msg
arr = [
"#{modulename} list show <list> [searchterm]"
"#{modulename} list add -h"
"#{modulename} list del -h"
"#{modulename} list update -h"
"#{modulename} list subscribe <list> [username] - subscribe to change notifications"
"#{modulename} list unsubscribe <list> [username]"
"#{modulename} list subscribers [list]"
]
out = arr.join "\n"
msg.send "```#{out}```"
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: " +
"displayed #{modulename} help"
robot.logger.info logmsg
writeData = ->
func_name = 'writeData'
fs.writeFileSync data_file, JSON.stringify(fwdata), 'utf-8'
logmsg = "#{modulename}_#{func_name}: wrote #{data_file}"
robotRef.logger.info logmsg
module.exports = (robot) ->
robotRef = robot
if process.env.HUBOT_GRAYLOG_URL && process.env.HUBOT_GRAYLOG_TOKEN
glApi = robot.http process.env.HUBOT_GRAYLOG_URL
glApi.auth process.env.HUBOT_GRAYLOG_TOKEN, 'token'
glApi.path 'api/search/universal/relative'
glApi.header 'Accept', 'application/json'
else
console.warn "#{modulename}: HUBOT_GRAYLOG_URL and HUBOT_GRAYLOG_TOKEN" +
" environment variables not set."
setTimeout oneMinuteWorker, 5 * 1000
setTimeout fiveMinuteWorker, 15 * 1000
try
fwdata = JSON.parse fs.readFileSync data_file, 'utf-8'
robot.logger.info "#{modulename}: read #{data_file}" if robot.logger
fwdata = {} unless isObject fwdata
fwdata['notify'] = {} unless isObject fwdata['notify']
fwdata['lists'] = {} unless isObject fwdata['lists']
fwdata['firewalls'] = [] unless isArray fwdata['firewalls']
fwdata['terse'] = {} unless isObject fwdata['terse']
fwdata['attackers'] = {} unless isObject fwdata['attackers']
fwdata['requests'] = {} unless isObject fwdata['requests']
catch error
unless error.code is 'ENOENT'
console.log("#{modulename}: unable to read #{data_file}: ", error)
robot.router.get "/#{robot.name}/#{modulename}", (req, res) ->
return httpGetHelp robot, req, res
robot.router.get "/#{robot.name}/#{modulename}/blacklist/url", (req, res) ->
return httpGetList robot, req, res, 'blacklist', 'url'
robot.router.get "/#{robot.name}/#{modulename}/blacklist/cidr", (req, res) ->
return httpGetList robot, req, res, 'blacklist', 'cidr'
robot.router.get "/#{robot.name}/#{modulename}/blacklist/domain", (req, res) ->
return httpGetList robot, req, res, 'blacklist', 'domain'
robot.router.get "/#{robot.name}/#{modulename}/whitelist/url", (req, res) ->
return httpGetList robot, req, res, 'whitelist', 'url'
robot.router.get "/#{robot.name}/#{modulename}/whitelist/cidr", (req, res) ->
return httpGetList robot, req, res, 'whitelist', 'cidr'
robot.router.get "/#{robot.name}/#{modulename}/whitelist/domain", (req, res) ->
return httpGetList robot, req, res, 'whitelist', 'domain'
robot.router.get "/#{robot.name}/#{modulename}/autoban/cidr", (req, res) ->
return httpGetList robot, req, res, 'autoban', 'cidr'
robot.respond /(?:firewall|fw)(?: help| h|)$/, (msg) ->
return moduleHelp robot, msg
robot.respond /(?:firewall|fw) list(?: help| h|)$/, (msg) ->
return listHelp robot, msg
robot.respond /(?:firewall|fw) list show admins$/i, (msg) ->
return listShowAdmins robot, msg
robot.respond /(?:firewall|fw) list show (?:checkins|firewalls|fw)$/i, (msg) ->
return listShowFirewallCheckins robot, msg
robot.respond /(?:firewall|fw) list subscribers(?: (.+)|)$/i, (msg) ->
return listShowSubscribers robot, msg
robot.respond /(?:firewall|fw) list show ([^ ]+)(?: (.+)|)$/i, (msg) ->
return listShow robot, msg
robot.respond /(?:firewall|fw) list (?:add|a)(?: (.+)|)$/i, (msg) ->
return listAddEntry robot, msg
robot.respond /(?:firewall|fw) list (?:delete|del|d)(?: (.+)|)$/i, (msg) ->
return unless isAuthorized msg
return unless is2fa msg
return listDeleteEntry robot, msg
robot.respond /(?:firewall|fw) list (?:update|upd|up|u)(?: (.+)|)$/i, (msg) ->
return unless isAuthorized msg
return unless is2fa msg
return listUpdateEntry robot, msg
robot.respond /(?:firewall|fw) list (?:subscribe|sub) ([^ ]+)(?: ([^ ]+)|)$/i, (msg) ->
return listSubscribe robot, msg
robot.respond /(?:firewall|fw) list (?:unsubscribe|unsub) ([^ ]+)(?: ([^ ]+)|)$/i, (msg) ->
return listUnsubscribe robot, msg
robot.respond /(?:firewall|fw) (?:rule|r)(?: (.+)|)$/i, (msg) ->
return unless isAuthorized msg
return ruleAddEntry robot, msg
robot.respond /(?:firewall|fw) (?:request|req) show(?: (.+)|)$/i, (msg) ->
return unless isAdmin msg
return requestShow robot, msg
robot.respond /(?:firewall|fw) (?:request|req) (?:approve|app|a)(?: (.+)|)$/i, (msg) ->
return unless isAdmin msg
return requestApprove robot, msg
robot.respond /(?:firewall|fw) (?:request|req) (?:decline|dec|d)(?: (.+)|)$/i, (msg) ->
return unless isAdmin msg
return requestDecline robot, msg
| true | # Description:
# Manage black/white lists for UA PA FW.
#
# Dependencies:
# moment
#
# Configuration:
# xxxxxxxxxxx [required] - API KEY
# GRAYLOG_URL (e.g. https://graylog.example.com)
# GRAYLOG_API_TOKEN (e.g. PI:KEY:<KEY>END_PI)
# GRAYLOG_SEPARATOR (e.g. ','. Default: "\n")
#
#
# Commands:
# hubot firewall - firewall commands
#
# Notes:
# requires hubot-auth be present
#
# Author:
# gfjohnson
fs = require 'fs'
moment = require 'moment'
CIDRMatcher = require 'cidr-matcher'
sprintf = require("sprintf-js").sprintf
AWS = require 'aws-sdk'
s3 = new AWS.S3()
request = require 'request'
parse = require 'yargs-parser'
modulename = 'fw'
data_file = modulename + ".json"
safety_fail_note = 'If this is time critical ask a human; otherwise please open a ticket.'
displayfmt = '%-4s %-50s %-15s %-10s %s'
timefmt = 'YYYY-MM-DD HH:mm:ss ZZ'
msOneMinute = 60 * 1000
msFiveMinutes = 300 * 1000
glApi = null;
s3bucket = 'ua-oit-security-pub'
s3pathPrefix = 'stats'
defaultNotifyAdmin = 'all' # normally null, for 'all'
defaultNotifySubscribers = 'all' # normally null, for 'all'
# enable or disable auto-banning
attackAutoBanEnabled = true
attackAutoBanNotifySubscribers = true
# auto-ban after X occurances
attackBanAfterOccurances = 5
# if no attacks detected in this duration, expire counter
attackExpirationHours = 6
# escalating ban durations for 2nd, 3rd, etc duration
attackBanHours = [
1
24
24 * 7
24 * 30
]
UA_Network = new CIDRMatcher [
'PI:IP_ADDRESS:192.168.3.11END_PI/16'
'PI:IP_ADDRESS:172.16.58.3END_PI/18'
'10.0.0.0/8'
'172.16.0.0/12'
'192.168.0.0/16'
]
list_names = [
'blacklist'
'whitelist'
'autoban'
]
list_types = [
'domain'
'cidr'
'url'
]
preventDomainBlacklist = [
[ 'alaska.edu', /alaska\.edu$/ ]
[ 'uaf.edu', /uaf\.edu$/ ]
]
preventUrlBlacklist = [
[ 'alaska.edu', /[^\/]+alaska.edu\// ]
[ 'uaf.edu', /[^\/]+uaf.edu\// ]
]
robotRef = false
fwdata = false
fwnames =
'10.9.0.252': 'Fairbanks-1'
'10.9.0.253': 'Fairbanks-2'
'10.9.128.10': 'Anchorage-1'
'10.9.128.11': 'Anchorage-2'
'10.9.192.10': 'Juneau-1'
'10.9.192.11': 'Juneau-2'
if process.env.HUBOT_AUTH_ADMIN
hubotAuthAdmin = process.env.HUBOT_AUTH_ADMIN.split ','
else
console.warn "#{modulename}: HUBOT_AUTH_ADMIN environment variable not set."
# borrowed from
# http://stackoverflow.com/questions/9796764/how-do-i-sort-an-array-with-coffeescript
sortBy = (key, a, b, r) ->
r = if r then 1 else -1
return -1*r if a[key] > b[key]
return +1*r if a[key] < b[key]
return 0
isArray = Array.isArray or (obj) -> toString.call(obj) == '[object Array]'
isString = (obj) -> toString.call(obj) == '[object String]'
isObject = (obj) -> toString.call(obj) == '[object Object]'
isAdmin = (msg, reply = true) ->
console.error 'bad robotRef' unless robotRef
who = msg.envelope.user.name
return true if who in hubotAuthAdmin
msg.reply "This requires administrator privilege." if reply
return false
isAuthorized = (msg, reply = true) ->
console.error 'bad robotRef' unless robotRef
u = msg.envelope.user
return true if robotRef.auth.hasRole(u,'fw')
msg.reply "Not authorized. Missing fw role." if reply
return false
is2fa = (msg, reply = true) ->
console.error 'bad robotRef' unless robotRef
u = msg.envelope.user
return true if robotRef.auth.is2fa(u)
msg.reply "2fa required. Use `auth 2fa` to validate identity." if reply
return false
isTerse = (who) ->
fwdata['terse'] = {} unless 'terse' of fwdata
return true if who of fwdata.terse && moment(fwdata.terse[who]).isAfter()
return false
isBanned = (ban_expires) ->
expires = moment(ban_expires)
return false unless expires.isValid()
return true if expires.isAfter()
return false
panConfigDevicesVsysRulebaseSecurityRule = (params, callback) ->
func_name = 'panConfigDevicesVsysRulebaseSecurityRule'
params = { name: params } if isString params
return false unless isObject params
return false unless 'name' of params
params.path = "/rulebase/security/rules/entry[@name='#{params.name}']"
return panConfigDevicesVsys params, callback
panConfigDeviceVsysAddress = (params, callback) ->
func_name = 'panConfigDeviceVsysAddress'
params = { name: params } if isString params
return false unless isObject params
for key in ['name']
return "#{func_name}: missing required param: #{key}" unless key of param
params.path = "/address/entry[@name='#{params.name}']"
return panConfigDevicesVsys params, callback
panConfigDevicesVsys = (params, callback) ->
func_name = 'panConfigDevicesVsys'
params = { path: params } if isString params
return false unless isObject params
for key in ['path']
return "#{func_name}: missing required param: #{key}" unless key of param
params.vsys = 'vsys1' unless 'vsys' of params
params.path = "/vsys/entry[@name='#{params.vsys}']/#{params.path}"
return panConfigDevices params, callback
panConfigDevices = (params, callback) ->
func_name = 'panConfigDevices'
params = { path: params } if isString params
return false unless isObject params
for key in ['path']
return "#{func_name}: missing required param: #{key}" unless key of param
params.device = 'localhost.localdomain' unless 'device' of params
params.path = "/devices/entry[@name='#{paramsPI:EMAIL:<EMAIL>END_PI.device}']#{params.path}"
return panGetConfig params, callback
panConfig = (params, callback) ->
func_name = 'panConfig'
return false unless isObject params
for key in ['fqdn','path','key']
return "#{func_name}: missing required param: #{key}" unless key of param
params.action = 'get' unless 'action' of params
unless params.action in ['get']
return "#{func_name}: invalid action param: #{params.action}"
q =
type: 'config'
action: params.action
xpath: "/config#{params.path}"
key: params.key
options =
url: "https://#{params.fqdn}/api/"
qs: q
strictSSL: false
accept: 'text/xml'
request.get options, (err, res, body) ->
return callback(null, err) if err
# XXX: convert xml2json
return callback(body)
return true
xmlVal = (name,val) ->
return '' unless name of obj
return "<#{name}>#{val}</#{name}>"
panOpTestSecurityPolicyMatch = (params, callback) ->
func_name = 'panOpTestSecurityPolicyMatch'
# cmd: <test><security-policy-match><from></from></security-policy-match></test>
#params = { path: params } if isString params
cmd = ''
return false unless isObject params
required = [
'destination'
'destination-port'
'protocol'
'source'
]
for key in required
return "#{func_name}: missing required param: #{key}" unless key of params
cmd += xmlVal key, params[key]
optional = [
'application'
'category'
'from'
'show-all'
'source-user'
'to'
]
for key in optional
if key of params
cmd += xmlVal key, params[key]
params.cmd = "<test><security-policy-match>#{cmd}</security-policy-match></test>"
return panOp params, callback
panCommit = (params, callback) ->
# cmd: <commit></commit>
#params = { path: params } if isString params
cmd = ''
return false unless isObject params
params.type = 'commit'
optional = [
'description'
]
for name in optional
if name of params
cmd += xmlVal name, params[name]
params.cmd = xmlVal 'commit', cmd
return panOp params, callback
panOp = (params, callback) ->
func_name = 'panOp'
return false unless isObject params
for key in ['PI:KEY:<KEY>END_PIdn','cmd']
return "#{func_name}: missing required param: #{key}" unless key of param
param.type = 'op' unless 'type' of params
unless params.type in ['op','commit']
return "#{func_name}: invalid param type: #{params.type}"
q =
type: 'op'
cmd: params.cmd
options =
url: "https://#{params.fqdn}/api/"
qs: q
strictSSL: false
accept: 'text/xml'
request.get options, (err, res, body) ->
return callback(null, err) if err
# XXX: convert xml2json
return callback(body)
return true
oneMinuteWorker = ->
queryAndProcessAttacks()
setTimeout oneMinuteWorker, msOneMinute
fiveMinuteWorker = ->
for list in ['autoban','blacklist','whitelist']
uploadReport list, 'all', 'list'
for type in ['url','cidr','domain']
continue if list is 'autoban' and type isnt 'cidr'
uploadReport list, type, 'terse'
expireAttackers()
preExpireNotify 'blacklist'
preExpireNotify 'whitelist'
expireEntriesFromList 'blacklist'
expireEntriesFromList 'whitelist'
expireEntriesFromList 'autoban'
setTimeout fiveMinuteWorker, msFiveMinutes
queryAndProcessCommits = ->
func_name = 'queryAndProcessCommits'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
console.log "#{log_date} #{func_name} --"
return if glApi is null
q =
query: 'logfile:SYSTEM\/general',
fields: 'message,source',
range: 60,
decorate: 'true'
glApi.query q
#console.log 'exec glApi.get() with glApi.options: ', JSON.stringify glApi.options, null, 2
glApi.get() (err, res, body) ->
unless res.statusCode is 200
return console.warn 'Error requesting Graylog url statusCode=', res.statusCode, 'err=', err, 'options=', glApi.options
glresponse = JSON.parse body
#console.log 'glApi returns body:', JSON.stringify jsonbody, null, 2
events = glresponse.messages.map (m) => m.message
for event in events
processCommit event
queryAndProcessAttacks = ->
func_name = 'queryAndProcessAttacks'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
console.log "#{log_date} #{func_name} --"
return if glApi is null
q =
query: 'logfile:THREAT\\/vulnerability',
fields: 'message,source,addrsrc,addrdst,action',
range: 60,
decorate: 'true'
glApi.query q
#console.log 'exec glApi.get() with glApi.options: ', JSON.stringify glApi.options, null, 2
glApi.get() (err, res, body) ->
unless res.statusCode is 200
return console.warn 'Error requesting Graylog url statusCode=', res.statusCode, 'err=', err, 'options=', glApi.options
glresponse = JSON.parse body
#console.log 'glApi returns body:', JSON.stringify jsonbody, null, 2
events = glresponse.messages.map (m) => m.message
for event in events
# skip if already on the attack list
#continue if fwdata.attackers[event.addrsrc] and fwdata.attackers[event.addrsrc].banned
# skip unless action
continue unless event.action in ['block-ip','drop','reset-both']
# skip if source is internal
continue if UA_Network.contains event.addrsrc
addAttackSource event
addAttackSource = (event) ->
func_name = 'addAttackSource'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
src = event.addrsrc
ldt = moment(event.timestamp).format('HH:mm:ss')
unless src of fwdata.attackers
console.log "#{log_date} #{func_name}: new source #{event.addrsrc}"
fwdata.attackers[src] =
attacks: 0
attacker: src
victims: []
created: moment().format()
banexpires: 0
msgs: []
fwdata.attackers[src].attacks++
fwdata.attackers[src].last = moment().format()
fwdata.attackers[src].msgs.push "#{ldt} / #{event.source} / #{event.message}"
if fwdata.attackers[src].msgs.length > attackBanAfterOccurances
fwdata.attackers[src].msgs.shift()
if event.addrdst not in fwdata.attackers[src].victims
fwdata.attackers[src].victims.push event.addrdst
# ban if attack count exceeds attackBanAfterOccurances value
if fwdata.attackers[src].attacks >= attackBanAfterOccurances
# do not ban if already banned
banAttackSource fwdata.attackers[src] unless isBanned fwdata.attackers[src].banexpires
banAttackSource = (attackSource) ->
func_name = 'banAttackSource'
#console.log 'banAttackSource --'
src = attackSource.attacker
msgs = attackSource.msgs.join "\n"
status = 'would have auto-banned'
status = 'auto-banning' if attackAutoBanEnabled
attackSource.bancount = 0 unless attackSource['bancount']
bc = fwdata.attackers[src].bancount
if attackSource.bancount >= (attackBanHours.length - 1)
bc = attackBanHours.length - 1
fwdata.attackers[src].bancount++
banHours = attackBanHours[bc]
attackSource.banexpires = moment().add(banHours,'hours').format()
usermsg = "#{modulename}_#{func_name}: #{status} `#{src}` for #{banHours} hours due to" +
" #{attackBanAfterOccurances} events since" +
" #{moment(attackSource.created).format('YYYY-MM-DD HH:mm:ss')}"
usermsg += " and #{bc} previous bans" if bc > 0
usermsg += ": ```#{msgs}```"
list_name = 'autoban'
notifySubscribers list_name, usermsg
# only notify unless enabled
return unless attackAutoBanEnabled
entry =
creator: "robot"
list: list_name
created: moment().format()
expires: attackSource.banexpires
type: 'cidr'
val: attackSource.attacker
reason: "#{attackSource.attacks} attacks\n#{msgs}"
result = addListEntry entry
if result isnt true
usermsg = "Failed to add `#{entry.val}` (#{entry.type}) to list" +
" #{list_name}. Error: `#{result}`"
notifySubscribers list_name, usermsg
#notifymsg = "#{entry.creator} added `#{entry.val}` (#{entry.type}) to list"
#notifymsg += " #{list_name}. Expires `#{entry.expires}`."
#notifySubscribers list_name, notifymsg
uploadReport = (list_name, list_type, list_style) ->
func_name = 'uploadReport'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
params =
type: list_type
r = buildList list_name, params
s3upload "#{list_name}-#{list_type}-#{list_style}", r[list_style]
s3upload = (filename,body,type='plain') ->
func_name = 's3upload'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
params =
Bucket: s3bucket
Key: PI:KEY:<KEY>END_PI
ContentType: "text/#{type}"
Body: body
s3.putObject params, (err, data) ->
if err
return console.error "#{log_date} #{func_name}: #{err}"
console.log "#{log_date} #{func_name}: #{params.ContentType} #{params.Bucket}:#{params.Key} success"
expireAttackers = ->
func_name = 'expireAttackers'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
console.log "#{log_date} #{func_name} --"
for src of fwdata.attackers
attackSource = fwdata.attackers[src]
# skip if last seen in x duration
expire = moment(attackSource.last).isBefore( moment().subtract(attackExpirationHours,'hour') )
continue unless expire
# skip if currently banned
continue if attackSource['banexpires'] and isBanned attackSource.banexpires
# flush it
console.log "#{moment().format('YYYY-MM-DD HH:mm:ss')} #{func_name}: #{src} "+
"last seen: #{moment(fwdata.attackers[src].last).fromNow()}"
delete fwdata.attackers[src]
preExpireNotify = (list_name) ->
func_name = 'preExpireNotify'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
dt_hour_from_now = moment().add(1,'hours')
params =
expires: 'before'
when: dt_hour_from_now
expire_notify: true
r = buildList list_name, params
return unless r.lines > 0
expiring = r.list
usermsg = "fw: #{list_name} entries will expire soon: " +
"```#{expiring}```"
notifySubscribers list_name, usermsg
expireEntriesFromList = (list_name) ->
func_name = 'expireEntriesFromList'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
unless list_name of fwdata.lists
return console.error "#{log_date} #{func_name}: #{list_name} does not exist"
dt_now = moment()
params =
expires: 'before'
when: dt_now
r = buildList list_name, params
return unless r.lines > 0
deleted = r.list
removequeue = []
list = fwdata.lists[list_name]
for entry in list when moment(entry.expires).isBefore(dt_now)
removequeue.push entry
while removequeue.length > 0
entry = removequeue.shift()
list.splice(list.indexOf(entry), 1)
usermsg = "fw: #{list_name} entries expired and have been removed: " +
"```#{deleted}```"
notifySubscribers list_name, usermsg
writeData()
notifySubscribers = (list_name, usermsg, current_un = false, who = defaultNotifySubscribers) ->
func_name = 'notifySubscribers'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
return console.error "#{log_date} #{func_name}: bad robotRef" unless robotRef
return console.error "#{log_date} #{func_name}: bad list: #{list_name}" unless list_name in list_names
return console.error "#{log_date} #{func_name}: list not created: #{list_name}" unless list_name of fwdata.notify
return console.error "#{log_date} #{func_name}: list empty: #{list_name}" unless isArray fwdata.notify[list_name]
un_list = who if isArray who
un_list = [who] if isString who
un_list = fwdata.notify[list_name] if who == 'all' or who is null
return notifyUsers usermsg, current_un, un_list
notifyUsers = (usermsg, current_un = false, who = null) ->
func_name = 'notifyUsers'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
return console.error "#{log_date} #{func_name}: bad robotRef" unless robotRef
return console.error "#{log_date} #{func_name}: must specify who" if who is null
un_list = who if isArray who
un_list = [who] if isString who
for un in un_list
console.log "#{log_date} #{func_name} #{un}: #{usermsg}"
robotRef.send { room: un }, usermsg unless current_un && un == current_un
return un_list
notifyAdmins = (usermsg, current_un = false, who = defaultNotifyAdmin) ->
func_name = 'notifyAdmins'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
return console.error "#{log_date} #{func_name}: bad robotRef" unless robotRef
un_list = who if isArray who
un_list = [who] if isString who
un_list = hubotAuthAdmin if who == 'all' or who is null
for un in un_list when un.indexOf('U') != 0
console.log "#{log_date} #{func_name} #{un}: #{usermsg}"
robotRef.send { room: un }, usermsg unless current_un && un == current_un
return un_list
listShowAdmins = (robot, msg) ->
func_name = 'listShowAdmins'
fullcmd = String msg.match.shift()
who = msg.envelope.user.name
logmsg = "#{modulename}_#{func_name}: #{who} requested: #{fullcmd}"
robot.logger.info logmsg
msg.reply "#{modulename} admins: #{hubotAuthAdmin.join(', ')}"
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: " +
"provided list of admins"
robot.logger.info logmsg
ruleAddEntryHelp = (robot, msg) ->
func_name = 'ruleAddEntryHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} rule <options>"
""
"Required options:"
" -N, --name Rule name"
" -f, --from From zone, eg. Untrust"
" -t, --to To zone, e.g. DMZ"
" -s, --src Source address"
" -d, --dst Dest address"
" -S, --svc Service, e.g. service-http"
" -a, --app Application, e.g. web-browse"
" -e, --erd URL to Firewall Access Diagram"
""
"Note: if rule name already exists, this will replace it!"
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
ruleAddEntry = (robot, msg) ->
func_name = 'ruleAddEntry'
fullcmd = String msg.match.shift()
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name}: #{who}: #{fullcmd}"
cmd = String msg.match.shift()
return ruleAddEntryHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
console.log "cmd: #{cmd} out: #{JSON.stringify args}"
return ruleAddEntryHelp(robot,msg) if 'h' of args
return ruleAddEntryHelp(robot,msg) if 'help' of args
return unless is2fa msg
keys =
N: 'PI:KEY:<KEY>END_PI'
f: 'from'
t: 'to'
s: 'src'
d: 'dst'
S: 'svc'
a: 'app'
e: 'erd'
for key of keys
if key of args
args[ keys[key] ] = args[key]
delete args[key]
args.requestor = who
result = processRule args, who
unless result is true
errmsg = "Unable to submit request"
errmsg += ":```#{result}```" unless result is false
return msg.send errmsg
msg.send "Submitted rule for review!"
normType = (val) ->
return val.join ", " if isArray val
return val if isString val
return "unable to handle value"
normHttpPrefix = (val) ->
if val.toLowerCase().indexOf('http://') == 0
return val.replace(/http:\/\//i,'')
return val
processRule = (rule, who) ->
func_name = 'processRule'
return false unless isObject rule
required = [
'requestor'
'src'
'dst'
'name'
'erd'
]
for name in required
return "#{func_name}: missing required parameter: #{name}" unless name of rule
unless 'app' of rule or 'svc' of rule
return "#{func_name}: missing required parameter: app or svc"
# convert single values to array
for key in ['from','to','src','dst','app','svc']
continue unless key of rule # skip if not present
rule[key] = [ rule[key] ] unless isArray rule[key]
# check zones
# XXX: check against zone names
# check addresses
# XXX: check against address and address-group objects
# remove slack url prefixes from fqdn style object names
for key in ['src','dst']
newarray = []
for val in rule[key]
newarray.push normHttpPrefix val
rule[key] = newarray
# check app
# XXX: check against app names
# check svc
# XXX: check against service and service-group objects
# add or update request queue
dt_now = moment()
req =
id: "#{who[0..2]}#{dt_now.format('MMDDHHmmss')}"
by: who
type: 'rule'
when: dt_now.format()
request: rule
addUpdateRequestEntry req
return true
addUpdateRequestEntry = (req) ->
return false unless isObject req
return false unless 'id' of req
usermsg = markupRequest req
notifiedAdmins = notifyAdmins usermsg
notifyUsers usermsg, false, req.by unless req.by in notifiedAdmins
fwdata.requests[req.id] = req
writeData()
return true
deleteRequestEntry = (req, res) ->
return false unless isObject req
return false unless isObject res
return false unless 'id' of req
usermsg = markupRequest req, res
notifiedAdmins = notifyAdmins usermsg
notifyUsers usermsg, false, req.by unless req.by in notifiedAdmins
delete fwdata.requests[req.id]
writeData()
return true
markupRequest = (req, res = null) ->
type = req.type[0].toUpperCase() + req.type[1..-1].toLowerCase()
adminmsg = "#{type} requested by #{req.by}."
if res
adminmsg = "#{type} #{res.action} by #{res.by}."
adminmsg += "\n> *Comment* #{res.comment}" if 'comment' of res
adminmsg += "\nRequest metadata:"
for key of req
continue if key in ['request','type']
adminmsg += "\n> *#{key}* #{req[key]}"
adminmsg += "\nRequest:"
entry = req.request
for key of entry
adminmsg += "\n> *#{key}* #{entry[key]}"
return adminmsg
requestQueue_NotifyAdmin_list = (entry, who, comment = null, action = 'requested', notifyList = null) ->
adminmsg = "List #{action} by #{who}."
adminmsg += "\n> *Comment* #{comment}" unless comment is null
for key of entry
adminmsg += "\n> *#{key}* #{entry[key]}"
#adminmsg += "> *Name* #{entry.name}"
#adminmsg += "\n> *Value* #{normType entry.val}"
#adminmsg += "\n> *Type* #{normType entry.type}"
#adminmsg += "\n> *Expires* #{normType entry.expires}"
notifyAdmins adminmsg, false, notifyList
helperListName = (list_name) ->
return false unless isString list_name
return false unless list_name.length > 0
return 'whitelist' if list_name.indexOf('w') == 0
return 'blacklist' if list_name.indexOf('b') == 0
return 'autoban' if list_name.indexOf('a') == 0
if list_name of fwdata.lists
return list_name
return false
listAddEntryHelp = (robot, msg) ->
func_name = 'listAddEntryHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} list add -L <list> -i|-d|-u <value> [options]"
""
"Required options:"
" -L <list> List name; e.g. blacklist"
" -i <ip or cidr> Address or cidr entry, e.g. 127.0.0.1/8"
" -d <domain> Domain entry, e.g. example.com"
" -u <url> URL entry, e.g. example.com/phishing/page123"
""
"Optional:"
" -e <date> Expiration, e.g. +12h, +30d, +6m, +1y, 2021-10-21"
" -r Request; required if not authorized and 2fa enabled"
" -R <reason> Reason for entry, e.g. \"SR 12345\""
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
listAddEntry = (robot, msg) ->
func_name = 'listAddEntry'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
cmd = String msg.match[1]
return listAddEntryHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
console.log "#{log_date} #{func_name}: cmd: #{cmd} out: #{JSON.stringify args}"
return listAddEntryHelp(robot,msg) if 'h' of args
return listAddEntryHelp(robot,msg) if 'help' of args
entry =
creator: who
created: moment().format()
expires: moment().add(1, 'months').format()
unless 'L' of args
return msg.send "#{func_name}: must specify `-L <list>`"
entry.list = helperListName args['L']
unless entry.list
return msg.send "#{func_name}: invalid list: #{args['L']}"
if 'i' of args
addrs = false
if isArray args.i
addrs = args.i
if isString args.i
addrs = [args.i]
addrs = args.i.split(',') if args.i.indexOf(',') > 0
if addrs is false
usermsg = "#{func_name}: invalid ip-address or cidr"
logmsg = "#{modulename}_#{func_name}: #{who} request failed: #{usermsg}"
robot.logger.info logmsg
return msg.send usermsg
for addr in addrs
if extra = addr.match /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})((?:\/\d{1,2}|))$/
if extra[2] isnt '' and extra[2] > -1 and extra[2] < 16
usermsg = "#{func_name}: Blocking addresses with cidr less than /16 not allowed."
logmsg = "#{modulename}_#{func_name}: #{who} request failed: #{usermsg}"
robot.logger.info logmsg
msg.send usermsg unless isAdmin msg, false # no redundant admin notifications
return notifyAdmins logmsg
else
usermsg = "#{func_name}: invalid ip-address or cidr"
logmsg = "#{modulename}_#{func_name}: #{who} request failed: #{usermsg}"
robot.logger.info logmsg
return msg.send usermsg
if UA_Network.contains addr
usermsg = "Blocking addresses in the UA_Network is not allowed. #{safety_fail_note}"
logmsg = "#{modulename}_#{func_name}: #{who} request failed safety check: #{fullcmd}"
robot.logger.info logmsg
msg.send usermsg unless isAdmin msg, false # no redundant admin notifications
return notifyAdmins "#{logmsg}\nReason: #{usermsg}"
entry.type = 'cidr'
entry.val = addrs[0] if addrs.length == 1
entry.vals = addrs if addrs.length > 1
if 'd' of args
domain = normHttpPrefix args.d
for arr in preventDomainBlacklist when domain.toLowerCase().match arr[1]
usermsg = "Blocking `#{arr[0]}` is not allowed. #{safety_fail_note}"
logmsg = "#{modulename}_#{func_name}: #{who} request failed safety check: #{fullcmd}"
robot.logger.info logmsg
msg.send usermsg
return notifyAdmins "#{logmsg}\nReason: #{usermsg}"
entry.type = 'domain'
entry.val = domain
if 'u' of args
url = normHttpPrefix args.u
if url.toLowerCase().indexOf('https://') == 0
return msg.send "#{entry.list}ing of https links not supported."
for arr in preventUrlBlacklist when url.toLowerCase().match arr[1]
usermsg = "Blocking `#{arr[0]}` is not allowed. #{safety_fail_note}"
logmsg = "#{modulename}_#{func_name}: #{who} request failed safety check: #{fullcmd}"
robot.logger.info logmsg
msg.send usermsg
return notifyAdmins "#{logmsg}\nReason: #{usermsg}"
entry.type = 'url'
entry.val = url
unless 'type' of entry
return msg.send "#{modulename}_#{func_name}: must specify `-i <ip>`, `-d <domain>`, or `-u <url>`"
if 'e' of args
expires = args.e
if extra = expires.match /\+(\d+)([a-zA-Z]+)/
n = extra[1]
unit = extra[2]
unless unit in ['h','hours','d','days','w','weeks','M','months','Q','quarters','y','years']
usermsg = "Invalid unit `#{unit}` in expiration `#{expires}`. Use h or hours, d or days, w or weeks, M or months, Q or quarters, y or years."
return msg.send usermsg
entry.expires = moment().add(n,unit).format()
else if moment(expires).isValid()
entry.expires = moment(expires).format()
else
usermsg = "invalid expiration date: #{expires}"
return msg.send usermsg
# reason
if 'R' of args
entry.reason = args['R']
# request
if 'r' of args
dt_now = moment()
req =
id: "#{who[0..2]}#{dt_now.format('MMDDHHmmss')}"
by: who
type: 'list'
when: dt_now.format()
request: entry
addUpdateRequestEntry req
return msg.send "Queued request for review!"
unless isAuthorized msg
usermsg = "or specify `-r` to request listing"
logmsg = "#{modulename}_#{func_name}: #{who} listing failed: #{usermsg}"
robot.logger.info logmsg
return msg.send usermsg
unless is2fa msg
usermsg = "or specify `-r` to request listing"
logmsg = "#{modulename}_#{func_name}: #{who} listing failed: #{usermsg}"
robot.logger.info logmsg
return msg.send usermsg
result = addListEntry entry
if result isnt true
usermsg = "Failed to add to list #{entry.list}. Error: `#{result}`"
msg.send usermsg
usermsg = ''
usermsg += "#{entry.creator} added `#{entry.val}` (#{entry.type}) to *#{entry.list}*." if 'val' of entry
if 'vals' of entry
usermsg += "#{entry.creator} added *#{entry.vals.length}* #{entry.type} entries to *#{entry.list}*."
usermsg += "```#{entry.vals.join ', '}```"
usermsg += " Expires #{entry.expires}." if expires isnt 'undefined'
usermsg += " Reason: ```#{entry.reason}```" if 'reason' of entry
notifySubscribers entry.list, usermsg, who
usermsg += " Change will be applied in < 5 minutes." unless isTerse who
msg.send usermsg
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: "
logmsg += "added entry to #{entry.list}" if 'val' of entry
logmsg += "added #{entry.vals.length} entries to #{entry.list}" if 'vals' of entry
robot.logger.info logmsg
# be terse after the first utterance
fwdata.terse[who] = moment().add(30,'minutes').format()
addListEntry = (entry) ->
func_name = 'addListEntry'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
vals = false
console.log "#{JSON.stringify entry}"
# validate correct list_name
return "parameter not object" unless isObject entry
return "must specify: list" unless 'list' of entry
return "must specify: creator" unless 'creator' or entry
return "must specify: created" unless 'created' of entry
return "must specify: type" unless 'type' of entry
return "must specify: expires" unless 'expires' of entry
vals = [entry.val] if 'val' of entry
vals = entry.vals if 'vals' of entry
return "must specify: val or vals" if vals is false
return "invalid list #{entry.list}" unless entry.list in list_names
logmsg = "#{modulename}_#{func_name}: #{entry.creator} requested:"
logmsg += " #{entry.list} #{entry.type} #{entry.val}" if 'val' of entry
logmsg += " #{entry.list} #{entry.type} #{entry.vals.length} entries" if 'vals' of entry
logmsg += " expires #{moment(entry.expires).format(timefmt)}"
logmsg += " reason #{entry.reason}" if 'reason' of entry
robotRef.logger.info logmsg
fwdata.lists[entry.list] = [] unless entry.list of fwdata.lists
for val in vals
e =
creator: entry.creator
created: entry.created
expires: entry.expires
list: entry.list
type: entry.type
val: val
e.reason = entry.reason if 'reason' of entry
logmsg = "#{modulename}_#{func_name}: #{e.creator} added"
logmsg += " #{e.list} #{e.type} #{e.val}"
logmsg += " expires #{moment(e.expires).fromNow()}"
logmsg += " reason #{e.reason}" if 'reason' of e
robotRef.logger.info logmsg
fwdata.lists[entry.list].push e
writeData()
return true
listUpdateEntryHelp = (robot, msg) ->
func_name = 'listUpdateEntryHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} list update -L <list> -s <searchstring> -e|-R <value>"
""
"Required options:"
" -L <list> List name; e.g. blacklist"
" -s <string> Search string, must only match one entry; e.g. 127.0.0.1"
" -e <expiration> Expiration, e.g. -12h, +36h, -1d, +30d, +6m, +1y, 2021-10-21, etc"
" -R <reason> Reason for entry, e.g. \"SR 12345\""
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
listUpdateEntry = (robot, msg) ->
func_name = 'listUpdateEntry'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name}: #{who}: #{fullcmd}"
cmd = String msg.match[1]
return listUpdateEntryHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
return listUpdateEntryHelp(robot,msg) if 'h' of args
return listUpdateEntryHelp(robot,msg) if 'help' of args
unless 'L' of args
return msg.send "#{func_name}: must specify `-L <list>`"
list_name = helperListName args['L']
unless list_name
return msg.send "#{func_name}: invalid list: #{args['L']}"
unless 's' of args
return msg.send "#{func_name}: must specify `-s <searchstring>`"
l_search = args.s
if l_search.toLowerCase().indexOf('https://') == 0
usermsg = "#{list_name}ing of https links not supported."
return msg.reply usermsg
if l_search.toLowerCase().indexOf('http://') == 0
l_search = l_search.replace(/http:\/\//i,'')
logmsg = "#{modulename}_#{func_name}: #{who} requested: #{list_name} update #{l_search}"
robot.logger.info logmsg
# check for matches
matches = 0
entry = undefined
for e in fwdata.lists[list_name] when e.val.indexOf(l_search) > -1
#console.log "e.type: [#{e.type}] l_search: [#{l_search}] e.val: [#{e.val}]"
if e.val.indexOf(l_search) > -1
#console.log "l_search: [#{l_search}] MATCHED e.val: [#{e.val}]"
matches++
entry = e
if matches != 1
usermsg = "search matched zero or more than a single entry; " +
"improve search term and try again"
return msg.reply usermsg
#console.log e
if 'e' of args
expires = args['e']
if extra = expires.match /(-|\+|)(\d+)([a-zA-Z])/
direction = extra.shift()
n = extra.shift()
unit = extra.shift()
unless unit in ['h','hours','d','days','w','weeks','M','months','Q','quarters','y','years']
usermsg = "Invalid unit `#{unit}` in expiration `#{expires}`. Use h or hours, d or days, w or weeks, M or months, Q or quarters, y or years."
return msg.send usermsg
if direction == '+'
entry.expires = moment(entry.expires).add(n,unit).format()
else if direction == '-'
entry.expires = moment(entry.expires).subtract(n,unit).format()
else
entry.expires = moment().add(n,unit).format()
else if moment(expires).isValid()
entry.expires = moment(expires).format()
else
usermsg = "invalid expiration date: #{expires}"
return msg.send usermsg
entry.expire_notified = false
logmsg = "#{modulename}_#{func_name}: #{who} requested: " +
"#{list_name} #{entry.type} #{entry.val} new expiration #{moment(entry.expires).format(timefmt)}"
robot.logger.info logmsg
usermsg = "#{who} updated `#{entry.val}` in *#{list_name}*.\n"
usermsg += "Old expiration: ```#{old_expiration}```\n"
usermsg += "New expiration: ```#{entry.expires}```\n"
else if 'R' of args
old_reason = 'none'
old_reason = entry.reason if 'reason' of entry
entry.reason = args['R']
logmsg = "#{modulename}_#{func_name}: #{who} requested: " +
"#{list_name} #{entry.type} #{entry.val} update reason: '#{old_reason}' -> '#{entry.reason}'"
robot.logger.info logmsg
usermsg = "#{who} updated `#{entry.val}` in *#{list_name}*.\n"
usermsg += "Old reason: ```#{old_reason}```\n"
usermsg += "New reason: ```#{entry.reason}```\n"
else
usermsg = "must specify new expiration or reason"
return msg.reply usermsg
writeData()
msg.reply usermsg
notifySubscribers list_name, usermsg, who
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: " +
"updated entry in #{list_name}"
robot.logger.info logmsg
listDeleteEntryHelp = (robot, msg) ->
func_name = 'listDeleteEntryHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} list delete -L <list> -s|-i|-d|-u <value> [options]"
""
"Required options:"
" -L <list> List name; e.g. blacklist"
" -i <ip or cidr> Address or cidr entry, e.g. 127.0.0.1/8"
" -d <domain> Domain entry, e.g. example.com"
" -u <url> URL entry, e.g. example.com/phishing/page123"
""
"Optional:"
" -r Request; required if not authorized and 2fa enabled"
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
listDeleteEntry = (robot, msg) ->
func_name = 'listDeleteEntry'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name} #{who} requested: #{fullcmd}"
cmd = String msg.match[1]
return listDeleteEntryHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
return listDeleteEntryHelp(robot,msg) if 'h' of args
return listDeleteEntryHelp(robot,msg) if 'help' of args
q =
axis: 0
unless 'L' of args
return msg.send "#{func_name}: must specify `-L <list>`"
q.list = helperListName args['L']
unless q.list
return msg.send "#{func_name}: invalid list: #{q.list}"
required = 0
if 's' of args
required++
q.search = args.s
if q.search.toLowerCase().indexOf('https://') == 0
return msg.reply "https links not supported"
if args.s.toLowerCase().indexOf('http://') == 0
q.search = args.s.replace(/http:\/\//i,'')
q.axis += 1
if 'i' of args
required++
addrs = false
if isArray args.i
addrs = args.i
if isString args.i
addrs = [args.i]
addrs = args.i.split(',') if args.i.indexOf(',') > 0
if addrs is false
usermsg = "#{func_name}: invalid ip-address or cidr"
logmsg = "#{modulename}_#{func_name}: #{who} request failed: #{usermsg}"
robot.logger.info logmsg
return msg.send usermsg
q.axis += 2
q.type = 'cidr'
q.addrs = addrs
# display help unless one of the rquired parameter is specified
return listDeleteEntryHelp(robot,msg) unless required > 0
searched = 0
deleted = []
new_listdata = []
listdata = fwdata.lists[q.list]
deleted.push sprintf displayfmt, 'Type', 'Value', 'Expiration', 'Creator', 'Reason'
for e in listdata
axis = 0
#console.log "#{log_date} #{func_name}: #{JSON.stringify e}"
# if not a match, add it to the keepers
if 'type' of q
test = q.type == e.type
#console.log "#{log_date} #{func_name}: TYPE e.type|#{e.type} == q.type|#{q.type} = test|#{test}"
if test
axis++
#console.log "#{log_date} #{func_name}: incremented axis: #{axis}"
if 'search' of q
test = e.val.indexOf(q.search) == -1
#console.log "#{log_date} #{func_name}: SEARCH e.val|#{e.val} q.search|#{q.search} test|#{test}"
if test
axis++
#console.log "#{log_date} #{func_name}: incremented axis: #{axis}"
if 'addrs' of q
test = e.val in q.addrs
#console.log "#{log_date} #{func_name}: ADDRS e.val|#{e.val} q.addrs|#{q.addrs} test|#{test}"
if test
axis++
#console.log "#{log_date} #{func_name}: incremented axis: #{axis}"
if axis < q.axis
#console.log "#{log_date} #{func_name}: axis|#{axis} < q.axis|#{q.axis} = NOT ENOUGH AXIS, keeping entry"
new_listdata.push e
continue
#console.log "#{log_date} #{func_name}: axis|#{axis} >= q.axis|#{q.axis} = ENOUGH AXIS, deleting entry"
expires = moment(e.expires)
#if expires.isBefore() # now
# new_listdata.push e
# continue
# display
reason = ''
if 'reason' of e
unless e.reason.indexOf("\n") > 0
reason = e.reason
else
reason = e.reason.split("\n").shift().substring(0,20)
deleted.push sprintf displayfmt, e.type, e.val,
expires.fromNow(), e.creator, reason
deltaN = listdata.length - new_listdata.length
if deltaN > 0
usermsg = "#{who} removed *#{deltaN}* entries from *#{q.list}*"
usermsg += "```"+ deleted.join("\n") + "```"
fwdata.lists[q.list] = new_listdata
writeData()
else
usermsg = "#{q.list} delete request did not match any records."
msg.send usermsg
logmsg = "#{modulename}_#{func_name} #{who} response: " +
"removed #{deltaN} entries from #{q.list}"
robot.logger.info logmsg
if deltaN > 0
notifySubscribers q.list, usermsg, who
listShow = (robot, msg) ->
func_name = 'listShow'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name} #{who} requested: #{fullcmd}"
list_name = helperListName String(msg.match[1])
unless list_name
return msg.send "#{func_name}: invalid list: #{list_name}"
l_type = false
l_search = false
if msg.match[2]?
l_search = String(msg.match[2])
unless list_name of fwdata.lists and fwdata.lists[list_name].length > 0
return msg.send "No entries on list #{list_name}."
params = {}
params.type = l_type if l_type
params.search = l_search if l_search
r = buildList list_name, params
maxLinesViaChat = 10
if r.lines == 1
msg.send r.single
if r.lines > 1 and r.lines <= maxLinesViaChat
msg.send "*#{list_name}* #{r.lines} entries.\n```#{r.list}```"
if r.lines > maxLinesViaChat
msg.send "*#{list_name}* #{r.lines} entries.\n"+
">List too long to display through chat. Try this:\n"+
">https://s3-us-west-2.amazonaws.com/"+
"#{s3bucket}/#{s3pathPrefix}/#{list_name}-all-list"
logmsg = "#{modulename}_#{func_name}: robot responded to #{msg.envelope.user.name}: " +
"displayed #{list_name} items and expirations"
robot.logger.info logmsg
requestShowHelp = (robot, msg) ->
func_name = 'requestShowHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} request show -a|-i <id>|-n <name>|-t <type>"
""
"Options:"
" -a All requests"
" -i Request id"
" -n Requestor name"
" -t Request type"
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
requestShow = (robot, msg) ->
func_name = 'requestShow'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name}: #{who}: #{fullcmd}"
cmd = String msg.match[1]
return requestShowHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
return requestShowHelp(robot,msg) if 'h' of args
return requestShowHelp(robot,msg) if 'help' of args
if 'i' of args
unless args.i of fwdata.requests
msg.send "#{func_name}: request does not exist: id=#{args.i}"
usermsg = markupRequest fwdata.requests[args.i]
msg.send usermsg
logmsg = "#{modulename}_#{func_name}: responded to #{who}: " +
"displaying id #{args.i}"
return robot.logger.info logmsg
out = ''
requestCount = 0
for key of fwdata.requests
req = fwdata.requests[key]
continue if 'u' of args and req.by isnt args.u
continue if 't' of args and req.type isnt args.t
requestCount += 1
out += "type=#{req.type} id=#{req.id} by=#{req.by} when=#{req.when}\n"
if requestCount > 0
msg.send "Requests:\n```#{out}```"
else
msg.send "No requests in queue; nice work!"
logmsg = "#{modulename}_#{func_name}: responded to #{who}: " +
"displayed #{requestCount} requests"
robot.logger.info logmsg
requestApproveHelp = (robot, msg) ->
func_name = 'requestApproveHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} request approve -i <id> -m \"<message>\""
""
"Required options:"
" -i Request id"
" -m Approval message"
""
"Note: immediate upon approval the request will be applied!"
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
requestApprove = (robot, msg) ->
func_name = 'requestApprove'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name}: #{who}: #{fullcmd}"
cmd = String msg.match[1]
return requestDeclineHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
return requestDeclineHelp(robot,msg) if 'h' of args
return requestDeclineHelp(robot,msg) if 'help' of args
console.log "#{log_date} #{func_name}: cmd: #{cmd} out: #{JSON.stringify args}"
return unless is2fa msg
unless 'i' of args
return msg.send "#{func_name}: missing required parameter: `-i <id>`"
id = args.i
unless 'm' of args
return msg.send "#{func_name}: missing required parameter: `-m \"<msg>\"`"
message = args.m
unless id of fwdata.requests
return msg.send "#{func_name}: request not found: id=#{id}"
req = fwdata.requests[id]
result = false
if req.type is 'list'
result = addListEntry(req.request)
else
result = "unable to process request type: #{req.type}"
unless result is true
return msg.send "Failed to apply #{req.type}. Error: ```#{result}```"
res =
by: who
action: 'approved'
comment: args.m
deleteRequestEntry req, res
#msg.send "Request #{id} approved with message: ```#{message}```"
logmsg = "#{modulename}_#{func_name}: responded to #{who}: " +
"request #{id} approved with message: #{message}"
robot.logger.info logmsg
requestDeclineHelp = (robot, msg) ->
func_name = 'requestDeclineHelp'
who = msg.envelope.user.name
arr = [
"#{modulename} request decline -i <id> -m <message>"
""
"Required options:"
" -i Request id"
" -m Decline message"
""
"Note: immediate upon decline the request is removed and notification sent."
]
output = arr.join "\n"
msg.send "```#{output}```"
robot.logger.info "#{modulename}_#{func_name}: #{who}: displayed help"
requestDecline = (robot, msg) ->
func_name = 'requestDecline'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
fullcmd = String msg.match[0]
who = msg.envelope.user.name
robot.logger.info "#{modulename}_#{func_name}: #{who}: #{fullcmd}"
cmd = String msg.match[1]
return requestDeclineHelp(robot,msg) if cmd is 'undefined'
args = parse cmd
args = {} unless isObject args
return requestDeclineHelp(robot,msg) if 'h' of args
return requestDeclineHelp(robot,msg) if 'help' of args
console.log "#{log_date} #{func_name}: cmd: #{cmd} out: #{JSON.stringify args}"
return unless is2fa msg
unless 'i' of args
return msg.send "#{func_name}: missing required parameter: `-i <id>`"
id = args.i
unless 'm' of args
return msg.send "#{func_name}: missing required parameter: `-m \"<msg>\"`"
message = args.m
unless id of fwdata.requests
return msg.send "#{func_name}: request not found: id=#{id}"
req = fwdata.requests[id]
res =
by: who
action: 'declined'
comment: args.m
deleteRequestEntry req, res
#msg.send "Request #{id} declined with message: ```#{message}```"
logmsg = "#{modulename}_#{func_name}: responded to #{who}: " +
"request #{id} declined with message: #{message}"
robot.logger.info logmsg
buildList = (list_name, params = {}) ->
func_name = 'buildList'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
lines = 0 # entries
out_terse = '' # string
delete params.type if 'type' of params and params.type is 'all'
out_list = sprintf "#{displayfmt}\n", 'Type', 'Value', 'Expiration', 'Creator', 'Reason'
for e in fwdata.lists[list_name]
bool_expires = false
dt_expires = moment(e.expires)
if 'expires' of params
dt = moment() unless 'when' of params
dt = moment(params.when) if 'when' of params
bool_expires = dt_expires.isBefore(dt)
bool_expires = dt_expires.isBefore(dt) if params.expires == 'before' and dt_expires.isBefore(dt)
bool_expires = dt_expires.isAfter(dt) if params.expires == 'after' and dt_expires.isAfter(dt)
#console.log "#{log_date} #{func_name} #{dt_expires.fromNow()} / #{dt_expires.format()} #{params.expires} #{dt.format()} #{bool_expires}"
continue unless bool_expires
else
continue if dt_expires.isBefore() # skip expired
continue if 'type' of params and params.type != e.type
continue if 'search' of params and e.val.indexOf(params.search) == -1
if 'expire_notify' of params # if pre-expiration notify, only do it once
continue if 'expire_notified' of e and e.expire_notified
e.expire_notified = true
reason = ''
reason = e.reason if 'reason' of e
if reason.indexOf("\n") > 0
reason = e.reason.split("\n").shift().substring(0,20)
vals = [e.val] if 'val' of e
vals = e.vals if 'vals' of e
for val in vals
lines++
out_terse += "#{val}\n"
out_list += sprintf "#{displayfmt}\n", e.type, val, dt_expires.fromNow(), e.creator, reason
out_single = "#{e.creator} added `#{val}` (#{e.type}) to list"
out_single += " #{list_name}. Expires #{moment(e.expires).fromNow()}."
out_single += " Reason: ```#{e.reason}```" if 'reason' of e
output =
single: out_single
terse: out_terse
list: out_list
lines: lines
return output
listSubscribe = (robot, msg) ->
func_name = 'listSubscribe'
user = msg.envelope.user
list_name = msg.match[1]
list_name = 'whitelist' if list_name.indexOf('w') == 0
list_name = 'blacklist' if list_name.indexOf('b') == 0
list_name = 'autoban' if list_name.indexOf('a') == 0
who = user.name
who = msg.match[2] if msg.match[2]
logmsg = "#{modulename}_#{func_name}: #{user.name} requested: subscribe #{list_name} #{who}"
robot.logger.info logmsg
fwdata.notify[list_name] = [] unless list_name of fwdata.notify
fwdata.notify[list_name].push who unless who in fwdata.notify[list_name]
usermsg = "Added #{who} to list #{list_name}."
msg.send usermsg
logmsg = "#{modulename}_#{func_name}: robot responded to #{user.name}: " +
"added #{who} to list #{list_name}"
robot.logger.info logmsg
writeData()
listUnsubscribe = (robot, msg) ->
func_name = 'listUnsubscribe'
user = msg.envelope.user
list_name = msg.match[1]
list_name = 'whitelist' if list_name.indexOf('w') == 0
list_name = 'blacklist' if list_name.indexOf('b') == 0
list_name = 'autoban' if list_name.indexOf('a') == 0
who = msg.envelope.user.name
who = msg.match[2] if msg.match[2]
logmsg = "#{modulename}_#{func_name}: #{user.name} requested: unsubscribe #{list_name} #{who}"
robot.logger.info logmsg
unless list_name of fwdata.notify
usermsg = "No such list #{list_name}."
return msg.reply usermsg
n = fwdata.notify[list_name].indexOf(who)
unless n > -1
usermsg = "`#{who}` not a member of list #{list_name}."
return msg.reply usermsg
fwdata.notify[list_name].splice(n, 1)
usermsg = "Removed #{who} from list #{list_name}."
msg.send usermsg
logmsg = "#{modulename}_#{func_name}: robot responded to #{user.name}: " +
"removed #{who} from list #{list_name}"
robot.logger.info logmsg
writeData()
listShowSubscribers = (robot, msg) ->
func_name = 'listShowSubscribers'
who = msg.envelope.user.name
list_name = ''
list_name = msg.match[1] if msg.match[1]
list_name = 'whitelist' if list_name.indexOf('w') == 0
list_name = 'blacklist' if list_name.indexOf('b') == 0
list_name = 'autoban' if list_name.indexOf('a') == 0
logmsg = "#{modulename}_#{func_name}: #{who} requested subscribers"
logmsg += " for list #{list_name}" if list_name
robot.logger.info logmsg
usermsg = ""
for list of fwdata.notify
continue if list_name and list != list_name
continue unless isArray(fwdata.notify[list]) and fwdata.notify[list].length > 0
usermsg += "Subscribers for #{list}: `"+ fwdata.notify[list].join('`, `') + "`\n\n"
if usermsg
msg.reply usermsg
logmsg = "#{modulename}_#{func_name}: displayed subscribers to #{who}"
robot.logger.info logmsg
httpGetHelp = (robot, req, res) ->
func_name = 'httpGetHelp'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
clientip = req.connection.remoteAddress || req.socket.remoteAddress ||
req.connection.socket.remoteAddress
logmsg = "#{modulename}_#{func_name}: web request from #{clientip}"
robot.logger.info logmsg
arr = ["<html>\n<body>\n<pre>\n"]
for list in list_names
for type in list_types
arr.push "<a href='#{list}/#{type}'>#{list}/#{type}</a>\n"
arr.push "</pre>\n</body>\n</html>\n"
res.setHeader 'content-type', 'text/html'
res.end arr.join "\n"
logmsg = "#{modulename}_#{func_name}: robot responded to web request"
robot.logger.info logmsg
httpGetList = (robot, req, res, list_name, list_type) ->
func_name = 'httpGetList'
log_date = moment().format('YYYY-MM-DD HH:mm:ss')
clientip = req.connection.remoteAddress || req.socket.remoteAddress ||
req.connection.socket.remoteAddress
rememberCheckin clientip, list_name, list_type
logmsg = "#{modulename}_#{func_name}: web request from #{clientip}: get #{list_type} #{list_name}"
robot.logger.info logmsg
params =
type: list_type
r = buildList list_name, params
content = '# nothing here yet! #'
content = r.terse if r.lines > 0
res.setHeader 'content-type', 'text/plain'
res.end content
logmsg = "#{modulename}_#{func_name}: robot responded to web request: sent #{list_type} #{list_name}"
robot.logger.info logmsg
listShowFirewallCheckins = (robot, msg) ->
who = msg.envelope.user.name
logmsg = "#{modulename}_#{func_name}: #{who} requested: checkins"
robot.logger.info logmsg
arr = []
for obj in fwdata.firewalls
obj.checkin = moment(obj.checkin) if typeof(obj.checkin) is 'string'
arr.push sprintf '%-16s %-10s %-10s %-15s', obj.name, obj.list, obj.type,
obj.checkin.fromNow()
usermsg = "Expected firewall check times: ```"+ arr.join("\n") + "```"
msg.send usermsg
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: checkins"
robot.logger.info logmsg
rememberCheckin = (clientip,list_name,l_type) ->
return unless fwname = fwnames[clientip] # skip non-firewalls
for obj in fwdata.firewalls
if obj.ip is clientip and obj.type is l_type and obj.list is list_name
obj.checkin = moment().add(5,'minutes')
writeData()
return
# otherwise create new object
obj =
ip: clientip
name: fwname
list: list_name
type: l_type
checkin: moment().add(5,'minutes')
fwdata.firewalls.push obj
if fwdata.firewalls.length > 1
fwdata.firewalls = fwdata.firewalls.sort (a,b) ->
sortBy('name',a,b) or sortBy('list',a,b) or sortBy('type',a,b)
writeData()
moduleHelp = (robot, msg) ->
func_name = 'moduleHelp'
who = msg.envelope.user.name
admin = isAdmin msg
arr = [
"#{modulename} list show <list> [searchterm]"
"#{modulename} list add -h"
"#{modulename} list del -h"
"#{modulename} list update -h"
"#{modulename} list subscribe <list> [username] - subscribe to change notifications"
"#{modulename} list unsubscribe <list> [username]"
"#{modulename} list subscribers [list]"
"#{modulename} rule <options>"
]
arr.push "#{modulename} request show [options]" if admin
arr.push "#{modulename} request approve <options>" if admin
out = arr.join "\n"
msg.send "```#{out}```"
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: " +
"displayed #{modulename} help"
robot.logger.info logmsg
listHelp = (robot, msg) ->
func_name = 'listHelp'
who = msg.envelope.user.name
admin = isAdmin msg
arr = [
"#{modulename} list show <list> [searchterm]"
"#{modulename} list add -h"
"#{modulename} list del -h"
"#{modulename} list update -h"
"#{modulename} list subscribe <list> [username] - subscribe to change notifications"
"#{modulename} list unsubscribe <list> [username]"
"#{modulename} list subscribers [list]"
]
out = arr.join "\n"
msg.send "```#{out}```"
logmsg = "#{modulename}_#{func_name}: robot responded to #{who}: " +
"displayed #{modulename} help"
robot.logger.info logmsg
writeData = ->
func_name = 'writeData'
fs.writeFileSync data_file, JSON.stringify(fwdata), 'utf-8'
logmsg = "#{modulename}_#{func_name}: wrote #{data_file}"
robotRef.logger.info logmsg
module.exports = (robot) ->
robotRef = robot
if process.env.HUBOT_GRAYLOG_URL && process.env.HUBOT_GRAYLOG_TOKEN
glApi = robot.http process.env.HUBOT_GRAYLOG_URL
glApi.auth process.env.HUBOT_GRAYLOG_TOKEN, 'token'
glApi.path 'api/search/universal/relative'
glApi.header 'Accept', 'application/json'
else
console.warn "#{modulename}: HUBOT_GRAYLOG_URL and HUBOT_GRAYLOG_TOKEN" +
" environment variables not set."
setTimeout oneMinuteWorker, 5 * 1000
setTimeout fiveMinuteWorker, 15 * 1000
try
fwdata = JSON.parse fs.readFileSync data_file, 'utf-8'
robot.logger.info "#{modulename}: read #{data_file}" if robot.logger
fwdata = {} unless isObject fwdata
fwdata['notify'] = {} unless isObject fwdata['notify']
fwdata['lists'] = {} unless isObject fwdata['lists']
fwdata['firewalls'] = [] unless isArray fwdata['firewalls']
fwdata['terse'] = {} unless isObject fwdata['terse']
fwdata['attackers'] = {} unless isObject fwdata['attackers']
fwdata['requests'] = {} unless isObject fwdata['requests']
catch error
unless error.code is 'ENOENT'
console.log("#{modulename}: unable to read #{data_file}: ", error)
robot.router.get "/#{robot.name}/#{modulename}", (req, res) ->
return httpGetHelp robot, req, res
robot.router.get "/#{robot.name}/#{modulename}/blacklist/url", (req, res) ->
return httpGetList robot, req, res, 'blacklist', 'url'
robot.router.get "/#{robot.name}/#{modulename}/blacklist/cidr", (req, res) ->
return httpGetList robot, req, res, 'blacklist', 'cidr'
robot.router.get "/#{robot.name}/#{modulename}/blacklist/domain", (req, res) ->
return httpGetList robot, req, res, 'blacklist', 'domain'
robot.router.get "/#{robot.name}/#{modulename}/whitelist/url", (req, res) ->
return httpGetList robot, req, res, 'whitelist', 'url'
robot.router.get "/#{robot.name}/#{modulename}/whitelist/cidr", (req, res) ->
return httpGetList robot, req, res, 'whitelist', 'cidr'
robot.router.get "/#{robot.name}/#{modulename}/whitelist/domain", (req, res) ->
return httpGetList robot, req, res, 'whitelist', 'domain'
robot.router.get "/#{robot.name}/#{modulename}/autoban/cidr", (req, res) ->
return httpGetList robot, req, res, 'autoban', 'cidr'
robot.respond /(?:firewall|fw)(?: help| h|)$/, (msg) ->
return moduleHelp robot, msg
robot.respond /(?:firewall|fw) list(?: help| h|)$/, (msg) ->
return listHelp robot, msg
robot.respond /(?:firewall|fw) list show admins$/i, (msg) ->
return listShowAdmins robot, msg
robot.respond /(?:firewall|fw) list show (?:checkins|firewalls|fw)$/i, (msg) ->
return listShowFirewallCheckins robot, msg
robot.respond /(?:firewall|fw) list subscribers(?: (.+)|)$/i, (msg) ->
return listShowSubscribers robot, msg
robot.respond /(?:firewall|fw) list show ([^ ]+)(?: (.+)|)$/i, (msg) ->
return listShow robot, msg
robot.respond /(?:firewall|fw) list (?:add|a)(?: (.+)|)$/i, (msg) ->
return listAddEntry robot, msg
robot.respond /(?:firewall|fw) list (?:delete|del|d)(?: (.+)|)$/i, (msg) ->
return unless isAuthorized msg
return unless is2fa msg
return listDeleteEntry robot, msg
robot.respond /(?:firewall|fw) list (?:update|upd|up|u)(?: (.+)|)$/i, (msg) ->
return unless isAuthorized msg
return unless is2fa msg
return listUpdateEntry robot, msg
robot.respond /(?:firewall|fw) list (?:subscribe|sub) ([^ ]+)(?: ([^ ]+)|)$/i, (msg) ->
return listSubscribe robot, msg
robot.respond /(?:firewall|fw) list (?:unsubscribe|unsub) ([^ ]+)(?: ([^ ]+)|)$/i, (msg) ->
return listUnsubscribe robot, msg
robot.respond /(?:firewall|fw) (?:rule|r)(?: (.+)|)$/i, (msg) ->
return unless isAuthorized msg
return ruleAddEntry robot, msg
robot.respond /(?:firewall|fw) (?:request|req) show(?: (.+)|)$/i, (msg) ->
return unless isAdmin msg
return requestShow robot, msg
robot.respond /(?:firewall|fw) (?:request|req) (?:approve|app|a)(?: (.+)|)$/i, (msg) ->
return unless isAdmin msg
return requestApprove robot, msg
robot.respond /(?:firewall|fw) (?:request|req) (?:decline|dec|d)(?: (.+)|)$/i, (msg) ->
return unless isAdmin msg
return requestDecline robot, msg
|
[
{
"context": "reeze the time for these tests\n\t\t@stubbedToken = \"mock-token\"\n\t\t@callback = sinon.stub()\n\t\t@OneTimeTokenHandle",
"end": 505,
"score": 0.9831242561340332,
"start": 495,
"tag": "PASSWORD",
"value": "mock-token"
},
{
"context": "foreEach ->\n\t\t\t\t@OneTimeTokenHandler.getNewToken 'password', 'mock-data-to-store', @callback\n\n\t\t\tit \"should ",
"end": 1011,
"score": 0.9978925585746765,
"start": 1003,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "\t\t\t\t@OneTimeTokenHandler.getNewToken 'password', 'mock-data-to-store', @callback\n\n\t\t\tit \"should insert a generated tok",
"end": 1033,
"score": 0.6361812949180603,
"start": 1015,
"tag": "PASSWORD",
"value": "mock-data-to-store"
},
{
"context": "foreEach ->\n\t\t\t\t@OneTimeTokenHandler.getNewToken 'password', 'mock-data-to-store', { expiresIn: 42 }, @callb",
"end": 1587,
"score": 0.9965584874153137,
"start": 1579,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "\t\t\t\t@OneTimeTokenHandler.getNewToken 'password', 'mock-data-to-store', { expiresIn: 42 }, @callback\n\n\t\t\tit \"should ins",
"end": 1609,
"score": 0.809305727481842,
"start": 1591,
"tag": "PASSWORD",
"value": "mock-data-to-store"
},
{
"context": "\t\t.calledWith({\n\t\t\t\t\t\tuse: 'password'\n\t\t\t\t\t\ttoken: @stubbedToken,\n\t\t\t\t\t\tcreatedAt: new Date(),\n\t\t\t\t\t\texpir",
"end": 1788,
"score": 0.5559830665588379,
"start": 1783,
"tag": "USERNAME",
"value": "@stub"
},
{
"context": "\t@OneTimeTokenHandler.getValueFromTokenAndExpire 'password', 'mock-token', @callback\n\n\t\t\tit 'should expire t",
"end": 2291,
"score": 0.9283432364463806,
"start": 2283,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "uery: {\n\t\t\t\t\t\t\tuse: 'password'\n\t\t\t\t\t\t\ttoken: 'mock-token',\n\t\t\t\t\t\t\texpiresAt: { $gt: new Date() },\n\t\t\t\t\t\t\tu",
"end": 2466,
"score": 0.5518474578857422,
"start": 2461,
"tag": "PASSWORD",
"value": "token"
},
{
"context": "\t@OneTimeTokenHandler.getValueFromTokenAndExpire 'password', 'mock-token', @callback\n\n\t\t\tit 'should return a",
"end": 2932,
"score": 0.9322745203971863,
"start": 2924,
"tag": "PASSWORD",
"value": "password"
}
] | test/unit/coffee/Security/OneTimeTokenHandlerTests.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/Security/OneTimeTokenHandler"
expect = require("chai").expect
Errors = require "../../../../app/js/Features/Errors/Errors"
tk = require("timekeeper")
describe "OneTimeTokenHandler", ->
beforeEach ->
tk.freeze Date.now() # freeze the time for these tests
@stubbedToken = "mock-token"
@callback = sinon.stub()
@OneTimeTokenHandler = SandboxedModule.require modulePath, requires:
"settings-sharelatex":@settings
"logger-sharelatex": log:->
"crypto": randomBytes: () => @stubbedToken
"../Errors/Errors": Errors
"../../infrastructure/mongojs": db: @db = tokens: {}
afterEach ->
tk.reset()
describe "getNewToken", ->
beforeEach ->
@db.tokens.insert = sinon.stub().yields()
describe 'normally', ->
beforeEach ->
@OneTimeTokenHandler.getNewToken 'password', 'mock-data-to-store', @callback
it "should insert a generated token with a 1 hour expiry", ->
@db.tokens.insert
.calledWith({
use: 'password'
token: @stubbedToken,
createdAt: new Date(),
expiresAt: new Date(Date.now() + 60 * 60 * 1000)
data: 'mock-data-to-store'
})
.should.equal true
it 'should call the callback with the token', ->
@callback.calledWith(null, @stubbedToken).should.equal true
describe 'with an optional expiresIn parameter', ->
beforeEach ->
@OneTimeTokenHandler.getNewToken 'password', 'mock-data-to-store', { expiresIn: 42 }, @callback
it "should insert a generated token with a custom expiry", ->
@db.tokens.insert
.calledWith({
use: 'password'
token: @stubbedToken,
createdAt: new Date(),
expiresAt: new Date(Date.now() + 42 * 1000)
data: 'mock-data-to-store'
})
.should.equal true
it 'should call the callback with the token', ->
@callback.calledWith(null, @stubbedToken).should.equal true
describe "getValueFromTokenAndExpire", ->
describe 'successfully', ->
beforeEach ->
@db.tokens.findAndModify = sinon.stub().yields(null, { data: 'mock-data' })
@OneTimeTokenHandler.getValueFromTokenAndExpire 'password', 'mock-token', @callback
it 'should expire the token', ->
@db.tokens.findAndModify
.calledWith({
query: {
use: 'password'
token: 'mock-token',
expiresAt: { $gt: new Date() },
usedAt: { $exists: false }
},
update: {
$set: { usedAt: new Date() }
}
})
.should.equal true
it 'should return the data', ->
@callback.calledWith(null, 'mock-data').should.equal true
describe 'when a valid token is not found', ->
beforeEach ->
@db.tokens.findAndModify = sinon.stub().yields(null, null)
@OneTimeTokenHandler.getValueFromTokenAndExpire 'password', 'mock-token', @callback
it 'should return a NotFoundError', ->
@callback
.calledWith(sinon.match.instanceOf(Errors.NotFoundError))
.should.equal true
| 47441 | should = require('chai').should()
SandboxedModule = require('sandboxed-module')
assert = require('assert')
path = require('path')
sinon = require('sinon')
modulePath = path.join __dirname, "../../../../app/js/Features/Security/OneTimeTokenHandler"
expect = require("chai").expect
Errors = require "../../../../app/js/Features/Errors/Errors"
tk = require("timekeeper")
describe "OneTimeTokenHandler", ->
beforeEach ->
tk.freeze Date.now() # freeze the time for these tests
@stubbedToken = "<PASSWORD>"
@callback = sinon.stub()
@OneTimeTokenHandler = SandboxedModule.require modulePath, requires:
"settings-sharelatex":@settings
"logger-sharelatex": log:->
"crypto": randomBytes: () => @stubbedToken
"../Errors/Errors": Errors
"../../infrastructure/mongojs": db: @db = tokens: {}
afterEach ->
tk.reset()
describe "getNewToken", ->
beforeEach ->
@db.tokens.insert = sinon.stub().yields()
describe 'normally', ->
beforeEach ->
@OneTimeTokenHandler.getNewToken '<PASSWORD>', '<PASSWORD>', @callback
it "should insert a generated token with a 1 hour expiry", ->
@db.tokens.insert
.calledWith({
use: 'password'
token: @stubbedToken,
createdAt: new Date(),
expiresAt: new Date(Date.now() + 60 * 60 * 1000)
data: 'mock-data-to-store'
})
.should.equal true
it 'should call the callback with the token', ->
@callback.calledWith(null, @stubbedToken).should.equal true
describe 'with an optional expiresIn parameter', ->
beforeEach ->
@OneTimeTokenHandler.getNewToken '<PASSWORD>', '<PASSWORD>', { expiresIn: 42 }, @callback
it "should insert a generated token with a custom expiry", ->
@db.tokens.insert
.calledWith({
use: 'password'
token: @stubbedToken,
createdAt: new Date(),
expiresAt: new Date(Date.now() + 42 * 1000)
data: 'mock-data-to-store'
})
.should.equal true
it 'should call the callback with the token', ->
@callback.calledWith(null, @stubbedToken).should.equal true
describe "getValueFromTokenAndExpire", ->
describe 'successfully', ->
beforeEach ->
@db.tokens.findAndModify = sinon.stub().yields(null, { data: 'mock-data' })
@OneTimeTokenHandler.getValueFromTokenAndExpire '<PASSWORD>', 'mock-token', @callback
it 'should expire the token', ->
@db.tokens.findAndModify
.calledWith({
query: {
use: 'password'
token: 'mock-<PASSWORD>',
expiresAt: { $gt: new Date() },
usedAt: { $exists: false }
},
update: {
$set: { usedAt: new Date() }
}
})
.should.equal true
it 'should return the data', ->
@callback.calledWith(null, 'mock-data').should.equal true
describe 'when a valid token is not found', ->
beforeEach ->
@db.tokens.findAndModify = sinon.stub().yields(null, null)
@OneTimeTokenHandler.getValueFromTokenAndExpire '<PASSWORD>', 'mock-token', @callback
it 'should return a NotFoundError', ->
@callback
.calledWith(sinon.match.instanceOf(Errors.NotFoundError))
.should.equal true
| 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/Security/OneTimeTokenHandler"
expect = require("chai").expect
Errors = require "../../../../app/js/Features/Errors/Errors"
tk = require("timekeeper")
describe "OneTimeTokenHandler", ->
beforeEach ->
tk.freeze Date.now() # freeze the time for these tests
@stubbedToken = "PI:PASSWORD:<PASSWORD>END_PI"
@callback = sinon.stub()
@OneTimeTokenHandler = SandboxedModule.require modulePath, requires:
"settings-sharelatex":@settings
"logger-sharelatex": log:->
"crypto": randomBytes: () => @stubbedToken
"../Errors/Errors": Errors
"../../infrastructure/mongojs": db: @db = tokens: {}
afterEach ->
tk.reset()
describe "getNewToken", ->
beforeEach ->
@db.tokens.insert = sinon.stub().yields()
describe 'normally', ->
beforeEach ->
@OneTimeTokenHandler.getNewToken 'PI:PASSWORD:<PASSWORD>END_PI', 'PI:PASSWORD:<PASSWORD>END_PI', @callback
it "should insert a generated token with a 1 hour expiry", ->
@db.tokens.insert
.calledWith({
use: 'password'
token: @stubbedToken,
createdAt: new Date(),
expiresAt: new Date(Date.now() + 60 * 60 * 1000)
data: 'mock-data-to-store'
})
.should.equal true
it 'should call the callback with the token', ->
@callback.calledWith(null, @stubbedToken).should.equal true
describe 'with an optional expiresIn parameter', ->
beforeEach ->
@OneTimeTokenHandler.getNewToken 'PI:PASSWORD:<PASSWORD>END_PI', 'PI:PASSWORD:<PASSWORD>END_PI', { expiresIn: 42 }, @callback
it "should insert a generated token with a custom expiry", ->
@db.tokens.insert
.calledWith({
use: 'password'
token: @stubbedToken,
createdAt: new Date(),
expiresAt: new Date(Date.now() + 42 * 1000)
data: 'mock-data-to-store'
})
.should.equal true
it 'should call the callback with the token', ->
@callback.calledWith(null, @stubbedToken).should.equal true
describe "getValueFromTokenAndExpire", ->
describe 'successfully', ->
beforeEach ->
@db.tokens.findAndModify = sinon.stub().yields(null, { data: 'mock-data' })
@OneTimeTokenHandler.getValueFromTokenAndExpire 'PI:PASSWORD:<PASSWORD>END_PI', 'mock-token', @callback
it 'should expire the token', ->
@db.tokens.findAndModify
.calledWith({
query: {
use: 'password'
token: 'mock-PI:PASSWORD:<PASSWORD>END_PI',
expiresAt: { $gt: new Date() },
usedAt: { $exists: false }
},
update: {
$set: { usedAt: new Date() }
}
})
.should.equal true
it 'should return the data', ->
@callback.calledWith(null, 'mock-data').should.equal true
describe 'when a valid token is not found', ->
beforeEach ->
@db.tokens.findAndModify = sinon.stub().yields(null, null)
@OneTimeTokenHandler.getValueFromTokenAndExpire 'PI:PASSWORD:<PASSWORD>END_PI', 'mock-token', @callback
it 'should return a NotFoundError', ->
@callback
.calledWith(sinon.match.instanceOf(Errors.NotFoundError))
.should.equal true
|
[
{
"context": ": TypePenID} >}}$0'\n description: 'Shortcode by Razon Yang'\n descriptionMoreURL: 'https://github.com/razo",
"end": 2402,
"score": 0.9989238977432251,
"start": 2392,
"tag": "NAME",
"value": "Razon Yang"
},
{
"context": "Yang'\n descriptionMoreURL: 'https://github.com/razonyang/hugo-theme-bootstrap/blob/master/layouts/shortcod",
"end": 2457,
"score": 0.9994120001792908,
"start": 2448,
"tag": "USERNAME",
"value": "razonyang"
},
{
"context": "team'\n descriptionMoreURL: 'https://github.com/twbs/bootstrap/tree/main/site/layouts/shortcodes'\n 'e",
"end": 2828,
"score": 0.9981733560562134,
"start": 2824,
"tag": "USERNAME",
"value": "twbs"
},
{
"context": "team'\n descriptionMoreURL: 'https://github.com/twbs/bootstrap/tree/main/site/layouts/shortcodes'\n 'p",
"end": 3149,
"score": 0.9980020523071289,
"start": 3145,
"tag": "USERNAME",
"value": "twbs"
},
{
"context": "team'\n descriptionMoreURL: 'https://github.com/twbs/bootstrap/tree/main/site/layouts/shortcodes'\n 'h",
"end": 3470,
"score": 0.9994736909866333,
"start": 3466,
"tag": "USERNAME",
"value": "twbs"
}
] | snippets/multilanguage-gfm.cson | vBuresh/atom-multilanguage-rfi | 0 | # Reed more about CoffeeScript syntax: http://coffeescript.org/
'.source.gfm':
'bold text':
prefix: 'rf-b'
body: '**$1**$0'
'code':
prefix: 'rf-code'
body: """
``` ${1:language} {${2:linenos=table,hl_lines=[1,"4-5"],linenostart=1}}
$3
```$0
"""
'italic text':
prefix: 'rf-i'
body: '*$1*$0'
'embedded image':
prefix: 'rf-img'
body: '$0'
'link':
prefix: 'rf-l'
body: '[$1]($2)$0'
'bullet point':
prefix: 'rf-p'
body: '- $1'
'reference':
prefix: 'rf-ref'
body: '[${1:id}]: ${2:url}${3: "${4:title}"}$0'
'reference image':
prefix: 'rf-rimg'
body: '![$1][$2]$0'
'reference link':
prefix: 'rf-rl'
body: '[$1][$2]$0'
'todo':
prefix: 'rf-t'
body: '- [ ] $1'
'table':
prefix: 'rf-table'
body: """
| ${1:Header One } | ${2:Header Two } |
| :------------- | :------------- |
| ${3:Item One } | ${4:Item Two } |$0
"""
# Hugo's
'i-bQsite':
prefix: 'rf-i-bQsite'
body: '<i>${1:author} <cite>[${2:name}](${3:URL})</cite></i>'
description: 'Автор и название цитируемого творения со ссылкой на источник.'
'go-comments':
prefix: 'rf-go-comments'
body: """
{{/*
${1:comment}
*/}}
"""
description: 'Go Templates comments. Do not try to comment out Go Template code using HTML comments.'
descriptionMoreURL: 'https://gohugo.io/templates/introduction/#go-templates-comments'
'img':
prefix: 'rf-img'
body: '{{< img src="${1:/images/b6.png}" ${2:class=""} title="${3:ReFreshing image}" >}}'
description: 'Let’s say you want to create your own img shortcode rather than use Hugo’s built-in figure shortcode.'
descriptionMoreURL: 'https://gohugo.io/templates/shortcode-templates/#single-named-example-image'
'figure':
prefix: 'rf-figure'
body: '{{< figure src="$1" caption="$2" ${3:class=""} ${4:width=""} ${5:height=""} >}}$0'
description: 'The figure shortcode can use the many named parameters'
descriptionMoreURL: 'https://gohugo.io/content-management/shortcodes/#figure'
'gist':
prefix: 'rf-gist'
body: '{{< gist ${1:user} ${2:id} >}}$0'
'codepen':
prefix: 'rf-codepen'
body: '{{< codepen ${1: TypePenID} >}}$0'
description: 'Shortcode by Razon Yang'
descriptionMoreURL: 'https://github.com/razonyang/hugo-theme-bootstrap/blob/master/layouts/shortcodes/'
'callout':
prefix: 'rf-callout'
body: """
{{< callout ${1:secondary} >}}
$2
{{< /callout >}}$0
"""
description: 'Type is one of info (default), danger, warning or secondary. Shortcode By Bootstrap team'
descriptionMoreURL: 'https://github.com/twbs/bootstrap/tree/main/site/layouts/shortcodes'
'example':
prefix: 'rf-example'
body: """
{{< example ${1:secondary} >}}
$2
{{< /example >}}$0
"""
description: 'args - are optional. Shortcode By Bootstrap team'
descriptionMoreURL: 'https://github.com/twbs/bootstrap/tree/main/site/layouts/shortcodes'
'placeholder':
prefix: 'rf-placeholder'
body: '{{< placeholder ${1:class="card-img-top"} ${2:width="100%" height="120"} ${3:text="Изображение"} >}}'
description: 'args - are optional. Shortcode By Bootstrap team'
descriptionMoreURL: 'https://github.com/twbs/bootstrap/tree/main/site/layouts/shortcodes'
'highlight-md':
prefix: 'rf-highlight-md'
body: """
``` ${1:language} {${2:linenos=table,hl_lines=[1,"4-5"],linenostart=1}}
$3
```$0
"""
description: 'Hugo built-in shortcode'
descriptionMoreURL: 'https://gohugo.io/content-management/syntax-highlighting/#example-highlight-shortcode'
'highlight':
prefix: 'rf-highlight-shortcode'
body: """
{{< highlight ${1:language} ${2:"linenos=table,hl_lines=8 15-17,linenostart=199"} >}}
$3
{{< /highlight >}}$0
"""
description: 'Hugo built-in shortcode'
descriptionMoreURL: 'https://gohugo.io/content-management/syntax-highlighting/#highlighting-in-code-fences'
'param':
prefix: 'rf-param'
body: '{{< param ${1:summary} >}}$0'
description: 'Hugo built-in shortcode. To access deeply nested params, use dot syntax, e.g - param "author.display_name".'
descriptionMoreURL: 'https://gohugo.io/content-management/syntax-highlighting/#example-highlight-shortcode'
#b6 BUG instagram API
'instagram':
prefix: 'rf-instagram'
body: '{{< instagram ${1:id} >}}$0'
description: 'Hugo’s Built-in Shortcode'
descriptionMoreURL: 'https://gohugo.io/content-management/shortcodes/#example-instagram-input'
'ref':
prefix: 'rf-ref'
body: '{{< ref "${1:/path/to/file.md}" >}}$0'
'relref':
prefix: 'rf-relref'
body: '{{< relref "${1:path/to/file.md}" >}}$0'
'speackerdeck':
prefix: 'rf-speackerdeck'
body: '{{< speakerdeck ${1:id} >}}$0'
'tweet':
prefix: 'rf-tweet'
body: '{{< tweet ${1:id} >}}$0'
'vimeo':
prefix: 'rf-vimeo'
body: '{{< vimeo ${1:id} ${2:class=""} >}}$0'
description: 'call id as a named parameter if add class'
'youtube':
prefix: 'rf-youtube'
body: '{{< youtube ${1:id} ${2:class=""} >}}$0'
description: 'call id as a named parameter if you add class'
| 17916 | # Reed more about CoffeeScript syntax: http://coffeescript.org/
'.source.gfm':
'bold text':
prefix: 'rf-b'
body: '**$1**$0'
'code':
prefix: 'rf-code'
body: """
``` ${1:language} {${2:linenos=table,hl_lines=[1,"4-5"],linenostart=1}}
$3
```$0
"""
'italic text':
prefix: 'rf-i'
body: '*$1*$0'
'embedded image':
prefix: 'rf-img'
body: '$0'
'link':
prefix: 'rf-l'
body: '[$1]($2)$0'
'bullet point':
prefix: 'rf-p'
body: '- $1'
'reference':
prefix: 'rf-ref'
body: '[${1:id}]: ${2:url}${3: "${4:title}"}$0'
'reference image':
prefix: 'rf-rimg'
body: '![$1][$2]$0'
'reference link':
prefix: 'rf-rl'
body: '[$1][$2]$0'
'todo':
prefix: 'rf-t'
body: '- [ ] $1'
'table':
prefix: 'rf-table'
body: """
| ${1:Header One } | ${2:Header Two } |
| :------------- | :------------- |
| ${3:Item One } | ${4:Item Two } |$0
"""
# Hugo's
'i-bQsite':
prefix: 'rf-i-bQsite'
body: '<i>${1:author} <cite>[${2:name}](${3:URL})</cite></i>'
description: 'Автор и название цитируемого творения со ссылкой на источник.'
'go-comments':
prefix: 'rf-go-comments'
body: """
{{/*
${1:comment}
*/}}
"""
description: 'Go Templates comments. Do not try to comment out Go Template code using HTML comments.'
descriptionMoreURL: 'https://gohugo.io/templates/introduction/#go-templates-comments'
'img':
prefix: 'rf-img'
body: '{{< img src="${1:/images/b6.png}" ${2:class=""} title="${3:ReFreshing image}" >}}'
description: 'Let’s say you want to create your own img shortcode rather than use Hugo’s built-in figure shortcode.'
descriptionMoreURL: 'https://gohugo.io/templates/shortcode-templates/#single-named-example-image'
'figure':
prefix: 'rf-figure'
body: '{{< figure src="$1" caption="$2" ${3:class=""} ${4:width=""} ${5:height=""} >}}$0'
description: 'The figure shortcode can use the many named parameters'
descriptionMoreURL: 'https://gohugo.io/content-management/shortcodes/#figure'
'gist':
prefix: 'rf-gist'
body: '{{< gist ${1:user} ${2:id} >}}$0'
'codepen':
prefix: 'rf-codepen'
body: '{{< codepen ${1: TypePenID} >}}$0'
description: 'Shortcode by <NAME>'
descriptionMoreURL: 'https://github.com/razonyang/hugo-theme-bootstrap/blob/master/layouts/shortcodes/'
'callout':
prefix: 'rf-callout'
body: """
{{< callout ${1:secondary} >}}
$2
{{< /callout >}}$0
"""
description: 'Type is one of info (default), danger, warning or secondary. Shortcode By Bootstrap team'
descriptionMoreURL: 'https://github.com/twbs/bootstrap/tree/main/site/layouts/shortcodes'
'example':
prefix: 'rf-example'
body: """
{{< example ${1:secondary} >}}
$2
{{< /example >}}$0
"""
description: 'args - are optional. Shortcode By Bootstrap team'
descriptionMoreURL: 'https://github.com/twbs/bootstrap/tree/main/site/layouts/shortcodes'
'placeholder':
prefix: 'rf-placeholder'
body: '{{< placeholder ${1:class="card-img-top"} ${2:width="100%" height="120"} ${3:text="Изображение"} >}}'
description: 'args - are optional. Shortcode By Bootstrap team'
descriptionMoreURL: 'https://github.com/twbs/bootstrap/tree/main/site/layouts/shortcodes'
'highlight-md':
prefix: 'rf-highlight-md'
body: """
``` ${1:language} {${2:linenos=table,hl_lines=[1,"4-5"],linenostart=1}}
$3
```$0
"""
description: 'Hugo built-in shortcode'
descriptionMoreURL: 'https://gohugo.io/content-management/syntax-highlighting/#example-highlight-shortcode'
'highlight':
prefix: 'rf-highlight-shortcode'
body: """
{{< highlight ${1:language} ${2:"linenos=table,hl_lines=8 15-17,linenostart=199"} >}}
$3
{{< /highlight >}}$0
"""
description: 'Hugo built-in shortcode'
descriptionMoreURL: 'https://gohugo.io/content-management/syntax-highlighting/#highlighting-in-code-fences'
'param':
prefix: 'rf-param'
body: '{{< param ${1:summary} >}}$0'
description: 'Hugo built-in shortcode. To access deeply nested params, use dot syntax, e.g - param "author.display_name".'
descriptionMoreURL: 'https://gohugo.io/content-management/syntax-highlighting/#example-highlight-shortcode'
#b6 BUG instagram API
'instagram':
prefix: 'rf-instagram'
body: '{{< instagram ${1:id} >}}$0'
description: 'Hugo’s Built-in Shortcode'
descriptionMoreURL: 'https://gohugo.io/content-management/shortcodes/#example-instagram-input'
'ref':
prefix: 'rf-ref'
body: '{{< ref "${1:/path/to/file.md}" >}}$0'
'relref':
prefix: 'rf-relref'
body: '{{< relref "${1:path/to/file.md}" >}}$0'
'speackerdeck':
prefix: 'rf-speackerdeck'
body: '{{< speakerdeck ${1:id} >}}$0'
'tweet':
prefix: 'rf-tweet'
body: '{{< tweet ${1:id} >}}$0'
'vimeo':
prefix: 'rf-vimeo'
body: '{{< vimeo ${1:id} ${2:class=""} >}}$0'
description: 'call id as a named parameter if add class'
'youtube':
prefix: 'rf-youtube'
body: '{{< youtube ${1:id} ${2:class=""} >}}$0'
description: 'call id as a named parameter if you add class'
| true | # Reed more about CoffeeScript syntax: http://coffeescript.org/
'.source.gfm':
'bold text':
prefix: 'rf-b'
body: '**$1**$0'
'code':
prefix: 'rf-code'
body: """
``` ${1:language} {${2:linenos=table,hl_lines=[1,"4-5"],linenostart=1}}
$3
```$0
"""
'italic text':
prefix: 'rf-i'
body: '*$1*$0'
'embedded image':
prefix: 'rf-img'
body: '$0'
'link':
prefix: 'rf-l'
body: '[$1]($2)$0'
'bullet point':
prefix: 'rf-p'
body: '- $1'
'reference':
prefix: 'rf-ref'
body: '[${1:id}]: ${2:url}${3: "${4:title}"}$0'
'reference image':
prefix: 'rf-rimg'
body: '![$1][$2]$0'
'reference link':
prefix: 'rf-rl'
body: '[$1][$2]$0'
'todo':
prefix: 'rf-t'
body: '- [ ] $1'
'table':
prefix: 'rf-table'
body: """
| ${1:Header One } | ${2:Header Two } |
| :------------- | :------------- |
| ${3:Item One } | ${4:Item Two } |$0
"""
# Hugo's
'i-bQsite':
prefix: 'rf-i-bQsite'
body: '<i>${1:author} <cite>[${2:name}](${3:URL})</cite></i>'
description: 'Автор и название цитируемого творения со ссылкой на источник.'
'go-comments':
prefix: 'rf-go-comments'
body: """
{{/*
${1:comment}
*/}}
"""
description: 'Go Templates comments. Do not try to comment out Go Template code using HTML comments.'
descriptionMoreURL: 'https://gohugo.io/templates/introduction/#go-templates-comments'
'img':
prefix: 'rf-img'
body: '{{< img src="${1:/images/b6.png}" ${2:class=""} title="${3:ReFreshing image}" >}}'
description: 'Let’s say you want to create your own img shortcode rather than use Hugo’s built-in figure shortcode.'
descriptionMoreURL: 'https://gohugo.io/templates/shortcode-templates/#single-named-example-image'
'figure':
prefix: 'rf-figure'
body: '{{< figure src="$1" caption="$2" ${3:class=""} ${4:width=""} ${5:height=""} >}}$0'
description: 'The figure shortcode can use the many named parameters'
descriptionMoreURL: 'https://gohugo.io/content-management/shortcodes/#figure'
'gist':
prefix: 'rf-gist'
body: '{{< gist ${1:user} ${2:id} >}}$0'
'codepen':
prefix: 'rf-codepen'
body: '{{< codepen ${1: TypePenID} >}}$0'
description: 'Shortcode by PI:NAME:<NAME>END_PI'
descriptionMoreURL: 'https://github.com/razonyang/hugo-theme-bootstrap/blob/master/layouts/shortcodes/'
'callout':
prefix: 'rf-callout'
body: """
{{< callout ${1:secondary} >}}
$2
{{< /callout >}}$0
"""
description: 'Type is one of info (default), danger, warning or secondary. Shortcode By Bootstrap team'
descriptionMoreURL: 'https://github.com/twbs/bootstrap/tree/main/site/layouts/shortcodes'
'example':
prefix: 'rf-example'
body: """
{{< example ${1:secondary} >}}
$2
{{< /example >}}$0
"""
description: 'args - are optional. Shortcode By Bootstrap team'
descriptionMoreURL: 'https://github.com/twbs/bootstrap/tree/main/site/layouts/shortcodes'
'placeholder':
prefix: 'rf-placeholder'
body: '{{< placeholder ${1:class="card-img-top"} ${2:width="100%" height="120"} ${3:text="Изображение"} >}}'
description: 'args - are optional. Shortcode By Bootstrap team'
descriptionMoreURL: 'https://github.com/twbs/bootstrap/tree/main/site/layouts/shortcodes'
'highlight-md':
prefix: 'rf-highlight-md'
body: """
``` ${1:language} {${2:linenos=table,hl_lines=[1,"4-5"],linenostart=1}}
$3
```$0
"""
description: 'Hugo built-in shortcode'
descriptionMoreURL: 'https://gohugo.io/content-management/syntax-highlighting/#example-highlight-shortcode'
'highlight':
prefix: 'rf-highlight-shortcode'
body: """
{{< highlight ${1:language} ${2:"linenos=table,hl_lines=8 15-17,linenostart=199"} >}}
$3
{{< /highlight >}}$0
"""
description: 'Hugo built-in shortcode'
descriptionMoreURL: 'https://gohugo.io/content-management/syntax-highlighting/#highlighting-in-code-fences'
'param':
prefix: 'rf-param'
body: '{{< param ${1:summary} >}}$0'
description: 'Hugo built-in shortcode. To access deeply nested params, use dot syntax, e.g - param "author.display_name".'
descriptionMoreURL: 'https://gohugo.io/content-management/syntax-highlighting/#example-highlight-shortcode'
#b6 BUG instagram API
'instagram':
prefix: 'rf-instagram'
body: '{{< instagram ${1:id} >}}$0'
description: 'Hugo’s Built-in Shortcode'
descriptionMoreURL: 'https://gohugo.io/content-management/shortcodes/#example-instagram-input'
'ref':
prefix: 'rf-ref'
body: '{{< ref "${1:/path/to/file.md}" >}}$0'
'relref':
prefix: 'rf-relref'
body: '{{< relref "${1:path/to/file.md}" >}}$0'
'speackerdeck':
prefix: 'rf-speackerdeck'
body: '{{< speakerdeck ${1:id} >}}$0'
'tweet':
prefix: 'rf-tweet'
body: '{{< tweet ${1:id} >}}$0'
'vimeo':
prefix: 'rf-vimeo'
body: '{{< vimeo ${1:id} ${2:class=""} >}}$0'
description: 'call id as a named parameter if add class'
'youtube':
prefix: 'rf-youtube'
body: '{{< youtube ${1:id} ${2:class=""} >}}$0'
description: 'call id as a named parameter if you add class'
|
[
{
"context": "ould have a name', ->\n @foo.name.should.equal 'Acute Pharyngitis'\n\n it 'should execute to the defined value set',",
"end": 1019,
"score": 0.9993446469306946,
"start": 1002,
"tag": "NAME",
"value": "Acute Pharyngitis"
},
{
"context": " setup @, data, [], vsets\n\n it 'should find that John is not female', ->\n @ctx = @ctx.withPatients n",
"end": 2335,
"score": 0.9437456727027893,
"start": 2331,
"tag": "NAME",
"value": "John"
},
{
"context": "exec(@ctx).should.be.false\n\n it 'should find that Sally is female', ->\n @ctx = @ctx.withPatients new P",
"end": 2480,
"score": 0.9957128763198853,
"start": 2475,
"tag": "NAME",
"value": "Sally"
}
] | Src/coffeescript/cql-execution/test/elm/clinical/test.coffee | esteban-aliverti/clinical_quality_language | 0 | should = require 'should'
setup = require '../../setup'
data = require './data'
vsets = require './valuesets'
{ p1, p2 } = require './patients'
{ PatientSource} = require '../../../lib/cql-patient'
describe 'ValueSetDef', ->
@beforeEach ->
setup @, data, [], vsets
it 'should return a resolved value set when the codeService knows about it', ->
vs = @known.exec(@ctx)
vs.oid.should.equal '2.16.840.1.113883.3.464.1003.101.12.1061'
vs.version.should.equal '20140501'
vs.codes.length.should.equal 3
it 'should execute one-arg to ValueSet with ID', ->
vs = @['unknown One Arg'].exec(@ctx)
vs.oid.should.equal '1.2.3.4.5.6.7.8.9'
should.not.exist vs.version
it 'should execute two-arg to ValueSet with ID and version', ->
vs = @['unknown Two Arg'].exec(@ctx)
vs.oid.should.equal '1.2.3.4.5.6.7.8.9'
vs.version.should.equal '1'
describe 'ValueSetRef', ->
@beforeEach ->
setup @, data
it 'should have a name', ->
@foo.name.should.equal 'Acute Pharyngitis'
it 'should execute to the defined value set', ->
@foo.exec(@ctx).oid.should.equal '2.16.840.1.113883.3.464.1003.101.12.1001'
describe 'InValueSet', ->
@beforeEach ->
setup @, data, [], vsets
it 'should find string code in value set', ->
@string.exec(@ctx).should.be.true
it 'should find string code in versioned value set', ->
@stringInVersionedValueSet.exec(@ctx).should.be.true
it 'should find short code in value set', ->
@shortCode.exec(@ctx).should.be.true
it 'should find medium code in value set', ->
@mediumCode.exec(@ctx).should.be.true
it 'should find long code in value set', ->
@longCode.exec(@ctx).should.be.true
it 'should not find string code in value set', ->
@wrongString.exec(@ctx).should.be.false
it 'should not find string code in versioned value set', ->
@wrongStringInVersionedValueSet.exec(@ctx).should.be.false
it 'should not find short code in value set', ->
@wrongShortCode.exec(@ctx).should.be.false
it 'should not find medium code in value set', ->
@wrongMediumCode.exec(@ctx).should.be.false
it 'should not find long code in value set', ->
@wrongLongCode.exec(@ctx).should.be.false
describe 'Patient Property In ValueSet', ->
@beforeEach ->
setup @, data, [], vsets
it 'should find that John is not female', ->
@ctx = @ctx.withPatients new PatientSource([ p1 ])
@isFemale.exec(@ctx).should.be.false
it 'should find that Sally is female', ->
@ctx = @ctx.withPatients new PatientSource([ p2 ])
@isFemale.exec(@ctx).should.be.true
describe 'CalculateAgeAt', ->
@beforeEach ->
setup @, data, [ p1 ]
it 'should execute age at 2012 as 31', ->
@ageAt2012.exec(@ctx).should.equal 31
it 'should execute age at 19810216 as 0', ->
@ageAt19810216.exec(@ctx).should.equal 0
it 'should execute age at 1975 as -5', ->
@ageAt19810216.exec(@ctx).should.equal 0
| 164576 | should = require 'should'
setup = require '../../setup'
data = require './data'
vsets = require './valuesets'
{ p1, p2 } = require './patients'
{ PatientSource} = require '../../../lib/cql-patient'
describe 'ValueSetDef', ->
@beforeEach ->
setup @, data, [], vsets
it 'should return a resolved value set when the codeService knows about it', ->
vs = @known.exec(@ctx)
vs.oid.should.equal '2.16.840.1.113883.3.464.1003.101.12.1061'
vs.version.should.equal '20140501'
vs.codes.length.should.equal 3
it 'should execute one-arg to ValueSet with ID', ->
vs = @['unknown One Arg'].exec(@ctx)
vs.oid.should.equal '1.2.3.4.5.6.7.8.9'
should.not.exist vs.version
it 'should execute two-arg to ValueSet with ID and version', ->
vs = @['unknown Two Arg'].exec(@ctx)
vs.oid.should.equal '1.2.3.4.5.6.7.8.9'
vs.version.should.equal '1'
describe 'ValueSetRef', ->
@beforeEach ->
setup @, data
it 'should have a name', ->
@foo.name.should.equal '<NAME>'
it 'should execute to the defined value set', ->
@foo.exec(@ctx).oid.should.equal '2.16.840.1.113883.3.464.1003.101.12.1001'
describe 'InValueSet', ->
@beforeEach ->
setup @, data, [], vsets
it 'should find string code in value set', ->
@string.exec(@ctx).should.be.true
it 'should find string code in versioned value set', ->
@stringInVersionedValueSet.exec(@ctx).should.be.true
it 'should find short code in value set', ->
@shortCode.exec(@ctx).should.be.true
it 'should find medium code in value set', ->
@mediumCode.exec(@ctx).should.be.true
it 'should find long code in value set', ->
@longCode.exec(@ctx).should.be.true
it 'should not find string code in value set', ->
@wrongString.exec(@ctx).should.be.false
it 'should not find string code in versioned value set', ->
@wrongStringInVersionedValueSet.exec(@ctx).should.be.false
it 'should not find short code in value set', ->
@wrongShortCode.exec(@ctx).should.be.false
it 'should not find medium code in value set', ->
@wrongMediumCode.exec(@ctx).should.be.false
it 'should not find long code in value set', ->
@wrongLongCode.exec(@ctx).should.be.false
describe 'Patient Property In ValueSet', ->
@beforeEach ->
setup @, data, [], vsets
it 'should find that <NAME> is not female', ->
@ctx = @ctx.withPatients new PatientSource([ p1 ])
@isFemale.exec(@ctx).should.be.false
it 'should find that <NAME> is female', ->
@ctx = @ctx.withPatients new PatientSource([ p2 ])
@isFemale.exec(@ctx).should.be.true
describe 'CalculateAgeAt', ->
@beforeEach ->
setup @, data, [ p1 ]
it 'should execute age at 2012 as 31', ->
@ageAt2012.exec(@ctx).should.equal 31
it 'should execute age at 19810216 as 0', ->
@ageAt19810216.exec(@ctx).should.equal 0
it 'should execute age at 1975 as -5', ->
@ageAt19810216.exec(@ctx).should.equal 0
| true | should = require 'should'
setup = require '../../setup'
data = require './data'
vsets = require './valuesets'
{ p1, p2 } = require './patients'
{ PatientSource} = require '../../../lib/cql-patient'
describe 'ValueSetDef', ->
@beforeEach ->
setup @, data, [], vsets
it 'should return a resolved value set when the codeService knows about it', ->
vs = @known.exec(@ctx)
vs.oid.should.equal '2.16.840.1.113883.3.464.1003.101.12.1061'
vs.version.should.equal '20140501'
vs.codes.length.should.equal 3
it 'should execute one-arg to ValueSet with ID', ->
vs = @['unknown One Arg'].exec(@ctx)
vs.oid.should.equal '1.2.3.4.5.6.7.8.9'
should.not.exist vs.version
it 'should execute two-arg to ValueSet with ID and version', ->
vs = @['unknown Two Arg'].exec(@ctx)
vs.oid.should.equal '1.2.3.4.5.6.7.8.9'
vs.version.should.equal '1'
describe 'ValueSetRef', ->
@beforeEach ->
setup @, data
it 'should have a name', ->
@foo.name.should.equal 'PI:NAME:<NAME>END_PI'
it 'should execute to the defined value set', ->
@foo.exec(@ctx).oid.should.equal '2.16.840.1.113883.3.464.1003.101.12.1001'
describe 'InValueSet', ->
@beforeEach ->
setup @, data, [], vsets
it 'should find string code in value set', ->
@string.exec(@ctx).should.be.true
it 'should find string code in versioned value set', ->
@stringInVersionedValueSet.exec(@ctx).should.be.true
it 'should find short code in value set', ->
@shortCode.exec(@ctx).should.be.true
it 'should find medium code in value set', ->
@mediumCode.exec(@ctx).should.be.true
it 'should find long code in value set', ->
@longCode.exec(@ctx).should.be.true
it 'should not find string code in value set', ->
@wrongString.exec(@ctx).should.be.false
it 'should not find string code in versioned value set', ->
@wrongStringInVersionedValueSet.exec(@ctx).should.be.false
it 'should not find short code in value set', ->
@wrongShortCode.exec(@ctx).should.be.false
it 'should not find medium code in value set', ->
@wrongMediumCode.exec(@ctx).should.be.false
it 'should not find long code in value set', ->
@wrongLongCode.exec(@ctx).should.be.false
describe 'Patient Property In ValueSet', ->
@beforeEach ->
setup @, data, [], vsets
it 'should find that PI:NAME:<NAME>END_PI is not female', ->
@ctx = @ctx.withPatients new PatientSource([ p1 ])
@isFemale.exec(@ctx).should.be.false
it 'should find that PI:NAME:<NAME>END_PI is female', ->
@ctx = @ctx.withPatients new PatientSource([ p2 ])
@isFemale.exec(@ctx).should.be.true
describe 'CalculateAgeAt', ->
@beforeEach ->
setup @, data, [ p1 ]
it 'should execute age at 2012 as 31', ->
@ageAt2012.exec(@ctx).should.equal 31
it 'should execute age at 19810216 as 0', ->
@ageAt19810216.exec(@ctx).should.equal 0
it 'should execute age at 1975 as -5', ->
@ageAt19810216.exec(@ctx).should.equal 0
|
[
{
"context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.",
"end": 215,
"score": 0.999852180480957,
"start": 198,
"tag": "NAME",
"value": "Benjamin Blundell"
},
{
"context": " PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.com\n\n This so",
"end": 231,
"score": 0.9999309778213501,
"start": 218,
"tag": "EMAIL",
"value": "ben@pxljs.com"
}
] | src/util/cache_var.coffee | OniDaito/pxljs | 1 | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
Benjamin Blundell - ben@pxljs.com
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
class CacheVar
constructor : (@variable) ->
@dirty = false
@
set : (new_value) ->
if new_value instanceof Array and @variable instanceof Array
if new_value.length != @variable.length
@dirty = true
@variable = new_value
else
for i in [0..new_value.length-1]
if not new_value[i].equals(@variable[i])
@dirty = true
@variable = new_value
return @
else if new_value.equals?
if not new_value.equals(@variable)
@dirty = true
@variable = new_value
else if new_value != @variable
@dirty = true
@variable = new_value
@
get: () ->
@dirty = false
@variable
isDirty: () ->
@dirty
module.exports =
CacheVar : CacheVar
| 64771 | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
<NAME> - <EMAIL>
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
class CacheVar
constructor : (@variable) ->
@dirty = false
@
set : (new_value) ->
if new_value instanceof Array and @variable instanceof Array
if new_value.length != @variable.length
@dirty = true
@variable = new_value
else
for i in [0..new_value.length-1]
if not new_value[i].equals(@variable[i])
@dirty = true
@variable = new_value
return @
else if new_value.equals?
if not new_value.equals(@variable)
@dirty = true
@variable = new_value
else if new_value != @variable
@dirty = true
@variable = new_value
@
get: () ->
@dirty = false
@variable
isDirty: () ->
@dirty
module.exports =
CacheVar : CacheVar
| true | ###
.__
_________ __| |
\____ \ \/ / |
| |_> > <| |__
| __/__/\_ \____/
|__| \/ js
PXL.js
PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI
http://pxljs.com
This software is released under the MIT Licence. See LICENCE.txt for details
###
class CacheVar
constructor : (@variable) ->
@dirty = false
@
set : (new_value) ->
if new_value instanceof Array and @variable instanceof Array
if new_value.length != @variable.length
@dirty = true
@variable = new_value
else
for i in [0..new_value.length-1]
if not new_value[i].equals(@variable[i])
@dirty = true
@variable = new_value
return @
else if new_value.equals?
if not new_value.equals(@variable)
@dirty = true
@variable = new_value
else if new_value != @variable
@dirty = true
@variable = new_value
@
get: () ->
@dirty = false
@variable
isDirty: () ->
@dirty
module.exports =
CacheVar : CacheVar
|
[
{
"context": "Name: 'rose', color: 'white'},\n {docName: 'lily', color: 'yellow'}]\n , 'all'\n\n it 'cal",
"end": 5635,
"score": 0.8017486929893494,
"start": 5634,
"tag": "NAME",
"value": "l"
},
{
"context": "}\n assert.deepEqual results[1], {docName: 'lily', color: 'yellow'}\n done()\n\n it 'filter",
"end": 6270,
"score": 0.9944648742675781,
"start": 6266,
"tag": "NAME",
"value": "lily"
},
{
"context": "entEmitter\n @queryEmitter.data = [{docName: 'lily', color: 'yellow'}]\n\n backend.query = (colle",
"end": 6741,
"score": 0.9969255924224854,
"start": 6737,
"tag": "NAME",
"value": "lily"
},
{
"context": " assert.deepEqual emitter.data[0], {docName: 'lily', color: 'yellow'}\n done()\n\n it 'fires ",
"end": 7295,
"score": 0.9945948719978333,
"start": 7291,
"tag": "NAME",
"value": "lily"
}
] | test/server/useragent.coffee | Acidburn0zzz/ShareJS | 1 | UserAgent = require '../../lib/server/useragent'
{Readable} = require 'stream'
{EventEmitter} = require 'events'
assert = require 'assert'
describe 'UserAgent', ->
backend = {}
shareInstance =
docFilters: []
opFilters: []
backend: backend
_trigger: (request, callback)->
callback(null, request)
beforeEach ->
@userAgent = new UserAgent shareInstance
shareInstance.docFilters = []
shareInstance.opFilters = []
describe 'fetch', ->
backend.fetch = (collection, document, callback) ->
callback null, {v:10, color: 'yellow'}
it 'calls fetch on backend', (done) ->
sinon.spy backend, 'fetch'
@userAgent.fetch 'flowers', 'lily', ->
sinon.assert.calledWith backend.fetch, 'flowers', 'lily'
backend.fetch.reset()
done()
it 'returns backend result', (done)->
@userAgent.fetch 'flowers', 'lily', (error, document)->
assert.deepEqual document, color: 'yellow'
done()
describe 'with doc filters', ->
it 'calls filter', (done)->
filter = sinon.spy (args..., next)-> next()
shareInstance.docFilters.push filter
@userAgent.fetch 'flowers', 'lily', (error, document)=>
sinon.assert.calledWith filter, 'flowers', 'lily', color: 'yellow'
done()
it 'manipulates document', (done)->
shareInstance.docFilters.push (collection, docName, data, next)->
data.color = 'red'
next()
@userAgent.fetch 'flowers', 'lily', (error, document)=>
assert.equal document.color, 'red'
done()
it 'passes exceptions as error', (done)->
shareInstance.docFilters.push -> throw Error 'oops'
@userAgent.fetch 'flowers', 'lily', (error, document)=>
assert.equal error, 'oops'
done()
it 'passes errors', (done)->
shareInstance.docFilters.push (args..., next)-> next('oops')
@userAgent.fetch 'flowers', 'lily', (error, document)=>
assert.equal error, 'oops'
done()
describe '#subscribe', ->
operationStream = new Readable objectMode: yes
operationStream._read = ->
beforeEach -> operationStream.unpipe()
backend.subscribe = (args..., callback)->
callback(null, operationStream)
it 'calls fetch on backend', (done)->
sinon.spy backend, 'subscribe'
@userAgent.subscribe 'flowers', 'lily', 10, ->
sinon.assert.calledWith backend.subscribe, 'flowers', 'lily', 10
backend.subscribe.reset()
done()
it 'can read operationStream', (done)->
@userAgent.subscribe 'flowers', 'lily', 10, (error, subscriptionStream)->
subscriptionStream.on 'readable', (data)->
assert.equal subscriptionStream.read(), 'first operation'
done()
operationStream.push 'first operation'
describe 'with op filters', ->
it 'calls the filter', (done)->
filter = sinon.spy (args..., next)-> next()
shareInstance.opFilters.push filter
@userAgent.subscribe 'flowers', 'lily', 10, (error, subscriptionStream)=>
subscriptionStream.on 'readable', (data)=>
sinon.assert.calledWith filter, 'flowers', 'lily', 'an op'
done()
operationStream.push 'an op'
it 'passes exceptions as errors to operationStream', (done)->
shareInstance.opFilters.push -> throw Error 'oops'
@userAgent.subscribe 'flowers', 'lily', 10, (error, subscriptionStream)->
subscriptionStream.on 'readable', (data)->
assert.deepEqual subscriptionStream.read(), {error: 'oops'}
done()
operationStream.push {op: 'first operation'}
it 'passes errors to operationStream', (done)->
shareInstance.opFilters.push (args..., next)-> next('oops')
@userAgent.subscribe 'flowers', 'lily', 10, (error, subscriptionStream)->
subscriptionStream.on 'readable', (data)->
assert.deepEqual subscriptionStream.read(), {error: 'oops'}
done()
operationStream.push {op: 'first operation'}
it 'manipulates operation', (done)->
shareInstance.opFilters.push (collection, docName, operation, next)->
operation.op = 'gotcha!'
next()
@userAgent.subscribe 'flowers', 'lily', 10, (error, subscriptionStream)->
subscriptionStream.on 'readable', (data)->
assert.deepEqual subscriptionStream.read(), {op: 'gotcha!'}
done()
operationStream.push {op: 'first operation'}
describe '#submit', ->
backend.submit = (collection, document, opData, options, callback)->
callback(null, 41, ['operation'], 'a document')
it 'calls submit on backend', (done)->
sinon.spy backend, 'submit'
@userAgent.submit 'flowers', 'lily', 'pluck', {}, ->
sinon.assert.calledWith backend.submit, 'flowers', 'lily', 'pluck'
backend.submit.reset()
done()
it 'returns version and operations', (done)->
@userAgent.submit 'flowers', 'lily', 'pluck', {}, (error, version, operations)->
assert.equal version, 41
assert.deepEqual operations, ['operation']
done()
it 'triggers after submit', (done)->
sinon.spy @userAgent, 'trigger'
@userAgent.submit 'flowers', 'lily', 'pluck', {}, =>
sinon.assert.calledWith @userAgent.trigger, 'after submit', 'flowers', 'lily'
done()
describe '#queryFetch', ->
backend.queryFetch = (collection, query, options, callback)->
callback null, [
{docName: 'rose', color: 'white'},
{docName: 'lily', color: 'yellow'}]
, 'all'
it 'calls queryFetch on backend', (done)->
sinon.spy backend, 'queryFetch'
@userAgent.queryFetch 'flowers', {smell: 'nice'}, {all: yes}, ->
sinon.assert.calledWith backend.queryFetch, 'flowers', {smell: 'nice'}, {all: yes}
backend.queryFetch.reset()
done()
it 'returns documents and extra', (done)->
@userAgent.queryFetch 'flowers', {smell: 'nice'}, {all: yes}, (error, results, extra)->
assert.equal extra, 'all'
assert.deepEqual results[0], {docName: 'rose', color: 'white'}
assert.deepEqual results[1], {docName: 'lily', color: 'yellow'}
done()
it 'filters documents', (done)->
shareInstance.docFilters.push (collection, docName, data, next)->
if docName == 'rose'
data.color = 'red'
next()
@userAgent.queryFetch 'flowers', {}, {}, (error, results)->
assert.equal results[0].color, 'red'
done()
describe '#query', ->
beforeEach ->
@queryEmitter = new EventEmitter
@queryEmitter.data = [{docName: 'lily', color: 'yellow'}]
backend.query = (collection, query, options, next)=>
next(null, @queryEmitter)
it 'calls query on backend', (done)->
sinon.spy backend, 'query'
@userAgent.query 'flowers', {smell: 'nice'}, {all: yes}, ->
sinon.assert.calledWith backend.query, 'flowers', {smell: 'nice'}, {all: yes}
backend.query.reset()
done()
it 'attaches results to emitter', (done)->
@userAgent.query 'flowers', {}, {}, (error, emitter)=>
assert.deepEqual emitter.data[0], {docName: 'lily', color: 'yellow'}
done()
it 'fires emit', (done)->
@userAgent.query 'flowers', {}, {}, (error, emitter)=>
emitter.on 'diff', (diffs)->
assert.equal diffs, 'This changed'
done()
@queryEmitter.emit('diff', 'This changed')
it 'filters records inserted into query results', (done)->
shareInstance.docFilters.push (collection, docName, data, next)->
if docName == 'rose'
data.color = 'red'
next()
@userAgent.query 'flowers', {}, {}, (error, emitter)=>
emitter.on 'diff', (diff)->
assert.equal diff[0].values[0].color, 'red'
done()
@queryEmitter.emit('diff', [{
type: 'insert',
values: [{docName: 'rose', color: 'white'}]
}])
describe '#trigger with middleware', ->
beforeEach ->
backend.bulkSubscribe = true
@instance = require('../../lib/server').createClient(backend: backend)
@userAgent.instance = @instance
it 'runs middleware', (done)->
@instance.use 'smell', (request, next)->
done()
@userAgent.trigger 'smell', 'flowers', 'lily', {}
it 'runs default middleware', (done)->
@instance.use (request, next)->
done()
@userAgent.trigger 'smell', 'flowers', 'lily', {}
it 'runs middleware with request', (done)->
@instance.use 'smell', (request, next)->
assert.equal request.action, 'smell'
assert.equal request.collection, 'flowers'
assert.equal request.docName, 'lily'
assert.equal request.deep, true
assert.deepEqual request.backend, backend
done()
@userAgent.trigger 'smell', 'flowers', 'lily', deep: true
it 'passes modified request to callback', (done)->
@instance.use 'smell', (request, next)->
request.eyesClosed = true
next()
@userAgent.trigger 'smell', 'flowers', 'lily', (error, request)->
assert.ok request.eyesClosed
done()
it 'passes errors to callback', (done)->
@instance.use 'smell', (request, next)->
next('Argh!')
@userAgent.trigger 'smell', 'flowers', 'lily', (error, request)->
assert.equal error, 'Argh!'
done()
| 203660 | UserAgent = require '../../lib/server/useragent'
{Readable} = require 'stream'
{EventEmitter} = require 'events'
assert = require 'assert'
describe 'UserAgent', ->
backend = {}
shareInstance =
docFilters: []
opFilters: []
backend: backend
_trigger: (request, callback)->
callback(null, request)
beforeEach ->
@userAgent = new UserAgent shareInstance
shareInstance.docFilters = []
shareInstance.opFilters = []
describe 'fetch', ->
backend.fetch = (collection, document, callback) ->
callback null, {v:10, color: 'yellow'}
it 'calls fetch on backend', (done) ->
sinon.spy backend, 'fetch'
@userAgent.fetch 'flowers', 'lily', ->
sinon.assert.calledWith backend.fetch, 'flowers', 'lily'
backend.fetch.reset()
done()
it 'returns backend result', (done)->
@userAgent.fetch 'flowers', 'lily', (error, document)->
assert.deepEqual document, color: 'yellow'
done()
describe 'with doc filters', ->
it 'calls filter', (done)->
filter = sinon.spy (args..., next)-> next()
shareInstance.docFilters.push filter
@userAgent.fetch 'flowers', 'lily', (error, document)=>
sinon.assert.calledWith filter, 'flowers', 'lily', color: 'yellow'
done()
it 'manipulates document', (done)->
shareInstance.docFilters.push (collection, docName, data, next)->
data.color = 'red'
next()
@userAgent.fetch 'flowers', 'lily', (error, document)=>
assert.equal document.color, 'red'
done()
it 'passes exceptions as error', (done)->
shareInstance.docFilters.push -> throw Error 'oops'
@userAgent.fetch 'flowers', 'lily', (error, document)=>
assert.equal error, 'oops'
done()
it 'passes errors', (done)->
shareInstance.docFilters.push (args..., next)-> next('oops')
@userAgent.fetch 'flowers', 'lily', (error, document)=>
assert.equal error, 'oops'
done()
describe '#subscribe', ->
operationStream = new Readable objectMode: yes
operationStream._read = ->
beforeEach -> operationStream.unpipe()
backend.subscribe = (args..., callback)->
callback(null, operationStream)
it 'calls fetch on backend', (done)->
sinon.spy backend, 'subscribe'
@userAgent.subscribe 'flowers', 'lily', 10, ->
sinon.assert.calledWith backend.subscribe, 'flowers', 'lily', 10
backend.subscribe.reset()
done()
it 'can read operationStream', (done)->
@userAgent.subscribe 'flowers', 'lily', 10, (error, subscriptionStream)->
subscriptionStream.on 'readable', (data)->
assert.equal subscriptionStream.read(), 'first operation'
done()
operationStream.push 'first operation'
describe 'with op filters', ->
it 'calls the filter', (done)->
filter = sinon.spy (args..., next)-> next()
shareInstance.opFilters.push filter
@userAgent.subscribe 'flowers', 'lily', 10, (error, subscriptionStream)=>
subscriptionStream.on 'readable', (data)=>
sinon.assert.calledWith filter, 'flowers', 'lily', 'an op'
done()
operationStream.push 'an op'
it 'passes exceptions as errors to operationStream', (done)->
shareInstance.opFilters.push -> throw Error 'oops'
@userAgent.subscribe 'flowers', 'lily', 10, (error, subscriptionStream)->
subscriptionStream.on 'readable', (data)->
assert.deepEqual subscriptionStream.read(), {error: 'oops'}
done()
operationStream.push {op: 'first operation'}
it 'passes errors to operationStream', (done)->
shareInstance.opFilters.push (args..., next)-> next('oops')
@userAgent.subscribe 'flowers', 'lily', 10, (error, subscriptionStream)->
subscriptionStream.on 'readable', (data)->
assert.deepEqual subscriptionStream.read(), {error: 'oops'}
done()
operationStream.push {op: 'first operation'}
it 'manipulates operation', (done)->
shareInstance.opFilters.push (collection, docName, operation, next)->
operation.op = 'gotcha!'
next()
@userAgent.subscribe 'flowers', 'lily', 10, (error, subscriptionStream)->
subscriptionStream.on 'readable', (data)->
assert.deepEqual subscriptionStream.read(), {op: 'gotcha!'}
done()
operationStream.push {op: 'first operation'}
describe '#submit', ->
backend.submit = (collection, document, opData, options, callback)->
callback(null, 41, ['operation'], 'a document')
it 'calls submit on backend', (done)->
sinon.spy backend, 'submit'
@userAgent.submit 'flowers', 'lily', 'pluck', {}, ->
sinon.assert.calledWith backend.submit, 'flowers', 'lily', 'pluck'
backend.submit.reset()
done()
it 'returns version and operations', (done)->
@userAgent.submit 'flowers', 'lily', 'pluck', {}, (error, version, operations)->
assert.equal version, 41
assert.deepEqual operations, ['operation']
done()
it 'triggers after submit', (done)->
sinon.spy @userAgent, 'trigger'
@userAgent.submit 'flowers', 'lily', 'pluck', {}, =>
sinon.assert.calledWith @userAgent.trigger, 'after submit', 'flowers', 'lily'
done()
describe '#queryFetch', ->
backend.queryFetch = (collection, query, options, callback)->
callback null, [
{docName: 'rose', color: 'white'},
{docName: '<NAME>ily', color: 'yellow'}]
, 'all'
it 'calls queryFetch on backend', (done)->
sinon.spy backend, 'queryFetch'
@userAgent.queryFetch 'flowers', {smell: 'nice'}, {all: yes}, ->
sinon.assert.calledWith backend.queryFetch, 'flowers', {smell: 'nice'}, {all: yes}
backend.queryFetch.reset()
done()
it 'returns documents and extra', (done)->
@userAgent.queryFetch 'flowers', {smell: 'nice'}, {all: yes}, (error, results, extra)->
assert.equal extra, 'all'
assert.deepEqual results[0], {docName: 'rose', color: 'white'}
assert.deepEqual results[1], {docName: '<NAME>', color: 'yellow'}
done()
it 'filters documents', (done)->
shareInstance.docFilters.push (collection, docName, data, next)->
if docName == 'rose'
data.color = 'red'
next()
@userAgent.queryFetch 'flowers', {}, {}, (error, results)->
assert.equal results[0].color, 'red'
done()
describe '#query', ->
beforeEach ->
@queryEmitter = new EventEmitter
@queryEmitter.data = [{docName: '<NAME>', color: 'yellow'}]
backend.query = (collection, query, options, next)=>
next(null, @queryEmitter)
it 'calls query on backend', (done)->
sinon.spy backend, 'query'
@userAgent.query 'flowers', {smell: 'nice'}, {all: yes}, ->
sinon.assert.calledWith backend.query, 'flowers', {smell: 'nice'}, {all: yes}
backend.query.reset()
done()
it 'attaches results to emitter', (done)->
@userAgent.query 'flowers', {}, {}, (error, emitter)=>
assert.deepEqual emitter.data[0], {docName: '<NAME>', color: 'yellow'}
done()
it 'fires emit', (done)->
@userAgent.query 'flowers', {}, {}, (error, emitter)=>
emitter.on 'diff', (diffs)->
assert.equal diffs, 'This changed'
done()
@queryEmitter.emit('diff', 'This changed')
it 'filters records inserted into query results', (done)->
shareInstance.docFilters.push (collection, docName, data, next)->
if docName == 'rose'
data.color = 'red'
next()
@userAgent.query 'flowers', {}, {}, (error, emitter)=>
emitter.on 'diff', (diff)->
assert.equal diff[0].values[0].color, 'red'
done()
@queryEmitter.emit('diff', [{
type: 'insert',
values: [{docName: 'rose', color: 'white'}]
}])
describe '#trigger with middleware', ->
beforeEach ->
backend.bulkSubscribe = true
@instance = require('../../lib/server').createClient(backend: backend)
@userAgent.instance = @instance
it 'runs middleware', (done)->
@instance.use 'smell', (request, next)->
done()
@userAgent.trigger 'smell', 'flowers', 'lily', {}
it 'runs default middleware', (done)->
@instance.use (request, next)->
done()
@userAgent.trigger 'smell', 'flowers', 'lily', {}
it 'runs middleware with request', (done)->
@instance.use 'smell', (request, next)->
assert.equal request.action, 'smell'
assert.equal request.collection, 'flowers'
assert.equal request.docName, 'lily'
assert.equal request.deep, true
assert.deepEqual request.backend, backend
done()
@userAgent.trigger 'smell', 'flowers', 'lily', deep: true
it 'passes modified request to callback', (done)->
@instance.use 'smell', (request, next)->
request.eyesClosed = true
next()
@userAgent.trigger 'smell', 'flowers', 'lily', (error, request)->
assert.ok request.eyesClosed
done()
it 'passes errors to callback', (done)->
@instance.use 'smell', (request, next)->
next('Argh!')
@userAgent.trigger 'smell', 'flowers', 'lily', (error, request)->
assert.equal error, 'Argh!'
done()
| true | UserAgent = require '../../lib/server/useragent'
{Readable} = require 'stream'
{EventEmitter} = require 'events'
assert = require 'assert'
describe 'UserAgent', ->
backend = {}
shareInstance =
docFilters: []
opFilters: []
backend: backend
_trigger: (request, callback)->
callback(null, request)
beforeEach ->
@userAgent = new UserAgent shareInstance
shareInstance.docFilters = []
shareInstance.opFilters = []
describe 'fetch', ->
backend.fetch = (collection, document, callback) ->
callback null, {v:10, color: 'yellow'}
it 'calls fetch on backend', (done) ->
sinon.spy backend, 'fetch'
@userAgent.fetch 'flowers', 'lily', ->
sinon.assert.calledWith backend.fetch, 'flowers', 'lily'
backend.fetch.reset()
done()
it 'returns backend result', (done)->
@userAgent.fetch 'flowers', 'lily', (error, document)->
assert.deepEqual document, color: 'yellow'
done()
describe 'with doc filters', ->
it 'calls filter', (done)->
filter = sinon.spy (args..., next)-> next()
shareInstance.docFilters.push filter
@userAgent.fetch 'flowers', 'lily', (error, document)=>
sinon.assert.calledWith filter, 'flowers', 'lily', color: 'yellow'
done()
it 'manipulates document', (done)->
shareInstance.docFilters.push (collection, docName, data, next)->
data.color = 'red'
next()
@userAgent.fetch 'flowers', 'lily', (error, document)=>
assert.equal document.color, 'red'
done()
it 'passes exceptions as error', (done)->
shareInstance.docFilters.push -> throw Error 'oops'
@userAgent.fetch 'flowers', 'lily', (error, document)=>
assert.equal error, 'oops'
done()
it 'passes errors', (done)->
shareInstance.docFilters.push (args..., next)-> next('oops')
@userAgent.fetch 'flowers', 'lily', (error, document)=>
assert.equal error, 'oops'
done()
describe '#subscribe', ->
operationStream = new Readable objectMode: yes
operationStream._read = ->
beforeEach -> operationStream.unpipe()
backend.subscribe = (args..., callback)->
callback(null, operationStream)
it 'calls fetch on backend', (done)->
sinon.spy backend, 'subscribe'
@userAgent.subscribe 'flowers', 'lily', 10, ->
sinon.assert.calledWith backend.subscribe, 'flowers', 'lily', 10
backend.subscribe.reset()
done()
it 'can read operationStream', (done)->
@userAgent.subscribe 'flowers', 'lily', 10, (error, subscriptionStream)->
subscriptionStream.on 'readable', (data)->
assert.equal subscriptionStream.read(), 'first operation'
done()
operationStream.push 'first operation'
describe 'with op filters', ->
it 'calls the filter', (done)->
filter = sinon.spy (args..., next)-> next()
shareInstance.opFilters.push filter
@userAgent.subscribe 'flowers', 'lily', 10, (error, subscriptionStream)=>
subscriptionStream.on 'readable', (data)=>
sinon.assert.calledWith filter, 'flowers', 'lily', 'an op'
done()
operationStream.push 'an op'
it 'passes exceptions as errors to operationStream', (done)->
shareInstance.opFilters.push -> throw Error 'oops'
@userAgent.subscribe 'flowers', 'lily', 10, (error, subscriptionStream)->
subscriptionStream.on 'readable', (data)->
assert.deepEqual subscriptionStream.read(), {error: 'oops'}
done()
operationStream.push {op: 'first operation'}
it 'passes errors to operationStream', (done)->
shareInstance.opFilters.push (args..., next)-> next('oops')
@userAgent.subscribe 'flowers', 'lily', 10, (error, subscriptionStream)->
subscriptionStream.on 'readable', (data)->
assert.deepEqual subscriptionStream.read(), {error: 'oops'}
done()
operationStream.push {op: 'first operation'}
it 'manipulates operation', (done)->
shareInstance.opFilters.push (collection, docName, operation, next)->
operation.op = 'gotcha!'
next()
@userAgent.subscribe 'flowers', 'lily', 10, (error, subscriptionStream)->
subscriptionStream.on 'readable', (data)->
assert.deepEqual subscriptionStream.read(), {op: 'gotcha!'}
done()
operationStream.push {op: 'first operation'}
describe '#submit', ->
backend.submit = (collection, document, opData, options, callback)->
callback(null, 41, ['operation'], 'a document')
it 'calls submit on backend', (done)->
sinon.spy backend, 'submit'
@userAgent.submit 'flowers', 'lily', 'pluck', {}, ->
sinon.assert.calledWith backend.submit, 'flowers', 'lily', 'pluck'
backend.submit.reset()
done()
it 'returns version and operations', (done)->
@userAgent.submit 'flowers', 'lily', 'pluck', {}, (error, version, operations)->
assert.equal version, 41
assert.deepEqual operations, ['operation']
done()
it 'triggers after submit', (done)->
sinon.spy @userAgent, 'trigger'
@userAgent.submit 'flowers', 'lily', 'pluck', {}, =>
sinon.assert.calledWith @userAgent.trigger, 'after submit', 'flowers', 'lily'
done()
describe '#queryFetch', ->
backend.queryFetch = (collection, query, options, callback)->
callback null, [
{docName: 'rose', color: 'white'},
{docName: 'PI:NAME:<NAME>END_PIily', color: 'yellow'}]
, 'all'
it 'calls queryFetch on backend', (done)->
sinon.spy backend, 'queryFetch'
@userAgent.queryFetch 'flowers', {smell: 'nice'}, {all: yes}, ->
sinon.assert.calledWith backend.queryFetch, 'flowers', {smell: 'nice'}, {all: yes}
backend.queryFetch.reset()
done()
it 'returns documents and extra', (done)->
@userAgent.queryFetch 'flowers', {smell: 'nice'}, {all: yes}, (error, results, extra)->
assert.equal extra, 'all'
assert.deepEqual results[0], {docName: 'rose', color: 'white'}
assert.deepEqual results[1], {docName: 'PI:NAME:<NAME>END_PI', color: 'yellow'}
done()
it 'filters documents', (done)->
shareInstance.docFilters.push (collection, docName, data, next)->
if docName == 'rose'
data.color = 'red'
next()
@userAgent.queryFetch 'flowers', {}, {}, (error, results)->
assert.equal results[0].color, 'red'
done()
describe '#query', ->
beforeEach ->
@queryEmitter = new EventEmitter
@queryEmitter.data = [{docName: 'PI:NAME:<NAME>END_PI', color: 'yellow'}]
backend.query = (collection, query, options, next)=>
next(null, @queryEmitter)
it 'calls query on backend', (done)->
sinon.spy backend, 'query'
@userAgent.query 'flowers', {smell: 'nice'}, {all: yes}, ->
sinon.assert.calledWith backend.query, 'flowers', {smell: 'nice'}, {all: yes}
backend.query.reset()
done()
it 'attaches results to emitter', (done)->
@userAgent.query 'flowers', {}, {}, (error, emitter)=>
assert.deepEqual emitter.data[0], {docName: 'PI:NAME:<NAME>END_PI', color: 'yellow'}
done()
it 'fires emit', (done)->
@userAgent.query 'flowers', {}, {}, (error, emitter)=>
emitter.on 'diff', (diffs)->
assert.equal diffs, 'This changed'
done()
@queryEmitter.emit('diff', 'This changed')
it 'filters records inserted into query results', (done)->
shareInstance.docFilters.push (collection, docName, data, next)->
if docName == 'rose'
data.color = 'red'
next()
@userAgent.query 'flowers', {}, {}, (error, emitter)=>
emitter.on 'diff', (diff)->
assert.equal diff[0].values[0].color, 'red'
done()
@queryEmitter.emit('diff', [{
type: 'insert',
values: [{docName: 'rose', color: 'white'}]
}])
describe '#trigger with middleware', ->
beforeEach ->
backend.bulkSubscribe = true
@instance = require('../../lib/server').createClient(backend: backend)
@userAgent.instance = @instance
it 'runs middleware', (done)->
@instance.use 'smell', (request, next)->
done()
@userAgent.trigger 'smell', 'flowers', 'lily', {}
it 'runs default middleware', (done)->
@instance.use (request, next)->
done()
@userAgent.trigger 'smell', 'flowers', 'lily', {}
it 'runs middleware with request', (done)->
@instance.use 'smell', (request, next)->
assert.equal request.action, 'smell'
assert.equal request.collection, 'flowers'
assert.equal request.docName, 'lily'
assert.equal request.deep, true
assert.deepEqual request.backend, backend
done()
@userAgent.trigger 'smell', 'flowers', 'lily', deep: true
it 'passes modified request to callback', (done)->
@instance.use 'smell', (request, next)->
request.eyesClosed = true
next()
@userAgent.trigger 'smell', 'flowers', 'lily', (error, request)->
assert.ok request.eyesClosed
done()
it 'passes errors to callback', (done)->
@instance.use 'smell', (request, next)->
next('Argh!')
@userAgent.trigger 'smell', 'flowers', 'lily', (error, request)->
assert.equal error, 'Argh!'
done()
|
[
{
"context": "space COOLSTRAP\n * @class Constants\n * \n * @author Abraham Barrera <abarrerac@gmail.com> || @abraham_barrera\n * \n###",
"end": 113,
"score": 0.9998882412910461,
"start": 98,
"tag": "NAME",
"value": "Abraham Barrera"
},
{
"context": " @class Constants\n * \n * @author Abraham Barrera <abarrerac@gmail.com> || @abraham_barrera\n * \n###\n\nCOOLSTRAP.Constants",
"end": 134,
"score": 0.999933660030365,
"start": 115,
"tag": "EMAIL",
"value": "abarrerac@gmail.com"
},
{
"context": "* @author Abraham Barrera <abarrerac@gmail.com> || @abraham_barrera\n * \n###\n\nCOOLSTRAP.Constants =\n ELEMENT:\n SECTI",
"end": 155,
"score": 0.999494194984436,
"start": 139,
"tag": "USERNAME",
"value": "@abraham_barrera"
}
] | coolstrap-core/app/assets/javascripts/coolstrap/_Coolstrap.Constants.coffee | cristianferrarig/coolstrap | 0 | ###
* Coolstrapp Global Constants
*
* @namespace COOLSTRAP
* @class Constants
*
* @author Abraham Barrera <abarrerac@gmail.com> || @abraham_barrera
*
###
COOLSTRAP.Constants =
ELEMENT:
SECTION: "section"
ARTICLE: "article"
ASIDE: "aside"
DIALOG: "div[role=\"dialog\"]"
BODY: "body"
DIV: "div"
TARGET:
CONTAINER: "container"
MAIN: "main"
SECTION: "section"
ARTICLE: "article"
ASIDE: "aside"
BACK: "back"
DIALOG: "dialog"
CLOSE: "close"
TRANSITION:
DURATION: 250
CLASS:
ACTIVE: "active"
ASIDE: "aside"
SHOW: "show"
HIDE: "hide"
CURRENT: "current"
FIRST: "first"
RIGHT: "onright"
LEFT: "onleft"
TOP: "ontop"
BOTTOM: "onbottom"
CENTER: "oncenter"
HORIZONTAL: "horizontal"
SCROLLABLE: "scrollable"
FADE_IN: "fadeIn"
NONE: ""
ATTRIBUTE:
ID: "id"
HREF: "href"
TITLE: "title"
ARTICLE: "article"
CLASS: "class"
WIDTH: "width"
HEIGHT: "height"
PIXEL: "px"
PERCENT: "%"
TARGET: "target"
FIRST: "first"
LAST: "last"
EMPTY: ""
TRIGGER:
LOAD: "load"
UNLOAD: "unload"
LOG_LEVEL:
DEBUG: -1
INFO: 0
LOG: 1
WARN: 2
ERROR: 3
NONE: 4
DIALOG:
MODAL: "modal"
ALERT: "alert"
ACTION: "action"
POPOVER: "popover"
COMMAND:
CLOSE_DIALOG: "close"
ERROR:
CREATE_SCROLL: "ERROR: Impossible to create a <scroll> without ID."
ROUTER: "ERROR: The target does not exists >>"
LOADING_RESOURCE: "ERROR: Loading resource." | 110968 | ###
* Coolstrapp Global Constants
*
* @namespace COOLSTRAP
* @class Constants
*
* @author <NAME> <<EMAIL>> || @abraham_barrera
*
###
COOLSTRAP.Constants =
ELEMENT:
SECTION: "section"
ARTICLE: "article"
ASIDE: "aside"
DIALOG: "div[role=\"dialog\"]"
BODY: "body"
DIV: "div"
TARGET:
CONTAINER: "container"
MAIN: "main"
SECTION: "section"
ARTICLE: "article"
ASIDE: "aside"
BACK: "back"
DIALOG: "dialog"
CLOSE: "close"
TRANSITION:
DURATION: 250
CLASS:
ACTIVE: "active"
ASIDE: "aside"
SHOW: "show"
HIDE: "hide"
CURRENT: "current"
FIRST: "first"
RIGHT: "onright"
LEFT: "onleft"
TOP: "ontop"
BOTTOM: "onbottom"
CENTER: "oncenter"
HORIZONTAL: "horizontal"
SCROLLABLE: "scrollable"
FADE_IN: "fadeIn"
NONE: ""
ATTRIBUTE:
ID: "id"
HREF: "href"
TITLE: "title"
ARTICLE: "article"
CLASS: "class"
WIDTH: "width"
HEIGHT: "height"
PIXEL: "px"
PERCENT: "%"
TARGET: "target"
FIRST: "first"
LAST: "last"
EMPTY: ""
TRIGGER:
LOAD: "load"
UNLOAD: "unload"
LOG_LEVEL:
DEBUG: -1
INFO: 0
LOG: 1
WARN: 2
ERROR: 3
NONE: 4
DIALOG:
MODAL: "modal"
ALERT: "alert"
ACTION: "action"
POPOVER: "popover"
COMMAND:
CLOSE_DIALOG: "close"
ERROR:
CREATE_SCROLL: "ERROR: Impossible to create a <scroll> without ID."
ROUTER: "ERROR: The target does not exists >>"
LOADING_RESOURCE: "ERROR: Loading resource." | true | ###
* Coolstrapp Global Constants
*
* @namespace COOLSTRAP
* @class Constants
*
* @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> || @abraham_barrera
*
###
COOLSTRAP.Constants =
ELEMENT:
SECTION: "section"
ARTICLE: "article"
ASIDE: "aside"
DIALOG: "div[role=\"dialog\"]"
BODY: "body"
DIV: "div"
TARGET:
CONTAINER: "container"
MAIN: "main"
SECTION: "section"
ARTICLE: "article"
ASIDE: "aside"
BACK: "back"
DIALOG: "dialog"
CLOSE: "close"
TRANSITION:
DURATION: 250
CLASS:
ACTIVE: "active"
ASIDE: "aside"
SHOW: "show"
HIDE: "hide"
CURRENT: "current"
FIRST: "first"
RIGHT: "onright"
LEFT: "onleft"
TOP: "ontop"
BOTTOM: "onbottom"
CENTER: "oncenter"
HORIZONTAL: "horizontal"
SCROLLABLE: "scrollable"
FADE_IN: "fadeIn"
NONE: ""
ATTRIBUTE:
ID: "id"
HREF: "href"
TITLE: "title"
ARTICLE: "article"
CLASS: "class"
WIDTH: "width"
HEIGHT: "height"
PIXEL: "px"
PERCENT: "%"
TARGET: "target"
FIRST: "first"
LAST: "last"
EMPTY: ""
TRIGGER:
LOAD: "load"
UNLOAD: "unload"
LOG_LEVEL:
DEBUG: -1
INFO: 0
LOG: 1
WARN: 2
ERROR: 3
NONE: 4
DIALOG:
MODAL: "modal"
ALERT: "alert"
ACTION: "action"
POPOVER: "popover"
COMMAND:
CLOSE_DIALOG: "close"
ERROR:
CREATE_SCROLL: "ERROR: Impossible to create a <scroll> without ID."
ROUTER: "ERROR: The target does not exists >>"
LOADING_RESOURCE: "ERROR: Loading resource." |
[
{
"context": "forms\"\nlocation: \"Stockport\"\nphase: \"alpha\"\nsro: \"Kenny Robertson\"\nservice_man: \"TBC\"\nphase_history:\n discovery: [",
"end": 317,
"score": 0.9998615980148315,
"start": 302,
"tag": "NAME",
"value": "Kenny Robertson"
}
] | app/data/projects/prove-you-can-apply.cson | tsmorgan/dwp-ux-work | 0 | id: 30
name: "Prove you can apply"
description: "Looking at how users can demonstrate they have the right to live in the UK and intend to settle in the UK, Isle of Man, Channel Islands, or Northern Ireland so they can access DWP services."
theme: "Platforms"
location: "Stockport"
phase: "alpha"
sro: "Kenny Robertson"
service_man: "TBC"
phase_history:
discovery: [
{
label: "Completed"
date: "May 2016"
}
]
alpha: [
{
label: "Started"
date: "June 2016"
}
]
priority: "Top"
prototype: "https://dwp-hrttriage.herokuapp.com/" | 174279 | id: 30
name: "Prove you can apply"
description: "Looking at how users can demonstrate they have the right to live in the UK and intend to settle in the UK, Isle of Man, Channel Islands, or Northern Ireland so they can access DWP services."
theme: "Platforms"
location: "Stockport"
phase: "alpha"
sro: "<NAME>"
service_man: "TBC"
phase_history:
discovery: [
{
label: "Completed"
date: "May 2016"
}
]
alpha: [
{
label: "Started"
date: "June 2016"
}
]
priority: "Top"
prototype: "https://dwp-hrttriage.herokuapp.com/" | true | id: 30
name: "Prove you can apply"
description: "Looking at how users can demonstrate they have the right to live in the UK and intend to settle in the UK, Isle of Man, Channel Islands, or Northern Ireland so they can access DWP services."
theme: "Platforms"
location: "Stockport"
phase: "alpha"
sro: "PI:NAME:<NAME>END_PI"
service_man: "TBC"
phase_history:
discovery: [
{
label: "Completed"
date: "May 2016"
}
]
alpha: [
{
label: "Started"
date: "June 2016"
}
]
priority: "Top"
prototype: "https://dwp-hrttriage.herokuapp.com/" |
[
{
"context": " event handler naming conventions in JSX\n# @author Jake Marsh\n###\n'use strict'\n\ndocsUrl = require 'eslint-plugi",
"end": 89,
"score": 0.9997519850730896,
"start": 79,
"tag": "NAME",
"value": "Jake Marsh"
}
] | src/rules/jsx-handler-names.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Enforce event handler naming conventions in JSX
# @author Jake Marsh
###
'use strict'
docsUrl = require 'eslint-plugin-react/lib/util/docsUrl'
# ------------------------------------------------------------------------------
# Rule Definition
# ------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'Enforce event handler naming conventions in JSX'
category: 'Stylistic Issues'
recommended: no
url: docsUrl 'jsx-handler-names'
schema: [
type: 'object'
properties:
eventHandlerPrefix:
type: 'string'
eventHandlerPropPrefix:
type: 'string'
additionalProperties: no
]
create: (context) ->
sourceCode = context.getSourceCode()
configuration = context.options[0] or {}
eventHandlerPrefix = configuration.eventHandlerPrefix or 'handle'
eventHandlerPropPrefix = configuration.eventHandlerPropPrefix or 'on'
EVENT_HANDLER_REGEX = new RegExp(
"^((props\\.#{eventHandlerPropPrefix})|((.*\\.)?#{eventHandlerPrefix}))[A-Z].*$"
)
PROP_EVENT_HANDLER_REGEX = new RegExp(
"^(#{eventHandlerPropPrefix}[A-Z].*|ref)$"
)
JSXAttribute: (node) ->
return unless node.value?.expression?.object
propKey =
if typeof node.name is 'object'
node.name.name
else
node.name
propValue =
sourceCode.getText(node.value.expression).replace /^this\.|.*::|@/, ''
return if propKey is 'ref'
propIsEventHandler = PROP_EVENT_HANDLER_REGEX.test propKey
propFnIsNamedCorrectly = EVENT_HANDLER_REGEX.test propValue
if propIsEventHandler and not propFnIsNamedCorrectly
context.report {
node
message: "Handler function for #{propKey} prop key must begin with '#{eventHandlerPrefix}'"
}
else if propFnIsNamedCorrectly and not propIsEventHandler
context.report {
node
message: "Prop key for #{propValue} must begin with '#{eventHandlerPropPrefix}'"
}
| 32607 | ###*
# @fileoverview Enforce event handler naming conventions in JSX
# @author <NAME>
###
'use strict'
docsUrl = require 'eslint-plugin-react/lib/util/docsUrl'
# ------------------------------------------------------------------------------
# Rule Definition
# ------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'Enforce event handler naming conventions in JSX'
category: 'Stylistic Issues'
recommended: no
url: docsUrl 'jsx-handler-names'
schema: [
type: 'object'
properties:
eventHandlerPrefix:
type: 'string'
eventHandlerPropPrefix:
type: 'string'
additionalProperties: no
]
create: (context) ->
sourceCode = context.getSourceCode()
configuration = context.options[0] or {}
eventHandlerPrefix = configuration.eventHandlerPrefix or 'handle'
eventHandlerPropPrefix = configuration.eventHandlerPropPrefix or 'on'
EVENT_HANDLER_REGEX = new RegExp(
"^((props\\.#{eventHandlerPropPrefix})|((.*\\.)?#{eventHandlerPrefix}))[A-Z].*$"
)
PROP_EVENT_HANDLER_REGEX = new RegExp(
"^(#{eventHandlerPropPrefix}[A-Z].*|ref)$"
)
JSXAttribute: (node) ->
return unless node.value?.expression?.object
propKey =
if typeof node.name is 'object'
node.name.name
else
node.name
propValue =
sourceCode.getText(node.value.expression).replace /^this\.|.*::|@/, ''
return if propKey is 'ref'
propIsEventHandler = PROP_EVENT_HANDLER_REGEX.test propKey
propFnIsNamedCorrectly = EVENT_HANDLER_REGEX.test propValue
if propIsEventHandler and not propFnIsNamedCorrectly
context.report {
node
message: "Handler function for #{propKey} prop key must begin with '#{eventHandlerPrefix}'"
}
else if propFnIsNamedCorrectly and not propIsEventHandler
context.report {
node
message: "Prop key for #{propValue} must begin with '#{eventHandlerPropPrefix}'"
}
| true | ###*
# @fileoverview Enforce event handler naming conventions in JSX
# @author PI:NAME:<NAME>END_PI
###
'use strict'
docsUrl = require 'eslint-plugin-react/lib/util/docsUrl'
# ------------------------------------------------------------------------------
# Rule Definition
# ------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'Enforce event handler naming conventions in JSX'
category: 'Stylistic Issues'
recommended: no
url: docsUrl 'jsx-handler-names'
schema: [
type: 'object'
properties:
eventHandlerPrefix:
type: 'string'
eventHandlerPropPrefix:
type: 'string'
additionalProperties: no
]
create: (context) ->
sourceCode = context.getSourceCode()
configuration = context.options[0] or {}
eventHandlerPrefix = configuration.eventHandlerPrefix or 'handle'
eventHandlerPropPrefix = configuration.eventHandlerPropPrefix or 'on'
EVENT_HANDLER_REGEX = new RegExp(
"^((props\\.#{eventHandlerPropPrefix})|((.*\\.)?#{eventHandlerPrefix}))[A-Z].*$"
)
PROP_EVENT_HANDLER_REGEX = new RegExp(
"^(#{eventHandlerPropPrefix}[A-Z].*|ref)$"
)
JSXAttribute: (node) ->
return unless node.value?.expression?.object
propKey =
if typeof node.name is 'object'
node.name.name
else
node.name
propValue =
sourceCode.getText(node.value.expression).replace /^this\.|.*::|@/, ''
return if propKey is 'ref'
propIsEventHandler = PROP_EVENT_HANDLER_REGEX.test propKey
propFnIsNamedCorrectly = EVENT_HANDLER_REGEX.test propValue
if propIsEventHandler and not propFnIsNamedCorrectly
context.report {
node
message: "Handler function for #{propKey} prop key must begin with '#{eventHandlerPrefix}'"
}
else if propFnIsNamedCorrectly and not propIsEventHandler
context.report {
node
message: "Prop key for #{propValue} must begin with '#{eventHandlerPropPrefix}'"
}
|
[
{
"context": "module.exports=\n name:\"东方Project\"\n #\n opening:\"异变发生!\"\n # to let p",
"end": 27,
"score": 0.7914875745773315,
"start": 26,
"tag": "NAME",
"value": "东"
},
{
"context": ".com/some_character.jpg\" # 头像链接\n name:\"博丽灵梦\" # 名字,必填\n prize:[\"八百万神的代言人\",\"博丽神社的巫女小姐",
"end": 702,
"score": 0.9997677803039551,
"start": 698,
"tag": "NAME",
"value": "博丽灵梦"
},
{
"context": "om/some_other_character_2.jpg\"]\n name:\"大鲶鱼\"\n prize:\"\" # 称号是允许留空的",
"end": 1020,
"score": 0.9984908103942871,
"start": 1017,
"tag": "NAME",
"value": "大鲶鱼"
}
] | server/themes/example.coffee | Sunev/jinrou | 18 | module.exports=
name:"东方Project"
#
opening:"异变发生!"
# to let players know woh they are
skin_tip:"你的身份"
# 主题的作者
author:"*******(加上联系方式)"
# 修改时间
lastModified:"2021-08-21T10:46:33.917Z"
vote:""
sunrise:""
sunset:""
icon:""
background_color:"black"
color:"rgb(255,0,166)"
lockable:true
isAvailable:->
# 如果想要做成有某种限制条件
# return false
return true
skins:
# 罗马字名 ,只允许半角英数字和下划线,数字和下划线不允许是首位
# 不可以重复
some_character:
# 头像链接 和 称号 可以是字符串数组,也可以是字符串
# 头像在显示的时候 会压缩为48*48,所以最好纵横比是1:1
avatar:"http://img.example.com/some_character.jpg" # 头像链接
name:"博丽灵梦" # 名字,必填
prize:["八百万神的代言人","博丽神社的巫女小姐","飞翔于天空的不可思议的巫女","快晴的巫女","乐园的可爱巫女","乐园的巫女","神秘!结界的巫女","五欲的巫女","永远之巫女","追逐怪奇!终结异变的巫女"] # 称号
some_other_character:
avatar:["http://img.example.com/some_other_character_1.jpg","http://img.example.com/some_other_character_2.jpg"]
name:"大鲶鱼"
prize:"" # 称号是允许留空的 | 104859 | module.exports=
name:"<NAME>方Project"
#
opening:"异变发生!"
# to let players know woh they are
skin_tip:"你的身份"
# 主题的作者
author:"*******(加上联系方式)"
# 修改时间
lastModified:"2021-08-21T10:46:33.917Z"
vote:""
sunrise:""
sunset:""
icon:""
background_color:"black"
color:"rgb(255,0,166)"
lockable:true
isAvailable:->
# 如果想要做成有某种限制条件
# return false
return true
skins:
# 罗马字名 ,只允许半角英数字和下划线,数字和下划线不允许是首位
# 不可以重复
some_character:
# 头像链接 和 称号 可以是字符串数组,也可以是字符串
# 头像在显示的时候 会压缩为48*48,所以最好纵横比是1:1
avatar:"http://img.example.com/some_character.jpg" # 头像链接
name:"<NAME>" # 名字,必填
prize:["八百万神的代言人","博丽神社的巫女小姐","飞翔于天空的不可思议的巫女","快晴的巫女","乐园的可爱巫女","乐园的巫女","神秘!结界的巫女","五欲的巫女","永远之巫女","追逐怪奇!终结异变的巫女"] # 称号
some_other_character:
avatar:["http://img.example.com/some_other_character_1.jpg","http://img.example.com/some_other_character_2.jpg"]
name:"<NAME>"
prize:"" # 称号是允许留空的 | true | module.exports=
name:"PI:NAME:<NAME>END_PI方Project"
#
opening:"异变发生!"
# to let players know woh they are
skin_tip:"你的身份"
# 主题的作者
author:"*******(加上联系方式)"
# 修改时间
lastModified:"2021-08-21T10:46:33.917Z"
vote:""
sunrise:""
sunset:""
icon:""
background_color:"black"
color:"rgb(255,0,166)"
lockable:true
isAvailable:->
# 如果想要做成有某种限制条件
# return false
return true
skins:
# 罗马字名 ,只允许半角英数字和下划线,数字和下划线不允许是首位
# 不可以重复
some_character:
# 头像链接 和 称号 可以是字符串数组,也可以是字符串
# 头像在显示的时候 会压缩为48*48,所以最好纵横比是1:1
avatar:"http://img.example.com/some_character.jpg" # 头像链接
name:"PI:NAME:<NAME>END_PI" # 名字,必填
prize:["八百万神的代言人","博丽神社的巫女小姐","飞翔于天空的不可思议的巫女","快晴的巫女","乐园的可爱巫女","乐园的巫女","神秘!结界的巫女","五欲的巫女","永远之巫女","追逐怪奇!终结异变的巫女"] # 称号
some_other_character:
avatar:["http://img.example.com/some_other_character_1.jpg","http://img.example.com/some_other_character_2.jpg"]
name:"PI:NAME:<NAME>END_PI"
prize:"" # 称号是允许留空的 |
[
{
"context": " username: env.OS_USERNAME\n password: env.OS_PASSWORD\n request.post options, (error, response, body) -",
"end": 432,
"score": 0.9976471662521362,
"start": 417,
"tag": "PASSWORD",
"value": "env.OS_PASSWORD"
}
] | designate.coffee | dit4c/designate-rr-monitor | 1 | 'use strict'
_ = require('lodash')
Q = require('q')
async = require('async-q')
env = process.env
moment = require('moment')
request = require('request')
newTokenAndEndpoint = (callback) ->
d = Q.defer()
options =
url: env.OS_AUTH_URL + 'tokens'
json: true
body:
auth:
tenantName: env.OS_TENANT_NAME,
passwordCredentials:
username: env.OS_USERNAME
password: env.OS_PASSWORD
request.post options, (error, response, body) ->
if (error)
d.reject(error)
else
designateEndpoint = _.chain(body.access.serviceCatalog)
.filter (obj) -> obj.type == 'dns'
.pluck 'endpoints'
.flatten()
.pluck 'publicURL'
.head()
.value()
d.resolve
expiry: body.access.token.expires,
token: body.access.token.id,
endpoint: designateEndpoint+"v1/"
d.promise
listDomains = (token, endpoint) ->
d = Q.defer()
options =
url: endpoint + 'domains/'
json: true
headers:
'Accept': 'application/json'
'X-Auth-Token': token
request.get options, (error, response, body) ->
if (error)
d.reject(error)
else
d.resolve(body.domains)
d.promise
listRecords = (token, endpoint, domainId) ->
d = Q.defer()
options =
url: endpoint + 'domains/' + domainId + '/records'
json: true
headers:
'Accept': 'application/json'
'X-Auth-Token': token
request.get options, (error, response, body) ->
if (error)
d.reject(error)
else
d.resolve(body.records)
d.promise
addRecord = (token, endpoint, domainId, record) ->
d = Q.defer()
options =
url: endpoint + 'domains/' + domainId + '/records'
json: true
headers:
'Accept': 'application/json'
'X-Auth-Token': token
body: record
request.post options, (error, response, body) ->
if error || response.statusCode != 200
console.log(error || body)
d.reject(error)
else
d.resolve(body)
d.promise
deleteRecord = (token, endpoint, domainId, recordId) ->
d = Q.defer()
options =
url: endpoint + 'domains/' + domainId + '/records/' + recordId
headers:
'X-Auth-Token': token
request.del options, (error, response) ->
if error || response.statusCode != 200
console.log(error || response.statusCode)
d.reject(error)
else
d.resolve()
d.promise
factory = (recordName, options) ->
options ?= {}
defaultTTL = options.ttl || 60
expiryBuffer = moment.duration('5', 'minutes')
infoRef =
info:
expiry: '1970-01-01',
token: null,
designateUrl: null
haveCurrentToken = () ->
moment(infoRef.info.expiry).isAfter(moment().add(expiryBuffer))
token = () ->
if haveCurrentToken()
Q(infoRef.info)
else
newTokenAndEndpoint().then (info) ->
listDomains(info.token, info.endpoint)
.then (domains) ->
_.chain(domains)
.filter (d) -> recordName.indexOf(d.name) != -1
.max (d) -> d.name.length
.value()
.then (domain) ->
infoRef.info = _.extend(info, { domain_id: domain.id })
obj = {}
obj.list = () ->
token()
.then (info) ->
listRecords(info.token, info.endpoint, info.domain_id)
.then (records) ->
_.filter records, (record) ->
record.name == recordName and record.type in ['A','AAAA']
add = (type, data) ->
token().then (info) ->
addRecord info.token, info.endpoint, info.domain_id,
name: recordName
type: type
data: data
ttl: defaultTTL
remove = (record_id) ->
token().then (info) ->
deleteRecord info.token, info.endpoint, info.domain_id, record_id
obj.addAll = (records) ->
obj.list()
.then (existingRecords) ->
recordsToAdd = _.reject records, (r1) ->
_.some existingRecords, (r2) ->
r1.type == r2.type && r1.addr == r2.data
jobs = recordsToAdd.map (r) -> () ->
add(r.type, r.addr)
async.series(jobs)
obj.retainAll = (records) ->
obj.list()
.then (existingRecords) ->
recordsToDelete = _.reject existingRecords, (r1) ->
_.some records, (r2) ->
r1.type == r2.type && r1.data == r2.addr
jobs = recordsToDelete.map (r) -> () ->
remove(r.id)
async.series(jobs)
obj
module.exports = factory
| 145281 | 'use strict'
_ = require('lodash')
Q = require('q')
async = require('async-q')
env = process.env
moment = require('moment')
request = require('request')
newTokenAndEndpoint = (callback) ->
d = Q.defer()
options =
url: env.OS_AUTH_URL + 'tokens'
json: true
body:
auth:
tenantName: env.OS_TENANT_NAME,
passwordCredentials:
username: env.OS_USERNAME
password: <PASSWORD>
request.post options, (error, response, body) ->
if (error)
d.reject(error)
else
designateEndpoint = _.chain(body.access.serviceCatalog)
.filter (obj) -> obj.type == 'dns'
.pluck 'endpoints'
.flatten()
.pluck 'publicURL'
.head()
.value()
d.resolve
expiry: body.access.token.expires,
token: body.access.token.id,
endpoint: designateEndpoint+"v1/"
d.promise
listDomains = (token, endpoint) ->
d = Q.defer()
options =
url: endpoint + 'domains/'
json: true
headers:
'Accept': 'application/json'
'X-Auth-Token': token
request.get options, (error, response, body) ->
if (error)
d.reject(error)
else
d.resolve(body.domains)
d.promise
listRecords = (token, endpoint, domainId) ->
d = Q.defer()
options =
url: endpoint + 'domains/' + domainId + '/records'
json: true
headers:
'Accept': 'application/json'
'X-Auth-Token': token
request.get options, (error, response, body) ->
if (error)
d.reject(error)
else
d.resolve(body.records)
d.promise
addRecord = (token, endpoint, domainId, record) ->
d = Q.defer()
options =
url: endpoint + 'domains/' + domainId + '/records'
json: true
headers:
'Accept': 'application/json'
'X-Auth-Token': token
body: record
request.post options, (error, response, body) ->
if error || response.statusCode != 200
console.log(error || body)
d.reject(error)
else
d.resolve(body)
d.promise
deleteRecord = (token, endpoint, domainId, recordId) ->
d = Q.defer()
options =
url: endpoint + 'domains/' + domainId + '/records/' + recordId
headers:
'X-Auth-Token': token
request.del options, (error, response) ->
if error || response.statusCode != 200
console.log(error || response.statusCode)
d.reject(error)
else
d.resolve()
d.promise
factory = (recordName, options) ->
options ?= {}
defaultTTL = options.ttl || 60
expiryBuffer = moment.duration('5', 'minutes')
infoRef =
info:
expiry: '1970-01-01',
token: null,
designateUrl: null
haveCurrentToken = () ->
moment(infoRef.info.expiry).isAfter(moment().add(expiryBuffer))
token = () ->
if haveCurrentToken()
Q(infoRef.info)
else
newTokenAndEndpoint().then (info) ->
listDomains(info.token, info.endpoint)
.then (domains) ->
_.chain(domains)
.filter (d) -> recordName.indexOf(d.name) != -1
.max (d) -> d.name.length
.value()
.then (domain) ->
infoRef.info = _.extend(info, { domain_id: domain.id })
obj = {}
obj.list = () ->
token()
.then (info) ->
listRecords(info.token, info.endpoint, info.domain_id)
.then (records) ->
_.filter records, (record) ->
record.name == recordName and record.type in ['A','AAAA']
add = (type, data) ->
token().then (info) ->
addRecord info.token, info.endpoint, info.domain_id,
name: recordName
type: type
data: data
ttl: defaultTTL
remove = (record_id) ->
token().then (info) ->
deleteRecord info.token, info.endpoint, info.domain_id, record_id
obj.addAll = (records) ->
obj.list()
.then (existingRecords) ->
recordsToAdd = _.reject records, (r1) ->
_.some existingRecords, (r2) ->
r1.type == r2.type && r1.addr == r2.data
jobs = recordsToAdd.map (r) -> () ->
add(r.type, r.addr)
async.series(jobs)
obj.retainAll = (records) ->
obj.list()
.then (existingRecords) ->
recordsToDelete = _.reject existingRecords, (r1) ->
_.some records, (r2) ->
r1.type == r2.type && r1.data == r2.addr
jobs = recordsToDelete.map (r) -> () ->
remove(r.id)
async.series(jobs)
obj
module.exports = factory
| true | 'use strict'
_ = require('lodash')
Q = require('q')
async = require('async-q')
env = process.env
moment = require('moment')
request = require('request')
newTokenAndEndpoint = (callback) ->
d = Q.defer()
options =
url: env.OS_AUTH_URL + 'tokens'
json: true
body:
auth:
tenantName: env.OS_TENANT_NAME,
passwordCredentials:
username: env.OS_USERNAME
password: PI:PASSWORD:<PASSWORD>END_PI
request.post options, (error, response, body) ->
if (error)
d.reject(error)
else
designateEndpoint = _.chain(body.access.serviceCatalog)
.filter (obj) -> obj.type == 'dns'
.pluck 'endpoints'
.flatten()
.pluck 'publicURL'
.head()
.value()
d.resolve
expiry: body.access.token.expires,
token: body.access.token.id,
endpoint: designateEndpoint+"v1/"
d.promise
listDomains = (token, endpoint) ->
d = Q.defer()
options =
url: endpoint + 'domains/'
json: true
headers:
'Accept': 'application/json'
'X-Auth-Token': token
request.get options, (error, response, body) ->
if (error)
d.reject(error)
else
d.resolve(body.domains)
d.promise
listRecords = (token, endpoint, domainId) ->
d = Q.defer()
options =
url: endpoint + 'domains/' + domainId + '/records'
json: true
headers:
'Accept': 'application/json'
'X-Auth-Token': token
request.get options, (error, response, body) ->
if (error)
d.reject(error)
else
d.resolve(body.records)
d.promise
addRecord = (token, endpoint, domainId, record) ->
d = Q.defer()
options =
url: endpoint + 'domains/' + domainId + '/records'
json: true
headers:
'Accept': 'application/json'
'X-Auth-Token': token
body: record
request.post options, (error, response, body) ->
if error || response.statusCode != 200
console.log(error || body)
d.reject(error)
else
d.resolve(body)
d.promise
deleteRecord = (token, endpoint, domainId, recordId) ->
d = Q.defer()
options =
url: endpoint + 'domains/' + domainId + '/records/' + recordId
headers:
'X-Auth-Token': token
request.del options, (error, response) ->
if error || response.statusCode != 200
console.log(error || response.statusCode)
d.reject(error)
else
d.resolve()
d.promise
factory = (recordName, options) ->
options ?= {}
defaultTTL = options.ttl || 60
expiryBuffer = moment.duration('5', 'minutes')
infoRef =
info:
expiry: '1970-01-01',
token: null,
designateUrl: null
haveCurrentToken = () ->
moment(infoRef.info.expiry).isAfter(moment().add(expiryBuffer))
token = () ->
if haveCurrentToken()
Q(infoRef.info)
else
newTokenAndEndpoint().then (info) ->
listDomains(info.token, info.endpoint)
.then (domains) ->
_.chain(domains)
.filter (d) -> recordName.indexOf(d.name) != -1
.max (d) -> d.name.length
.value()
.then (domain) ->
infoRef.info = _.extend(info, { domain_id: domain.id })
obj = {}
obj.list = () ->
token()
.then (info) ->
listRecords(info.token, info.endpoint, info.domain_id)
.then (records) ->
_.filter records, (record) ->
record.name == recordName and record.type in ['A','AAAA']
add = (type, data) ->
token().then (info) ->
addRecord info.token, info.endpoint, info.domain_id,
name: recordName
type: type
data: data
ttl: defaultTTL
remove = (record_id) ->
token().then (info) ->
deleteRecord info.token, info.endpoint, info.domain_id, record_id
obj.addAll = (records) ->
obj.list()
.then (existingRecords) ->
recordsToAdd = _.reject records, (r1) ->
_.some existingRecords, (r2) ->
r1.type == r2.type && r1.addr == r2.data
jobs = recordsToAdd.map (r) -> () ->
add(r.type, r.addr)
async.series(jobs)
obj.retainAll = (records) ->
obj.list()
.then (existingRecords) ->
recordsToDelete = _.reject existingRecords, (r1) ->
_.some records, (r2) ->
r1.type == r2.type && r1.data == r2.addr
jobs = recordsToDelete.map (r) -> () ->
remove(r.id)
async.series(jobs)
obj
module.exports = factory
|
[
{
"context": "# Menu.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Main applic",
"end": 22,
"score": 0.9984639883041382,
"start": 16,
"tag": "NAME",
"value": "Tomasz"
},
{
"context": "# Menu.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Main application menu o",
"end": 36,
"score": 0.9693412780761719,
"start": 24,
"tag": "NAME",
"value": "Tomek) Zemla"
},
{
"context": "# Menu.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Main application menu on the left side of the ",
"end": 59,
"score": 0.9999293684959412,
"start": 39,
"tag": "EMAIL",
"value": "tomek@datacratic.com"
}
] | src/Menu.coffee | SachithDassanayaka/sachithdassanayaka.github.io | 0 | # Menu.coffee
# Tomasz (Tomek) Zemla
# tomek@datacratic.com
# Main application menu on the left side of the application window.
Panel = require('./Panel.coffee')
class Menu extends Panel
# E V E N T S
@EVENT_TOGGLE_ALL_ON : "EVENT_TOGGLE_ALL_ON"
@EVENT_TOGGLE_ALL_OFF : "EVENT_TOGGLE_ALL_OFF"
@EVENT_TOGGLE_ID : "EVENT_TOGGLE_ID"
@EVENT_CLUSTER_ID : "EVENT_CLUSTER_ID"
# C O N S T A N T S
@TOGGLE_ON : "[+]"
@TOGGLE_OFF : "[-]"
@TOGGLE_MIX : "[/]"
# M E M B E R S
clusters : 0 # total number of clusters
selected : -1 # currently selected cluster
colors : null # set of colors to use
# C O N S T R U C T O R
constructor : (id) ->
super(id)
# E V E N T H A N D L E R S
# Toggle visibility of all clusters at once.
onToggleAll : (event) =>
state = $("#toggleAll").text()
switch state
when Menu.TOGGLE_OFF, Menu.TOGGLE_MIX # turn all on
$("#toggleAll").text(Menu.TOGGLE_ON)
for i in [0...@clusters]
$("#t" + String(i)).text(Menu.TOGGLE_ON)
@notify(Menu.EVENT_TOGGLE_ALL_ON)
when Menu.TOGGLE_ON # turn all off
$("#toggleAll").text(Menu.TOGGLE_OFF)
for i in [0...@clusters]
$("#t" + String(i)).text(Menu.TOGGLE_OFF)
@notify(Menu.EVENT_TOGGLE_ALL_OFF)
onToggle : (event) =>
identifier = event.target.id
id = identifier.replace("t", "")
index = parseInt(id)
@doToggle(index)
@notify(Menu.EVENT_TOGGLE_ID, { id : index })
onCluster : (event) =>
# retrieve clicked cluster number
index = parseInt(event.target.id.replace("b", ""))
if @selected is index then @selected = -1 # unselect
else @selected = index # select
@updateSwatches()
@updateButtons()
@notify(Menu.EVENT_CLUSTER_ID, { id : index })
# Flip toggle given by its index.
doToggle : (index) ->
tag = "#t" + String(index)
state = $(tag).text()
switch state
when Menu.TOGGLE_ON
$(tag).text(Menu.TOGGLE_OFF)
when Menu.TOGGLE_OFF
$(tag).text(Menu.TOGGLE_ON)
@updateMasterToggle()
# M E T H O D S
# Create dynamically menu for given number of clusters.
# Use given set of colors for color coding to match visualization.
create : (@clusters, @colors) ->
# button IDs are b0, b1, b2...
# toggle IDs are t0, t1, t2...
# swatch IDs are c0, c1, c2...
for i in [0...@clusters]
html = "<span class='toggle' id='t#{i}'>[+]</span><span class='button' id='b#{i}'> Cluster</span><span class='color' id='c#{i}'> #{i} </span><br/>"
$("#menu").append(html)
$("#toggleAll").click(@onToggleAll)
for i in [0...@clusters]
$("#t" + String(i)).click( @onToggle )
$("#b" + String(i)).click( @onCluster )
@updateSwatches()
# Count how many toggles are on.
togglesOn : ->
result = 0
for i in [0...@clusters]
tag = "#t" + String(i)
state = $(tag).text()
if state is Menu.TOGGLE_ON then result++
return result
# Based on the state of all cluster toggles, set the master toggle.
updateMasterToggle : () ->
shown = @togglesOn()
switch shown
when 0 then $("#toggleAll").text(Menu.TOGGLE_OFF)
when @clusters then $("#toggleAll").text(Menu.TOGGLE_ON)
else $("#toggleAll").text(Menu.TOGGLE_MIX)
# Swatches have IDs: c0, c1, c2...
updateSwatches : ->
for i in [0...@clusters]
if i is @selected
$("#c" + String(i)).css( 'color', Palette.HIGHLIGHT.getStyle() )
else
$("#c" + String(i)).css( 'color', @colors[i].getStyle() )
# Cluster buttons have IDs: b0, b1, b2...
updateButtons : ->
for i in [0...@clusters]
if i is @selected
$("#b" + String(i)).css( 'color', Palette.HIGHLIGHT.getStyle() )
else
$("#b" + String(i)).css( 'color', Palette.BUTTON.getStyle() )
module.exports = Menu
| 125693 | # Menu.coffee
# <NAME> (<NAME>
# <EMAIL>
# Main application menu on the left side of the application window.
Panel = require('./Panel.coffee')
class Menu extends Panel
# E V E N T S
@EVENT_TOGGLE_ALL_ON : "EVENT_TOGGLE_ALL_ON"
@EVENT_TOGGLE_ALL_OFF : "EVENT_TOGGLE_ALL_OFF"
@EVENT_TOGGLE_ID : "EVENT_TOGGLE_ID"
@EVENT_CLUSTER_ID : "EVENT_CLUSTER_ID"
# C O N S T A N T S
@TOGGLE_ON : "[+]"
@TOGGLE_OFF : "[-]"
@TOGGLE_MIX : "[/]"
# M E M B E R S
clusters : 0 # total number of clusters
selected : -1 # currently selected cluster
colors : null # set of colors to use
# C O N S T R U C T O R
constructor : (id) ->
super(id)
# E V E N T H A N D L E R S
# Toggle visibility of all clusters at once.
onToggleAll : (event) =>
state = $("#toggleAll").text()
switch state
when Menu.TOGGLE_OFF, Menu.TOGGLE_MIX # turn all on
$("#toggleAll").text(Menu.TOGGLE_ON)
for i in [0...@clusters]
$("#t" + String(i)).text(Menu.TOGGLE_ON)
@notify(Menu.EVENT_TOGGLE_ALL_ON)
when Menu.TOGGLE_ON # turn all off
$("#toggleAll").text(Menu.TOGGLE_OFF)
for i in [0...@clusters]
$("#t" + String(i)).text(Menu.TOGGLE_OFF)
@notify(Menu.EVENT_TOGGLE_ALL_OFF)
onToggle : (event) =>
identifier = event.target.id
id = identifier.replace("t", "")
index = parseInt(id)
@doToggle(index)
@notify(Menu.EVENT_TOGGLE_ID, { id : index })
onCluster : (event) =>
# retrieve clicked cluster number
index = parseInt(event.target.id.replace("b", ""))
if @selected is index then @selected = -1 # unselect
else @selected = index # select
@updateSwatches()
@updateButtons()
@notify(Menu.EVENT_CLUSTER_ID, { id : index })
# Flip toggle given by its index.
doToggle : (index) ->
tag = "#t" + String(index)
state = $(tag).text()
switch state
when Menu.TOGGLE_ON
$(tag).text(Menu.TOGGLE_OFF)
when Menu.TOGGLE_OFF
$(tag).text(Menu.TOGGLE_ON)
@updateMasterToggle()
# M E T H O D S
# Create dynamically menu for given number of clusters.
# Use given set of colors for color coding to match visualization.
create : (@clusters, @colors) ->
# button IDs are b0, b1, b2...
# toggle IDs are t0, t1, t2...
# swatch IDs are c0, c1, c2...
for i in [0...@clusters]
html = "<span class='toggle' id='t#{i}'>[+]</span><span class='button' id='b#{i}'> Cluster</span><span class='color' id='c#{i}'> #{i} </span><br/>"
$("#menu").append(html)
$("#toggleAll").click(@onToggleAll)
for i in [0...@clusters]
$("#t" + String(i)).click( @onToggle )
$("#b" + String(i)).click( @onCluster )
@updateSwatches()
# Count how many toggles are on.
togglesOn : ->
result = 0
for i in [0...@clusters]
tag = "#t" + String(i)
state = $(tag).text()
if state is Menu.TOGGLE_ON then result++
return result
# Based on the state of all cluster toggles, set the master toggle.
updateMasterToggle : () ->
shown = @togglesOn()
switch shown
when 0 then $("#toggleAll").text(Menu.TOGGLE_OFF)
when @clusters then $("#toggleAll").text(Menu.TOGGLE_ON)
else $("#toggleAll").text(Menu.TOGGLE_MIX)
# Swatches have IDs: c0, c1, c2...
updateSwatches : ->
for i in [0...@clusters]
if i is @selected
$("#c" + String(i)).css( 'color', Palette.HIGHLIGHT.getStyle() )
else
$("#c" + String(i)).css( 'color', @colors[i].getStyle() )
# Cluster buttons have IDs: b0, b1, b2...
updateButtons : ->
for i in [0...@clusters]
if i is @selected
$("#b" + String(i)).css( 'color', Palette.HIGHLIGHT.getStyle() )
else
$("#b" + String(i)).css( 'color', Palette.BUTTON.getStyle() )
module.exports = Menu
| true | # Menu.coffee
# PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI
# PI:EMAIL:<EMAIL>END_PI
# Main application menu on the left side of the application window.
Panel = require('./Panel.coffee')
class Menu extends Panel
# E V E N T S
@EVENT_TOGGLE_ALL_ON : "EVENT_TOGGLE_ALL_ON"
@EVENT_TOGGLE_ALL_OFF : "EVENT_TOGGLE_ALL_OFF"
@EVENT_TOGGLE_ID : "EVENT_TOGGLE_ID"
@EVENT_CLUSTER_ID : "EVENT_CLUSTER_ID"
# C O N S T A N T S
@TOGGLE_ON : "[+]"
@TOGGLE_OFF : "[-]"
@TOGGLE_MIX : "[/]"
# M E M B E R S
clusters : 0 # total number of clusters
selected : -1 # currently selected cluster
colors : null # set of colors to use
# C O N S T R U C T O R
constructor : (id) ->
super(id)
# E V E N T H A N D L E R S
# Toggle visibility of all clusters at once.
onToggleAll : (event) =>
state = $("#toggleAll").text()
switch state
when Menu.TOGGLE_OFF, Menu.TOGGLE_MIX # turn all on
$("#toggleAll").text(Menu.TOGGLE_ON)
for i in [0...@clusters]
$("#t" + String(i)).text(Menu.TOGGLE_ON)
@notify(Menu.EVENT_TOGGLE_ALL_ON)
when Menu.TOGGLE_ON # turn all off
$("#toggleAll").text(Menu.TOGGLE_OFF)
for i in [0...@clusters]
$("#t" + String(i)).text(Menu.TOGGLE_OFF)
@notify(Menu.EVENT_TOGGLE_ALL_OFF)
onToggle : (event) =>
identifier = event.target.id
id = identifier.replace("t", "")
index = parseInt(id)
@doToggle(index)
@notify(Menu.EVENT_TOGGLE_ID, { id : index })
onCluster : (event) =>
# retrieve clicked cluster number
index = parseInt(event.target.id.replace("b", ""))
if @selected is index then @selected = -1 # unselect
else @selected = index # select
@updateSwatches()
@updateButtons()
@notify(Menu.EVENT_CLUSTER_ID, { id : index })
# Flip toggle given by its index.
doToggle : (index) ->
tag = "#t" + String(index)
state = $(tag).text()
switch state
when Menu.TOGGLE_ON
$(tag).text(Menu.TOGGLE_OFF)
when Menu.TOGGLE_OFF
$(tag).text(Menu.TOGGLE_ON)
@updateMasterToggle()
# M E T H O D S
# Create dynamically menu for given number of clusters.
# Use given set of colors for color coding to match visualization.
create : (@clusters, @colors) ->
# button IDs are b0, b1, b2...
# toggle IDs are t0, t1, t2...
# swatch IDs are c0, c1, c2...
for i in [0...@clusters]
html = "<span class='toggle' id='t#{i}'>[+]</span><span class='button' id='b#{i}'> Cluster</span><span class='color' id='c#{i}'> #{i} </span><br/>"
$("#menu").append(html)
$("#toggleAll").click(@onToggleAll)
for i in [0...@clusters]
$("#t" + String(i)).click( @onToggle )
$("#b" + String(i)).click( @onCluster )
@updateSwatches()
# Count how many toggles are on.
togglesOn : ->
result = 0
for i in [0...@clusters]
tag = "#t" + String(i)
state = $(tag).text()
if state is Menu.TOGGLE_ON then result++
return result
# Based on the state of all cluster toggles, set the master toggle.
updateMasterToggle : () ->
shown = @togglesOn()
switch shown
when 0 then $("#toggleAll").text(Menu.TOGGLE_OFF)
when @clusters then $("#toggleAll").text(Menu.TOGGLE_ON)
else $("#toggleAll").text(Menu.TOGGLE_MIX)
# Swatches have IDs: c0, c1, c2...
updateSwatches : ->
for i in [0...@clusters]
if i is @selected
$("#c" + String(i)).css( 'color', Palette.HIGHLIGHT.getStyle() )
else
$("#c" + String(i)).css( 'color', @colors[i].getStyle() )
# Cluster buttons have IDs: b0, b1, b2...
updateButtons : ->
for i in [0...@clusters]
if i is @selected
$("#b" + String(i)).css( 'color', Palette.HIGHLIGHT.getStyle() )
else
$("#b" + String(i)).css( 'color', Palette.BUTTON.getStyle() )
module.exports = Menu
|
[
{
"context": " line input:\n#\n# neat g project dummy author:\"John Doe\" keywords:foo,bar\n#\n# The hash arguments, once pa",
"end": 3103,
"score": 0.9998639822006226,
"start": 3095,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "ts` function,\n# will look like:\n#\n# {author: 'John Doe', keywords: ['foo', 'bar']}\n#\n# Basic types such ",
"end": 3235,
"score": 0.9998546838760376,
"start": 3227,
"tag": "NAME",
"value": "John Doe"
}
] | node_modules/neat/src/utils/commands.coffee | Montana-Studio/StarterDailyMediakit | 0 | # This file contains utilities to setup commands and generators.
# @toc
{spawn} = require 'child_process'
{resolve} = require 'path'
{puts, print, error} = require './logs'
Neat = require '../neat'
_ = Neat.i18n.getHelper()
#### Private
##### decorate
# Decorates an object with the specified property and value.
decorate = (target, property, value) ->
target[property] = value
target
#### Public
##### aliases
# Defines the aliases of the `target`. Aliases are used to defined
# the keywords for which the command respond.
#
# aliases 'f', 'foo', -> console.log 'command was called'
aliases = (aliases..., target) -> decorate target, 'aliases', aliases
##### asyncErrorTrap
# Trap error returned by asynchronous function in the callback arguments
# by generating a callback wrapper that will call the callback only if
# no errors was received. The error argument is not passed to the callback.
#
# fs.readFile "/path/to/file", asyncErrorTrap (content) ->
# # do something with content
#
# Optionally, a function can be passed as first argument to receive the error,
# typically the final callback you'll trigger in your async process.
#
# asyncFunction = (callback) ->
# path = "/path/to/file"
# fs.readFile path, asyncErrorTrap callback, (content) ->
# # do something with content
# callback? null, content
#
# If an error occurs, the callback is automatically triggered with the error
# as the first argument, following in that regard the pattern of node's async
# functions. You should take care to pass your results after a null argument,
# allowing callback to use the following pattern:
#
# asyncFunction asyncErrorTrap (results...) -> # etc...
asyncErrorTrap = (errCallback, callback) -> (err, args...) ->
[errCallback, callback] = [callback, errCallback] unless callback?
if err?
if errCallback? then return errCallback err else return err
callback?.apply null, args
##### deprecated
deprecated = (message, target) -> decorate target, 'deprecated', message
##### describe
# Defines the description of the `target`.
#
# describe 'This is a description', ->
# console.log 'command was called'
describe = (description, target) -> decorate target, 'description', description
##### environment
# Loads automatically the specified environment before triggering
# the `target`.
#
# environment 'test', ->
# console.log Neat.env.test? # true
environment = (env, target) -> decorate target, 'environment', env
##### hashArguments
# Converts an array of strings with a form such as `key:value`
# in an object with the corresponding properties.
#
# These are supposed to come from a command line input such as
# some limitations occurs:
#
# 1. There cannot be any spaces between the key, the colon and the value.
# 2. String values that will contains spaces must be wrapped into `"` or `'`.
# 3. There cannot be any spaces between the element of an array and the
# commas before and after it.
#
# For instance, in the following command line input:
#
# neat g project dummy author:"John Doe" keywords:foo,bar
#
# The hash arguments, once parsed by the `hashArguments` function,
# will look like:
#
# {author: 'John Doe', keywords: ['foo', 'bar']}
#
# Basic types such `String`, `Number`, `Boolean` and `Array` are supported
# as arguments value:
#
# integer:0 # 0
# float:0.5 # 0.5
# string:foo # 'foo'
# stringWithSpace:"foo bar" # 'foo bar'
# booleans:yes # true
# arrays:foo,10,false # ['foo', 10, false]
#
# As you may have notice, booleans are available with various aliases:
#
# * `true`: `true`, `on`, `yes`
# * `false`: `false`, `off`, `no`
hashArguments = (ary...) ->
ary = ary.flatten()
hash = {}
parse = (v) ->
switch true
when /^(false|no|off)$/.test v then false
when /^(true|yes|on)$/.test v then true
when /^(-*)\d+$/g.test v then parseInt v
when /^(-*)\d+\.\d+$/g.test v then parseFloat v
when ',' in String(v) then parse sub for sub in v.split ','
else v.replace /^('|")|('|")$/g, ''
for expr in ary
(hash[k] = true; continue) unless ':' in expr
[k,v] = expr.split ':'
if v.empty()
throw new Error _('neat.commands.invalid_arguments', expression: expr)
hash[k] = parse v
hash
##### help
# Defines the help of the `target`.
#
# help 'This is the help', ->
# console.log 'command was called'
help = (help, target) -> decorate target, 'help', help
##### neatTask
# Register a cake task that will run through Neat.
#
# exports.taskName = neatTask
# name: 'taskName' # required
# description: 'task description' # optional
# environment: 'production' # optional
# action: -> ... # required
neatTask = (options) ->
{name, action, description, environment} = options
throw new Error _('neat.tasks.no_name') unless name?
throw new Error _('neat.tasks.no_action') unless action?
action.environment = environment
action.description = description
taskAction = ->
{action, environment} = options
Neat.defaultEnvironment = environment if environment?
Neat.initEnvironment ->
Neat.beforeTask.dispatch -> action (status) ->
Neat.afterTask.dispatch status, ->
process.exit status
task name, description, taskAction
action
##### neatTaskAlias
neatTaskAlias = (source, alias, environment) ->
neatTask
name: alias
description: _('neat.tasks.alias', task: source)
environment: environment
action: (callback) ->
task = Neat.task(source)
task callback
##### run
# Runs the specified `command` with the passed-in `params`.
# The `callback` is called on the command exit if provided.
#
# run 'coffee', ['-pcb', 'console.log "foo"'], (status) ->
# console.log "command exited with status #{status}"
#
# You can also prevent the function to print the command output
# or register your own output listeners using the `options` hash.
#
# options =
# noStdout: true
# stdError: (data) -> # Do something with data
#
# run 'coffee', ['src/*'], options, (status) ->
# console.log "command exited with status #{status}"
run = (command, params, options, callback) ->
[callback, options] = [options, callback] if typeof options is 'function'
exe = spawn command, params
unless options?.noStdout?
exe.stdout.on 'data', options?.stdout || (data) -> print data.toString()
unless options?.noStderr?
exe.stderr.on 'data', options?.stderr || (data) -> print data.toString()
exe.on 'exit', (status) -> callback? status
exe
##### usages
# Defines the usages of the `target`.
#
# usages 'foo', 'foo [arg]', -> console.log 'command called'
usages = (usages..., target) -> decorate target, 'usages', usages
module.exports = {
aliases
asyncErrorTrap
decorate
describe
deprecated
environment
hashArguments
help
neatTask
neatTaskAlias
run
usages
}
| 189461 | # This file contains utilities to setup commands and generators.
# @toc
{spawn} = require 'child_process'
{resolve} = require 'path'
{puts, print, error} = require './logs'
Neat = require '../neat'
_ = Neat.i18n.getHelper()
#### Private
##### decorate
# Decorates an object with the specified property and value.
decorate = (target, property, value) ->
target[property] = value
target
#### Public
##### aliases
# Defines the aliases of the `target`. Aliases are used to defined
# the keywords for which the command respond.
#
# aliases 'f', 'foo', -> console.log 'command was called'
aliases = (aliases..., target) -> decorate target, 'aliases', aliases
##### asyncErrorTrap
# Trap error returned by asynchronous function in the callback arguments
# by generating a callback wrapper that will call the callback only if
# no errors was received. The error argument is not passed to the callback.
#
# fs.readFile "/path/to/file", asyncErrorTrap (content) ->
# # do something with content
#
# Optionally, a function can be passed as first argument to receive the error,
# typically the final callback you'll trigger in your async process.
#
# asyncFunction = (callback) ->
# path = "/path/to/file"
# fs.readFile path, asyncErrorTrap callback, (content) ->
# # do something with content
# callback? null, content
#
# If an error occurs, the callback is automatically triggered with the error
# as the first argument, following in that regard the pattern of node's async
# functions. You should take care to pass your results after a null argument,
# allowing callback to use the following pattern:
#
# asyncFunction asyncErrorTrap (results...) -> # etc...
asyncErrorTrap = (errCallback, callback) -> (err, args...) ->
[errCallback, callback] = [callback, errCallback] unless callback?
if err?
if errCallback? then return errCallback err else return err
callback?.apply null, args
##### deprecated
deprecated = (message, target) -> decorate target, 'deprecated', message
##### describe
# Defines the description of the `target`.
#
# describe 'This is a description', ->
# console.log 'command was called'
describe = (description, target) -> decorate target, 'description', description
##### environment
# Loads automatically the specified environment before triggering
# the `target`.
#
# environment 'test', ->
# console.log Neat.env.test? # true
environment = (env, target) -> decorate target, 'environment', env
##### hashArguments
# Converts an array of strings with a form such as `key:value`
# in an object with the corresponding properties.
#
# These are supposed to come from a command line input such as
# some limitations occurs:
#
# 1. There cannot be any spaces between the key, the colon and the value.
# 2. String values that will contains spaces must be wrapped into `"` or `'`.
# 3. There cannot be any spaces between the element of an array and the
# commas before and after it.
#
# For instance, in the following command line input:
#
# neat g project dummy author:"<NAME>" keywords:foo,bar
#
# The hash arguments, once parsed by the `hashArguments` function,
# will look like:
#
# {author: '<NAME>', keywords: ['foo', 'bar']}
#
# Basic types such `String`, `Number`, `Boolean` and `Array` are supported
# as arguments value:
#
# integer:0 # 0
# float:0.5 # 0.5
# string:foo # 'foo'
# stringWithSpace:"foo bar" # 'foo bar'
# booleans:yes # true
# arrays:foo,10,false # ['foo', 10, false]
#
# As you may have notice, booleans are available with various aliases:
#
# * `true`: `true`, `on`, `yes`
# * `false`: `false`, `off`, `no`
hashArguments = (ary...) ->
ary = ary.flatten()
hash = {}
parse = (v) ->
switch true
when /^(false|no|off)$/.test v then false
when /^(true|yes|on)$/.test v then true
when /^(-*)\d+$/g.test v then parseInt v
when /^(-*)\d+\.\d+$/g.test v then parseFloat v
when ',' in String(v) then parse sub for sub in v.split ','
else v.replace /^('|")|('|")$/g, ''
for expr in ary
(hash[k] = true; continue) unless ':' in expr
[k,v] = expr.split ':'
if v.empty()
throw new Error _('neat.commands.invalid_arguments', expression: expr)
hash[k] = parse v
hash
##### help
# Defines the help of the `target`.
#
# help 'This is the help', ->
# console.log 'command was called'
help = (help, target) -> decorate target, 'help', help
##### neatTask
# Register a cake task that will run through Neat.
#
# exports.taskName = neatTask
# name: 'taskName' # required
# description: 'task description' # optional
# environment: 'production' # optional
# action: -> ... # required
neatTask = (options) ->
{name, action, description, environment} = options
throw new Error _('neat.tasks.no_name') unless name?
throw new Error _('neat.tasks.no_action') unless action?
action.environment = environment
action.description = description
taskAction = ->
{action, environment} = options
Neat.defaultEnvironment = environment if environment?
Neat.initEnvironment ->
Neat.beforeTask.dispatch -> action (status) ->
Neat.afterTask.dispatch status, ->
process.exit status
task name, description, taskAction
action
##### neatTaskAlias
neatTaskAlias = (source, alias, environment) ->
neatTask
name: alias
description: _('neat.tasks.alias', task: source)
environment: environment
action: (callback) ->
task = Neat.task(source)
task callback
##### run
# Runs the specified `command` with the passed-in `params`.
# The `callback` is called on the command exit if provided.
#
# run 'coffee', ['-pcb', 'console.log "foo"'], (status) ->
# console.log "command exited with status #{status}"
#
# You can also prevent the function to print the command output
# or register your own output listeners using the `options` hash.
#
# options =
# noStdout: true
# stdError: (data) -> # Do something with data
#
# run 'coffee', ['src/*'], options, (status) ->
# console.log "command exited with status #{status}"
run = (command, params, options, callback) ->
[callback, options] = [options, callback] if typeof options is 'function'
exe = spawn command, params
unless options?.noStdout?
exe.stdout.on 'data', options?.stdout || (data) -> print data.toString()
unless options?.noStderr?
exe.stderr.on 'data', options?.stderr || (data) -> print data.toString()
exe.on 'exit', (status) -> callback? status
exe
##### usages
# Defines the usages of the `target`.
#
# usages 'foo', 'foo [arg]', -> console.log 'command called'
usages = (usages..., target) -> decorate target, 'usages', usages
module.exports = {
aliases
asyncErrorTrap
decorate
describe
deprecated
environment
hashArguments
help
neatTask
neatTaskAlias
run
usages
}
| true | # This file contains utilities to setup commands and generators.
# @toc
{spawn} = require 'child_process'
{resolve} = require 'path'
{puts, print, error} = require './logs'
Neat = require '../neat'
_ = Neat.i18n.getHelper()
#### Private
##### decorate
# Decorates an object with the specified property and value.
decorate = (target, property, value) ->
target[property] = value
target
#### Public
##### aliases
# Defines the aliases of the `target`. Aliases are used to defined
# the keywords for which the command respond.
#
# aliases 'f', 'foo', -> console.log 'command was called'
aliases = (aliases..., target) -> decorate target, 'aliases', aliases
##### asyncErrorTrap
# Trap error returned by asynchronous function in the callback arguments
# by generating a callback wrapper that will call the callback only if
# no errors was received. The error argument is not passed to the callback.
#
# fs.readFile "/path/to/file", asyncErrorTrap (content) ->
# # do something with content
#
# Optionally, a function can be passed as first argument to receive the error,
# typically the final callback you'll trigger in your async process.
#
# asyncFunction = (callback) ->
# path = "/path/to/file"
# fs.readFile path, asyncErrorTrap callback, (content) ->
# # do something with content
# callback? null, content
#
# If an error occurs, the callback is automatically triggered with the error
# as the first argument, following in that regard the pattern of node's async
# functions. You should take care to pass your results after a null argument,
# allowing callback to use the following pattern:
#
# asyncFunction asyncErrorTrap (results...) -> # etc...
asyncErrorTrap = (errCallback, callback) -> (err, args...) ->
[errCallback, callback] = [callback, errCallback] unless callback?
if err?
if errCallback? then return errCallback err else return err
callback?.apply null, args
##### deprecated
deprecated = (message, target) -> decorate target, 'deprecated', message
##### describe
# Defines the description of the `target`.
#
# describe 'This is a description', ->
# console.log 'command was called'
describe = (description, target) -> decorate target, 'description', description
##### environment
# Loads automatically the specified environment before triggering
# the `target`.
#
# environment 'test', ->
# console.log Neat.env.test? # true
environment = (env, target) -> decorate target, 'environment', env
##### hashArguments
# Converts an array of strings with a form such as `key:value`
# in an object with the corresponding properties.
#
# These are supposed to come from a command line input such as
# some limitations occurs:
#
# 1. There cannot be any spaces between the key, the colon and the value.
# 2. String values that will contains spaces must be wrapped into `"` or `'`.
# 3. There cannot be any spaces between the element of an array and the
# commas before and after it.
#
# For instance, in the following command line input:
#
# neat g project dummy author:"PI:NAME:<NAME>END_PI" keywords:foo,bar
#
# The hash arguments, once parsed by the `hashArguments` function,
# will look like:
#
# {author: 'PI:NAME:<NAME>END_PI', keywords: ['foo', 'bar']}
#
# Basic types such `String`, `Number`, `Boolean` and `Array` are supported
# as arguments value:
#
# integer:0 # 0
# float:0.5 # 0.5
# string:foo # 'foo'
# stringWithSpace:"foo bar" # 'foo bar'
# booleans:yes # true
# arrays:foo,10,false # ['foo', 10, false]
#
# As you may have notice, booleans are available with various aliases:
#
# * `true`: `true`, `on`, `yes`
# * `false`: `false`, `off`, `no`
hashArguments = (ary...) ->
ary = ary.flatten()
hash = {}
parse = (v) ->
switch true
when /^(false|no|off)$/.test v then false
when /^(true|yes|on)$/.test v then true
when /^(-*)\d+$/g.test v then parseInt v
when /^(-*)\d+\.\d+$/g.test v then parseFloat v
when ',' in String(v) then parse sub for sub in v.split ','
else v.replace /^('|")|('|")$/g, ''
for expr in ary
(hash[k] = true; continue) unless ':' in expr
[k,v] = expr.split ':'
if v.empty()
throw new Error _('neat.commands.invalid_arguments', expression: expr)
hash[k] = parse v
hash
##### help
# Defines the help of the `target`.
#
# help 'This is the help', ->
# console.log 'command was called'
help = (help, target) -> decorate target, 'help', help
##### neatTask
# Register a cake task that will run through Neat.
#
# exports.taskName = neatTask
# name: 'taskName' # required
# description: 'task description' # optional
# environment: 'production' # optional
# action: -> ... # required
neatTask = (options) ->
{name, action, description, environment} = options
throw new Error _('neat.tasks.no_name') unless name?
throw new Error _('neat.tasks.no_action') unless action?
action.environment = environment
action.description = description
taskAction = ->
{action, environment} = options
Neat.defaultEnvironment = environment if environment?
Neat.initEnvironment ->
Neat.beforeTask.dispatch -> action (status) ->
Neat.afterTask.dispatch status, ->
process.exit status
task name, description, taskAction
action
##### neatTaskAlias
neatTaskAlias = (source, alias, environment) ->
neatTask
name: alias
description: _('neat.tasks.alias', task: source)
environment: environment
action: (callback) ->
task = Neat.task(source)
task callback
##### run
# Runs the specified `command` with the passed-in `params`.
# The `callback` is called on the command exit if provided.
#
# run 'coffee', ['-pcb', 'console.log "foo"'], (status) ->
# console.log "command exited with status #{status}"
#
# You can also prevent the function to print the command output
# or register your own output listeners using the `options` hash.
#
# options =
# noStdout: true
# stdError: (data) -> # Do something with data
#
# run 'coffee', ['src/*'], options, (status) ->
# console.log "command exited with status #{status}"
run = (command, params, options, callback) ->
[callback, options] = [options, callback] if typeof options is 'function'
exe = spawn command, params
unless options?.noStdout?
exe.stdout.on 'data', options?.stdout || (data) -> print data.toString()
unless options?.noStderr?
exe.stderr.on 'data', options?.stderr || (data) -> print data.toString()
exe.on 'exit', (status) -> callback? status
exe
##### usages
# Defines the usages of the `target`.
#
# usages 'foo', 'foo [arg]', -> console.log 'command called'
usages = (usages..., target) -> decorate target, 'usages', usages
module.exports = {
aliases
asyncErrorTrap
decorate
describe
deprecated
environment
hashArguments
help
neatTask
neatTaskAlias
run
usages
}
|
[
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri",
"end": 42,
"score": 0.9998428225517273,
"start": 24,
"tag": "NAME",
"value": "Alexander Cherniuk"
},
{
"context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistribution and use in ",
"end": 60,
"score": 0.999928891658783,
"start": 44,
"tag": "EMAIL",
"value": "ts33kr@gmail.com"
}
] | library/semantic/abstract.coffee | ts33kr/granite | 6 | ###
Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
async = require "async"
uuid = require "node-uuid"
teacup = require "teacup"
assert = require "assert"
{Archetype} = require "../nucleus/arche"
{remote, cc} = require "../membrane/remote"
{Composition} = require "../nucleus/compose"
{GoogleFonts} = require "../shipped/fonting"
# This is an abstract base class for all the front-end widgets. It
# is important to understand that widgets are not services. They do
# not carry any sort of server or data related functionality at all.
# All the widgets are only functional UIX components. They are meant
# to be used for expressing visual abstractions and compounds that
# are exposing some sort of functionality or some of internal API.
module.exports.Widget = cc -> class Widget extends Archetype
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# Bring the tags definitions of the `Teacup` template engine
# to the current class scope on the client and server sites.
# Remember, that the `teacup` symbol is constantly available
# on both sites, respecitvely. Also, take into consideration
# that when you need a client-site template in the service,
# this is all done automatically and there if no need for it.
# Please see the `TemplateToolkit` class for more information.
{div, renderable} = teacup
# This prototype definition is a template-function driven by
# the `Teacup` templating engine. When widget instantiated,
# this defintion is used to render the root DOM element of
# the widget and store it in the widget instance under the
# instance variable with the same name of `element`. Please
# refer to the `TemplateToolkit` class for an information.
# Also, please refer to the `Teacup` manual for reference.
element: -> div ".generic-widget-element"
# Create a subwidget definition, using the supplied signature.
# The signature should be `token: method` object descriptor. It
# specifies the name of the subwidget and its implementation. A
# method will be created with this name. When called, a method
# should create and return a jQuery element. This element then
# will be wrapped with the special class instance of `Widget`.
# This is a shortcut for quick widget design and composition.
@subwidget: (signature) ->
blueprint = this # save to use it from closure
token = (try _.first(_.keys(signature))) or no
value = (try _.first(_.values(signature))) or no
invalid = "received invalid invocation signature"
unnamed = "could not find correct subwidget name"
implement = "implementation has to be a function"
assert _.isObject(@prototype), "invalid context"
assert _.isObject(signature or false), invalid
assert _.isFunction(value or false), implement
assert _.isString(token or undefined), unnamed
return this.prototype[token] = (params...) ->
sbce = "failed to create subwidget element"
sbpc = "failed to properly init a subwidget"
widget = value.apply this, arguments or []
reference = "#{@reference}-#{token}" # ID
assert widget and widget.length is 1, sbce
anonym = class Subwidget extends blueprint
anonym::predefined = -> widget # constant
instance = new anonym @element, reference
instance.$.addClass "semantic-subwidget"
assert instance.element is widget, sbpc
return instance # return wrapped widget
# This method is invoked if this widget has been declared for a
# reconfiguration, with respect to some service. This is usually
# achieved by the reconfiguration mechanism. What this method is
# actually doing - it extends a widget instance with a service
# methods, that are still bound to the service (to work). Please
# consult with the `reconfigure` method of the `TransitTookit`.
@reconfigure: (service) ->
notService = "supplied service is not a object"
notCorrect = "supplied service looks malformed"
reconfiged = "Reconfig %s class with %s service"
assert _.isObject(service or null), notService
assert _.isString(service.service), notCorrect
assert _.isObject proto = @prototype or Object()
assert exist = (src) -> (v, key) -> key of src
assert fbinder = (f) -> return f.bind(service)
assert _.isObject cloned = Composition.cloner @
cloned.rebased this # god forbidden black magic
assert _.extend cloned, $reconfigured: 1 # mark
execute = (arbitraryValueVect) -> return cloned
execute cloned::$reconfigure = (parameters) ->
assert methods = _.pick(service, _.isFunction)
assert methods = {} unless _.isObject methods
assert bounded = _.mapValues methods, fbinder
assert clensed = _.omit bounded, exist(proto)
assert identify = try this.identify().underline
assert srvident = try service.service.underline
assert _.extend this or cloned::, clensed or {}
logger.silly reconfiged, identify, srvident
# The autorun method that generates the barebones toolkit for
# the current widget. This toolkit contains most widely used
# routines and shorthands to manipulate the element of widget
# or its contents. In case if widget constructor is overriden
# and autorun is not automatically called, be sure to invoke
# this method manually, as it sets up important scaffolding.
generateToolkit: (element) ->
missing = "the root element of widget not located"
incomps = "the root element of widget seem broken"
message = "Generating HTML toolkit in a %s widget"
deducts = (fx) -> (fx.element and fx.$) or $(fx)
assert cident = @constructor.identify().underline
assert _.isObject(@element or undefined), missing
assert (try @element?.length or no) >= 0, incomps
logger.silly message.toString(), cident.underline
@element.addClass "semantic-widget", @reference
Object.defineProperty this, "$", get: => @element
Object.defineProperty this, "id", value: uuid.v1()
assert @element.attr id: @id.toString() # UUID v1
assert @add = (fx) => @element.append deducts fx
assert @classes = => return @element.attr "class"
assert @siblings = => return $(".#{@reference}")
assert @remove = => return this.element.remove()
assert @show = => this.element.show arguments...
assert @hide = => this.element.hide arguments...
assert @find = => this.element.find arguments...
assert @attr = => this.element.attr arguments...
assert @html = => this.element.html arguments...
assert @text = => this.element.text arguments...
# A generic widget constructor that takes care of most of the
# boilerplating of creating the element within the container,
# marking it with the proper identifications and preparing an
# internal APIs and shorthands for convenient access to some
# of the most basic functionality related to a visual widget.
# The reference has to be a bare (without a dot) HTML class.
constructor: (@container, @reference, @payload) ->
msg = "Constructing widget %s with reference %s"
ptf = "no valid template-function for an element"
noContainer = "no valid container object supplied"
noReference = "no valid reference string supplied"
noPayload = "something wrong with payload function"
@$reconfigure?.apply this, arguments # if it exists
@payload = (->) if _.isEmpty @payload or undefined
hasParents = => not _.isEmpty try @element.parent()
assert _.isObject(@container or null), noContainer
assert _.isString(@reference or null), noReference
assert _.isFunction(@payload or null), noPayload
assert _.isFunction(@constructor::element), ptf
@element = $ renderable(@constructor::element) @
@element = @constructor::predefined?() or @element
@element.appendTo @container unless hasParents()
@generateToolkit(this.element) # makeup toolkit
assert identify = @constructor.identify().bold
super if _.isObject try @constructor.__super__
this.constructor.configure().call this, (r) =>
@payload.call this, @element, @reference
assert ref = @reference.toString().bold
logger.debug msg, identify, ref.bold
| 9812 | ###
Copyright (c) 2013, <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
async = require "async"
uuid = require "node-uuid"
teacup = require "teacup"
assert = require "assert"
{Archetype} = require "../nucleus/arche"
{remote, cc} = require "../membrane/remote"
{Composition} = require "../nucleus/compose"
{GoogleFonts} = require "../shipped/fonting"
# This is an abstract base class for all the front-end widgets. It
# is important to understand that widgets are not services. They do
# not carry any sort of server or data related functionality at all.
# All the widgets are only functional UIX components. They are meant
# to be used for expressing visual abstractions and compounds that
# are exposing some sort of functionality or some of internal API.
module.exports.Widget = cc -> class Widget extends Archetype
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# Bring the tags definitions of the `Teacup` template engine
# to the current class scope on the client and server sites.
# Remember, that the `teacup` symbol is constantly available
# on both sites, respecitvely. Also, take into consideration
# that when you need a client-site template in the service,
# this is all done automatically and there if no need for it.
# Please see the `TemplateToolkit` class for more information.
{div, renderable} = teacup
# This prototype definition is a template-function driven by
# the `Teacup` templating engine. When widget instantiated,
# this defintion is used to render the root DOM element of
# the widget and store it in the widget instance under the
# instance variable with the same name of `element`. Please
# refer to the `TemplateToolkit` class for an information.
# Also, please refer to the `Teacup` manual for reference.
element: -> div ".generic-widget-element"
# Create a subwidget definition, using the supplied signature.
# The signature should be `token: method` object descriptor. It
# specifies the name of the subwidget and its implementation. A
# method will be created with this name. When called, a method
# should create and return a jQuery element. This element then
# will be wrapped with the special class instance of `Widget`.
# This is a shortcut for quick widget design and composition.
@subwidget: (signature) ->
blueprint = this # save to use it from closure
token = (try _.first(_.keys(signature))) or no
value = (try _.first(_.values(signature))) or no
invalid = "received invalid invocation signature"
unnamed = "could not find correct subwidget name"
implement = "implementation has to be a function"
assert _.isObject(@prototype), "invalid context"
assert _.isObject(signature or false), invalid
assert _.isFunction(value or false), implement
assert _.isString(token or undefined), unnamed
return this.prototype[token] = (params...) ->
sbce = "failed to create subwidget element"
sbpc = "failed to properly init a subwidget"
widget = value.apply this, arguments or []
reference = "#{@reference}-#{token}" # ID
assert widget and widget.length is 1, sbce
anonym = class Subwidget extends blueprint
anonym::predefined = -> widget # constant
instance = new anonym @element, reference
instance.$.addClass "semantic-subwidget"
assert instance.element is widget, sbpc
return instance # return wrapped widget
# This method is invoked if this widget has been declared for a
# reconfiguration, with respect to some service. This is usually
# achieved by the reconfiguration mechanism. What this method is
# actually doing - it extends a widget instance with a service
# methods, that are still bound to the service (to work). Please
# consult with the `reconfigure` method of the `TransitTookit`.
@reconfigure: (service) ->
notService = "supplied service is not a object"
notCorrect = "supplied service looks malformed"
reconfiged = "Reconfig %s class with %s service"
assert _.isObject(service or null), notService
assert _.isString(service.service), notCorrect
assert _.isObject proto = @prototype or Object()
assert exist = (src) -> (v, key) -> key of src
assert fbinder = (f) -> return f.bind(service)
assert _.isObject cloned = Composition.cloner @
cloned.rebased this # god forbidden black magic
assert _.extend cloned, $reconfigured: 1 # mark
execute = (arbitraryValueVect) -> return cloned
execute cloned::$reconfigure = (parameters) ->
assert methods = _.pick(service, _.isFunction)
assert methods = {} unless _.isObject methods
assert bounded = _.mapValues methods, fbinder
assert clensed = _.omit bounded, exist(proto)
assert identify = try this.identify().underline
assert srvident = try service.service.underline
assert _.extend this or cloned::, clensed or {}
logger.silly reconfiged, identify, srvident
# The autorun method that generates the barebones toolkit for
# the current widget. This toolkit contains most widely used
# routines and shorthands to manipulate the element of widget
# or its contents. In case if widget constructor is overriden
# and autorun is not automatically called, be sure to invoke
# this method manually, as it sets up important scaffolding.
generateToolkit: (element) ->
missing = "the root element of widget not located"
incomps = "the root element of widget seem broken"
message = "Generating HTML toolkit in a %s widget"
deducts = (fx) -> (fx.element and fx.$) or $(fx)
assert cident = @constructor.identify().underline
assert _.isObject(@element or undefined), missing
assert (try @element?.length or no) >= 0, incomps
logger.silly message.toString(), cident.underline
@element.addClass "semantic-widget", @reference
Object.defineProperty this, "$", get: => @element
Object.defineProperty this, "id", value: uuid.v1()
assert @element.attr id: @id.toString() # UUID v1
assert @add = (fx) => @element.append deducts fx
assert @classes = => return @element.attr "class"
assert @siblings = => return $(".#{@reference}")
assert @remove = => return this.element.remove()
assert @show = => this.element.show arguments...
assert @hide = => this.element.hide arguments...
assert @find = => this.element.find arguments...
assert @attr = => this.element.attr arguments...
assert @html = => this.element.html arguments...
assert @text = => this.element.text arguments...
# A generic widget constructor that takes care of most of the
# boilerplating of creating the element within the container,
# marking it with the proper identifications and preparing an
# internal APIs and shorthands for convenient access to some
# of the most basic functionality related to a visual widget.
# The reference has to be a bare (without a dot) HTML class.
constructor: (@container, @reference, @payload) ->
msg = "Constructing widget %s with reference %s"
ptf = "no valid template-function for an element"
noContainer = "no valid container object supplied"
noReference = "no valid reference string supplied"
noPayload = "something wrong with payload function"
@$reconfigure?.apply this, arguments # if it exists
@payload = (->) if _.isEmpty @payload or undefined
hasParents = => not _.isEmpty try @element.parent()
assert _.isObject(@container or null), noContainer
assert _.isString(@reference or null), noReference
assert _.isFunction(@payload or null), noPayload
assert _.isFunction(@constructor::element), ptf
@element = $ renderable(@constructor::element) @
@element = @constructor::predefined?() or @element
@element.appendTo @container unless hasParents()
@generateToolkit(this.element) # makeup toolkit
assert identify = @constructor.identify().bold
super if _.isObject try @constructor.__super__
this.constructor.configure().call this, (r) =>
@payload.call this, @element, @reference
assert ref = @reference.toString().bold
logger.debug msg, identify, ref.bold
| true | ###
Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
_ = require "lodash"
async = require "async"
uuid = require "node-uuid"
teacup = require "teacup"
assert = require "assert"
{Archetype} = require "../nucleus/arche"
{remote, cc} = require "../membrane/remote"
{Composition} = require "../nucleus/compose"
{GoogleFonts} = require "../shipped/fonting"
# This is an abstract base class for all the front-end widgets. It
# is important to understand that widgets are not services. They do
# not carry any sort of server or data related functionality at all.
# All the widgets are only functional UIX components. They are meant
# to be used for expressing visual abstractions and compounds that
# are exposing some sort of functionality or some of internal API.
module.exports.Widget = cc -> class Widget extends Archetype
# This is a marker that indicates to some internal subsystems
# that this class has to be considered abstract and therefore
# can not be treated as a complete class implementation. This
# mainly is used to exclude or account for abstract classes.
# Once inherited from, the inheritee is not abstract anymore.
@abstract yes
# Bring the tags definitions of the `Teacup` template engine
# to the current class scope on the client and server sites.
# Remember, that the `teacup` symbol is constantly available
# on both sites, respecitvely. Also, take into consideration
# that when you need a client-site template in the service,
# this is all done automatically and there if no need for it.
# Please see the `TemplateToolkit` class for more information.
{div, renderable} = teacup
# This prototype definition is a template-function driven by
# the `Teacup` templating engine. When widget instantiated,
# this defintion is used to render the root DOM element of
# the widget and store it in the widget instance under the
# instance variable with the same name of `element`. Please
# refer to the `TemplateToolkit` class for an information.
# Also, please refer to the `Teacup` manual for reference.
element: -> div ".generic-widget-element"
# Create a subwidget definition, using the supplied signature.
# The signature should be `token: method` object descriptor. It
# specifies the name of the subwidget and its implementation. A
# method will be created with this name. When called, a method
# should create and return a jQuery element. This element then
# will be wrapped with the special class instance of `Widget`.
# This is a shortcut for quick widget design and composition.
@subwidget: (signature) ->
blueprint = this # save to use it from closure
token = (try _.first(_.keys(signature))) or no
value = (try _.first(_.values(signature))) or no
invalid = "received invalid invocation signature"
unnamed = "could not find correct subwidget name"
implement = "implementation has to be a function"
assert _.isObject(@prototype), "invalid context"
assert _.isObject(signature or false), invalid
assert _.isFunction(value or false), implement
assert _.isString(token or undefined), unnamed
return this.prototype[token] = (params...) ->
sbce = "failed to create subwidget element"
sbpc = "failed to properly init a subwidget"
widget = value.apply this, arguments or []
reference = "#{@reference}-#{token}" # ID
assert widget and widget.length is 1, sbce
anonym = class Subwidget extends blueprint
anonym::predefined = -> widget # constant
instance = new anonym @element, reference
instance.$.addClass "semantic-subwidget"
assert instance.element is widget, sbpc
return instance # return wrapped widget
# This method is invoked if this widget has been declared for a
# reconfiguration, with respect to some service. This is usually
# achieved by the reconfiguration mechanism. What this method is
# actually doing - it extends a widget instance with a service
# methods, that are still bound to the service (to work). Please
# consult with the `reconfigure` method of the `TransitTookit`.
@reconfigure: (service) ->
notService = "supplied service is not a object"
notCorrect = "supplied service looks malformed"
reconfiged = "Reconfig %s class with %s service"
assert _.isObject(service or null), notService
assert _.isString(service.service), notCorrect
assert _.isObject proto = @prototype or Object()
assert exist = (src) -> (v, key) -> key of src
assert fbinder = (f) -> return f.bind(service)
assert _.isObject cloned = Composition.cloner @
cloned.rebased this # god forbidden black magic
assert _.extend cloned, $reconfigured: 1 # mark
execute = (arbitraryValueVect) -> return cloned
execute cloned::$reconfigure = (parameters) ->
assert methods = _.pick(service, _.isFunction)
assert methods = {} unless _.isObject methods
assert bounded = _.mapValues methods, fbinder
assert clensed = _.omit bounded, exist(proto)
assert identify = try this.identify().underline
assert srvident = try service.service.underline
assert _.extend this or cloned::, clensed or {}
logger.silly reconfiged, identify, srvident
# The autorun method that generates the barebones toolkit for
# the current widget. This toolkit contains most widely used
# routines and shorthands to manipulate the element of widget
# or its contents. In case if widget constructor is overriden
# and autorun is not automatically called, be sure to invoke
# this method manually, as it sets up important scaffolding.
generateToolkit: (element) ->
missing = "the root element of widget not located"
incomps = "the root element of widget seem broken"
message = "Generating HTML toolkit in a %s widget"
deducts = (fx) -> (fx.element and fx.$) or $(fx)
assert cident = @constructor.identify().underline
assert _.isObject(@element or undefined), missing
assert (try @element?.length or no) >= 0, incomps
logger.silly message.toString(), cident.underline
@element.addClass "semantic-widget", @reference
Object.defineProperty this, "$", get: => @element
Object.defineProperty this, "id", value: uuid.v1()
assert @element.attr id: @id.toString() # UUID v1
assert @add = (fx) => @element.append deducts fx
assert @classes = => return @element.attr "class"
assert @siblings = => return $(".#{@reference}")
assert @remove = => return this.element.remove()
assert @show = => this.element.show arguments...
assert @hide = => this.element.hide arguments...
assert @find = => this.element.find arguments...
assert @attr = => this.element.attr arguments...
assert @html = => this.element.html arguments...
assert @text = => this.element.text arguments...
# A generic widget constructor that takes care of most of the
# boilerplating of creating the element within the container,
# marking it with the proper identifications and preparing an
# internal APIs and shorthands for convenient access to some
# of the most basic functionality related to a visual widget.
# The reference has to be a bare (without a dot) HTML class.
constructor: (@container, @reference, @payload) ->
msg = "Constructing widget %s with reference %s"
ptf = "no valid template-function for an element"
noContainer = "no valid container object supplied"
noReference = "no valid reference string supplied"
noPayload = "something wrong with payload function"
@$reconfigure?.apply this, arguments # if it exists
@payload = (->) if _.isEmpty @payload or undefined
hasParents = => not _.isEmpty try @element.parent()
assert _.isObject(@container or null), noContainer
assert _.isString(@reference or null), noReference
assert _.isFunction(@payload or null), noPayload
assert _.isFunction(@constructor::element), ptf
@element = $ renderable(@constructor::element) @
@element = @constructor::predefined?() or @element
@element.appendTo @container unless hasParents()
@generateToolkit(this.element) # makeup toolkit
assert identify = @constructor.identify().bold
super if _.isObject try @constructor.__super__
this.constructor.configure().call this, (r) =>
@payload.call this, @element, @reference
assert ref = @reference.toString().bold
logger.debug msg, identify, ref.bold
|
[
{
"context": "an admin that will balk at the stub\"\n\nusers: {\n \"herb\": {}\n \"basil\": {}\n}\n\nteams: {\n \"cabal\": {\n l",
"end": 84,
"score": 0.9963794946670532,
"start": 80,
"tag": "USERNAME",
"value": "herb"
},
{
"context": " will balk at the stub\"\n\nusers: {\n \"herb\": {}\n \"basil\": {}\n}\n\nteams: {\n \"cabal\": {\n links: [\n ",
"end": 98,
"score": 0.9705899953842163,
"start": 93,
"tag": "USERNAME",
"value": "basil"
},
{
"context": " signer: \"basil\"\n members:\n owner: [\"basil\"]\n admin: [\"herb\"]\n ,\n type: \"invi",
"end": 220,
"score": 0.9456520080566406,
"start": 215,
"tag": "USERNAME",
"value": "basil"
},
{
"context": "embers:\n owner: [\"basil\"]\n admin: [\"herb\"]\n ,\n type: \"invite\"\n signer: \"basil",
"end": 244,
"score": 0.9970559477806091,
"start": 240,
"tag": "USERNAME",
"value": "herb"
},
{
"context": "\n invites:\n admin: [ {\n id: \"54eafff3400b5bcd8b40bff3d225ab27\",\n name: \"max+be6ef086a4a5@keyba.se\",\n ",
"end": 377,
"score": 0.9607008099555969,
"start": 345,
"tag": "KEY",
"value": "54eafff3400b5bcd8b40bff3d225ab27"
},
{
"context": "eafff3400b5bcd8b40bff3d225ab27\",\n name: \"max+be6ef086a4a5@keyba.se\",\n type: \"email\"\n } ]\n\n ]\n }\n",
"end": 422,
"score": 0.999925971031189,
"start": 397,
"tag": "EMAIL",
"value": "max+be6ef086a4a5@keyba.se"
}
] | teamchains/inputs/stub_admin.iced | keybase/keybase-test-vectors | 4 | description: "Stub a link for an admin that will balk at the stub"
users: {
"herb": {}
"basil": {}
}
teams: {
"cabal": {
links: [
type: "root"
signer: "basil"
members:
owner: ["basil"]
admin: ["herb"]
,
type: "invite"
signer: "basil"
invites:
admin: [ {
id: "54eafff3400b5bcd8b40bff3d225ab27",
name: "max+be6ef086a4a5@keyba.se",
type: "email"
} ]
]
}
}
sessions: [
loads: [
stub: [2]
need_admin: true
error: true
error_type: "StubbedError"
error_substr: "seqno 2"
]
,
loads: [
upto: 1
need_admin: true
,
need_admin: true
stub: [2]
error: true
error_type: "StubbedError"
error_substr: "seqno 2"
]
]
| 7041 | description: "Stub a link for an admin that will balk at the stub"
users: {
"herb": {}
"basil": {}
}
teams: {
"cabal": {
links: [
type: "root"
signer: "basil"
members:
owner: ["basil"]
admin: ["herb"]
,
type: "invite"
signer: "basil"
invites:
admin: [ {
id: "<KEY>",
name: "<EMAIL>",
type: "email"
} ]
]
}
}
sessions: [
loads: [
stub: [2]
need_admin: true
error: true
error_type: "StubbedError"
error_substr: "seqno 2"
]
,
loads: [
upto: 1
need_admin: true
,
need_admin: true
stub: [2]
error: true
error_type: "StubbedError"
error_substr: "seqno 2"
]
]
| true | description: "Stub a link for an admin that will balk at the stub"
users: {
"herb": {}
"basil": {}
}
teams: {
"cabal": {
links: [
type: "root"
signer: "basil"
members:
owner: ["basil"]
admin: ["herb"]
,
type: "invite"
signer: "basil"
invites:
admin: [ {
id: "PI:KEY:<KEY>END_PI",
name: "PI:EMAIL:<EMAIL>END_PI",
type: "email"
} ]
]
}
}
sessions: [
loads: [
stub: [2]
need_admin: true
error: true
error_type: "StubbedError"
error_substr: "seqno 2"
]
,
loads: [
upto: 1
need_admin: true
,
need_admin: true
stub: [2]
error: true
error_type: "StubbedError"
error_substr: "seqno 2"
]
]
|
[
{
"context": "</div>\n </div>')\n\n person =\n name: 'Jasmine Taylor'\n email: 'jasmine.tailor@example.com'\n\n d",
"end": 350,
"score": 0.9998875856399536,
"start": 336,
"tag": "NAME",
"value": "Jasmine Taylor"
},
{
"context": "son =\n name: 'Jasmine Taylor'\n email: 'jasmine.tailor@example.com'\n\n doc.find('.person').render person\n data ",
"end": 392,
"score": 0.9999285936355591,
"start": 366,
"tag": "EMAIL",
"value": "jasmine.tailor@example.com"
},
{
"context": "</div>\n </div>')\n\n person =\n name: 'Jasmine Taylor'\n email: 'jasmine.tailor@example.com'\n\n d",
"end": 762,
"score": 0.9998787045478821,
"start": 748,
"tag": "NAME",
"value": "Jasmine Taylor"
},
{
"context": "son =\n name: 'Jasmine Taylor'\n email: 'jasmine.tailor@example.com'\n\n doc.find('.person').render person\n data ",
"end": 804,
"score": 0.9999312162399292,
"start": 778,
"tag": "EMAIL",
"value": "jasmine.tailor@example.com"
},
{
"context": "nd('.person .name').data('data')\n data.name = 'Frank Sinatra'\n\n expect(data.name).toEqual(person.name)",
"end": 925,
"score": 0.9997997283935547,
"start": 912,
"tag": "NAME",
"value": "Frank Sinatra"
}
] | spec/data_references_spec.coffee | dineshkummarc/transparency | 1 | require './spec_helper'
require '../src/jquery.transparency'
describe "Transparency", ->
it "should provide reference to original data", ->
doc = jQuery(
'<div>
<div class="person">
<span class="name"></span>
<span class="email"></span>
</div>
</div>')
person =
name: 'Jasmine Taylor'
email: 'jasmine.tailor@example.com'
doc.find('.person').render person
data = doc.find('.name').data('data')
expect(data).toEqual(person)
it "should allow updating original data", ->
doc = jQuery(
'<div>
<div class="person">
<span class="name"></span>
<span class="email"></span>
</div>
</div>')
person =
name: 'Jasmine Taylor'
email: 'jasmine.tailor@example.com'
doc.find('.person').render person
data = doc.find('.person .name').data('data')
data.name = 'Frank Sinatra'
expect(data.name).toEqual(person.name) | 2531 | require './spec_helper'
require '../src/jquery.transparency'
describe "Transparency", ->
it "should provide reference to original data", ->
doc = jQuery(
'<div>
<div class="person">
<span class="name"></span>
<span class="email"></span>
</div>
</div>')
person =
name: '<NAME>'
email: '<EMAIL>'
doc.find('.person').render person
data = doc.find('.name').data('data')
expect(data).toEqual(person)
it "should allow updating original data", ->
doc = jQuery(
'<div>
<div class="person">
<span class="name"></span>
<span class="email"></span>
</div>
</div>')
person =
name: '<NAME>'
email: '<EMAIL>'
doc.find('.person').render person
data = doc.find('.person .name').data('data')
data.name = '<NAME>'
expect(data.name).toEqual(person.name) | true | require './spec_helper'
require '../src/jquery.transparency'
describe "Transparency", ->
it "should provide reference to original data", ->
doc = jQuery(
'<div>
<div class="person">
<span class="name"></span>
<span class="email"></span>
</div>
</div>')
person =
name: 'PI:NAME:<NAME>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
doc.find('.person').render person
data = doc.find('.name').data('data')
expect(data).toEqual(person)
it "should allow updating original data", ->
doc = jQuery(
'<div>
<div class="person">
<span class="name"></span>
<span class="email"></span>
</div>
</div>')
person =
name: 'PI:NAME:<NAME>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
doc.find('.person').render person
data = doc.find('.person .name').data('data')
data.name = 'PI:NAME:<NAME>END_PI'
expect(data.name).toEqual(person.name) |
[
{
"context": "n\nsecuredServer = fusker.http.createServer 8081, 'admin', 'pass123'\n\nio.sockets.on 'connection', (socket)",
"end": 537,
"score": 0.7180964350700378,
"start": 532,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "Server = fusker.http.createServer 8081, 'admin', 'pass123'\n\nio.sockets.on 'connection', (socket) ->\n\n sock",
"end": 548,
"score": 0.9971694946289062,
"start": 541,
"tag": "PASSWORD",
"value": "pass123"
}
] | examples/test.coffee | wearefractal/fusker | 36 | fusker = require '../lib/main'
fusker.config.dir = __dirname
fusker.config.banLength = 1
fusker.config.verbose = true
fusker.http.detect 'csrf', 'xss', 'sqli', 'lfi', '404'
fusker.http.punish 'blacklist', 'bush'
fusker.socket.detect 'xss', 'sqli', 'lfi'
fusker.socket.punish 'blacklist'
server = fusker.http.createServer 8080
io = fusker.socket.listen server
# This will run an http server on port 8081 identical to the one on 8080 but requiring a username and password to log in
securedServer = fusker.http.createServer 8081, 'admin', 'pass123'
io.sockets.on 'connection', (socket) ->
socket.emit 'HelloClient', 'o hay thar client'
socket.on 'TestObject', (msg) ->
console.log 'HelloServer1! Contents: ' + msg
socket.on 'TestObject', (msg) ->
console.log 'HelloServer2! Contents: ' + msg
socket.on 'TestObject', (msg) ->
console.log 'HelloServer3! Contents: ' + msg
# Uncomment the attack senders in index.html to test these
socket.on 'TestSQL', (msg) ->
console.log 'SQL Handled! Contents: ' + msg
socket.on 'TestLFI', (msg) ->
console.log 'LFI Handled! Contents: ' + msg
socket.on 'TestXSS', (msg) ->
console.log 'XSS Handled! Contents: ' + msg
| 148508 | fusker = require '../lib/main'
fusker.config.dir = __dirname
fusker.config.banLength = 1
fusker.config.verbose = true
fusker.http.detect 'csrf', 'xss', 'sqli', 'lfi', '404'
fusker.http.punish 'blacklist', 'bush'
fusker.socket.detect 'xss', 'sqli', 'lfi'
fusker.socket.punish 'blacklist'
server = fusker.http.createServer 8080
io = fusker.socket.listen server
# This will run an http server on port 8081 identical to the one on 8080 but requiring a username and password to log in
securedServer = fusker.http.createServer 8081, 'admin', '<PASSWORD>'
io.sockets.on 'connection', (socket) ->
socket.emit 'HelloClient', 'o hay thar client'
socket.on 'TestObject', (msg) ->
console.log 'HelloServer1! Contents: ' + msg
socket.on 'TestObject', (msg) ->
console.log 'HelloServer2! Contents: ' + msg
socket.on 'TestObject', (msg) ->
console.log 'HelloServer3! Contents: ' + msg
# Uncomment the attack senders in index.html to test these
socket.on 'TestSQL', (msg) ->
console.log 'SQL Handled! Contents: ' + msg
socket.on 'TestLFI', (msg) ->
console.log 'LFI Handled! Contents: ' + msg
socket.on 'TestXSS', (msg) ->
console.log 'XSS Handled! Contents: ' + msg
| true | fusker = require '../lib/main'
fusker.config.dir = __dirname
fusker.config.banLength = 1
fusker.config.verbose = true
fusker.http.detect 'csrf', 'xss', 'sqli', 'lfi', '404'
fusker.http.punish 'blacklist', 'bush'
fusker.socket.detect 'xss', 'sqli', 'lfi'
fusker.socket.punish 'blacklist'
server = fusker.http.createServer 8080
io = fusker.socket.listen server
# This will run an http server on port 8081 identical to the one on 8080 but requiring a username and password to log in
securedServer = fusker.http.createServer 8081, 'admin', 'PI:PASSWORD:<PASSWORD>END_PI'
io.sockets.on 'connection', (socket) ->
socket.emit 'HelloClient', 'o hay thar client'
socket.on 'TestObject', (msg) ->
console.log 'HelloServer1! Contents: ' + msg
socket.on 'TestObject', (msg) ->
console.log 'HelloServer2! Contents: ' + msg
socket.on 'TestObject', (msg) ->
console.log 'HelloServer3! Contents: ' + msg
# Uncomment the attack senders in index.html to test these
socket.on 'TestSQL', (msg) ->
console.log 'SQL Handled! Contents: ' + msg
socket.on 'TestLFI', (msg) ->
console.log 'LFI Handled! Contents: ' + msg
socket.on 'TestXSS', (msg) ->
console.log 'XSS Handled! Contents: ' + msg
|
[
{
"context": "#\n# Ruby/Rails colorifier\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\nColorifier.ruby = Colorifier.rails = new Class ",
"end": 66,
"score": 0.9998834133148193,
"start": 49,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | src/lang/ruby.coffee | MadRabbit/colorifier | 1 | #
# Ruby/Rails colorifier
#
# Copyright (C) 2012 Nikolay Nemshilov
#
Colorifier.ruby = Colorifier.rails = new Class Colorifier,
comments: '=begin =end,#'
keywords: 'class,module,def,do,end,if,unless,else,elsif,when,case,for,in,and,or,then,ensure,'+
'while,begin,rescue,raise,return,try,catch,until,yield,super,break,alias,not,next'
booleans: 'true,false,nil'
objects: 'public,protected,private,__FILE__,__LINE__,self,include,extend'
rails: 'render,redirect_to,respond_to,before_filter,after_filter,around_filter,'+
# active record things
'has_one,has_many,belongs_to,has_and_belongs_to_many,scope,'+
'validates_acceptance_of,validates_inclusion_of,validates_associated,'+
'validates_length_of,validates_confirmation_of,validates_numericality_of,'+
'validates_each,validates_presence_of,validates_exclusion_of,validates_size_of,'+
'validates_format_of,validates_uniqueness_of,attr_accessible,'+
'before_save,before_create,before_update,before_destroy,before_validation,'+
'after_save,after_create,after_update,after_destroy,after_validation,'+
# active-view helpers
'url_for,link_to,form_for,div_for,content_tag_for,content_tag,simple_format'
paint: (text)->
@$super text, (text)->
text = @_symbols(text)
text = @_variables(text)
text = @_rails(text)
# private
_symbols: (text)->
@_prepare(text, [
[/([^'"\d\w\.])(:[\a-z_]+)(?!['"\d\w\._])/ig, "boolean", "$1 "]
[/([^'"\d\w\.])([\a-z_]+:)(?!['"\d\w\._])/ig, "boolean", "$1 "]
])
_variables: (text)->
@_prepare(text, [
[/([^'"\d\w])(@[\a-z_]+)(?!['"\d\w_])/ig, "property", "$1 "]
])
_rails: (text)->
replacements = []
for token in @rails.split(',')
replacements.push([
new RegExp("([^'\"\\d\\w])(#{escape(token)})(?!['\"\\d\\w_])", "g"),
'regexp', "$1 "
])
@_prepare(text, replacements) | 183905 | #
# Ruby/Rails colorifier
#
# Copyright (C) 2012 <NAME>
#
Colorifier.ruby = Colorifier.rails = new Class Colorifier,
comments: '=begin =end,#'
keywords: 'class,module,def,do,end,if,unless,else,elsif,when,case,for,in,and,or,then,ensure,'+
'while,begin,rescue,raise,return,try,catch,until,yield,super,break,alias,not,next'
booleans: 'true,false,nil'
objects: 'public,protected,private,__FILE__,__LINE__,self,include,extend'
rails: 'render,redirect_to,respond_to,before_filter,after_filter,around_filter,'+
# active record things
'has_one,has_many,belongs_to,has_and_belongs_to_many,scope,'+
'validates_acceptance_of,validates_inclusion_of,validates_associated,'+
'validates_length_of,validates_confirmation_of,validates_numericality_of,'+
'validates_each,validates_presence_of,validates_exclusion_of,validates_size_of,'+
'validates_format_of,validates_uniqueness_of,attr_accessible,'+
'before_save,before_create,before_update,before_destroy,before_validation,'+
'after_save,after_create,after_update,after_destroy,after_validation,'+
# active-view helpers
'url_for,link_to,form_for,div_for,content_tag_for,content_tag,simple_format'
paint: (text)->
@$super text, (text)->
text = @_symbols(text)
text = @_variables(text)
text = @_rails(text)
# private
_symbols: (text)->
@_prepare(text, [
[/([^'"\d\w\.])(:[\a-z_]+)(?!['"\d\w\._])/ig, "boolean", "$1 "]
[/([^'"\d\w\.])([\a-z_]+:)(?!['"\d\w\._])/ig, "boolean", "$1 "]
])
_variables: (text)->
@_prepare(text, [
[/([^'"\d\w])(@[\a-z_]+)(?!['"\d\w_])/ig, "property", "$1 "]
])
_rails: (text)->
replacements = []
for token in @rails.split(',')
replacements.push([
new RegExp("([^'\"\\d\\w])(#{escape(token)})(?!['\"\\d\\w_])", "g"),
'regexp', "$1 "
])
@_prepare(text, replacements) | true | #
# Ruby/Rails colorifier
#
# Copyright (C) 2012 PI:NAME:<NAME>END_PI
#
Colorifier.ruby = Colorifier.rails = new Class Colorifier,
comments: '=begin =end,#'
keywords: 'class,module,def,do,end,if,unless,else,elsif,when,case,for,in,and,or,then,ensure,'+
'while,begin,rescue,raise,return,try,catch,until,yield,super,break,alias,not,next'
booleans: 'true,false,nil'
objects: 'public,protected,private,__FILE__,__LINE__,self,include,extend'
rails: 'render,redirect_to,respond_to,before_filter,after_filter,around_filter,'+
# active record things
'has_one,has_many,belongs_to,has_and_belongs_to_many,scope,'+
'validates_acceptance_of,validates_inclusion_of,validates_associated,'+
'validates_length_of,validates_confirmation_of,validates_numericality_of,'+
'validates_each,validates_presence_of,validates_exclusion_of,validates_size_of,'+
'validates_format_of,validates_uniqueness_of,attr_accessible,'+
'before_save,before_create,before_update,before_destroy,before_validation,'+
'after_save,after_create,after_update,after_destroy,after_validation,'+
# active-view helpers
'url_for,link_to,form_for,div_for,content_tag_for,content_tag,simple_format'
paint: (text)->
@$super text, (text)->
text = @_symbols(text)
text = @_variables(text)
text = @_rails(text)
# private
_symbols: (text)->
@_prepare(text, [
[/([^'"\d\w\.])(:[\a-z_]+)(?!['"\d\w\._])/ig, "boolean", "$1 "]
[/([^'"\d\w\.])([\a-z_]+:)(?!['"\d\w\._])/ig, "boolean", "$1 "]
])
_variables: (text)->
@_prepare(text, [
[/([^'"\d\w])(@[\a-z_]+)(?!['"\d\w_])/ig, "property", "$1 "]
])
_rails: (text)->
replacements = []
for token in @rails.split(',')
replacements.push([
new RegExp("([^'\"\\d\\w])(#{escape(token)})(?!['\"\\d\\w_])", "g"),
'regexp', "$1 "
])
@_prepare(text, replacements) |
[
{
"context": "loStats: (data)=>\n winners = {\n key: 'Wins'\n color: '#0049BD'\n values: []\n ",
"end": 772,
"score": 0.9927159547805786,
"start": 768,
"tag": "KEY",
"value": "Wins"
},
{
"context": "values: []\n }\n losers = {\n key: 'Losses'\n color: '#F3005D'\n values: []\n ",
"end": 863,
"score": 0.9916059374809265,
"start": 857,
"tag": "KEY",
"value": "Losses"
}
] | client/app/services/Statistics/Statistics.service.coffee | johnttan/spicybattle | 0 | 'use strict'
angular.module 'spicyPartyApp'
.service 'Statistics', ['$http',
class Statistics
constructor: ($http)->
@http = $http
@leaders = []
@globalStats = {}
@eloStats = []
loadLeaders: (data)=>
console.log "loaded leaderboard"
@leaders = data.data
loadStats: (data)=>
console.log "loaded stats"
@globalStats.champStats = _.map(data.data.champStats, (el, key)->
return {
name: key
stats: el
}
)
@globalStats.packStats = _.map(data.data.packStats, (el, key)->
return {
name: key
stats: el
}
)
@globalStats.gamesAnalyzed = data.data.gamesAnalyzed
loadEloStats: (data)=>
winners = {
key: 'Wins'
color: '#0049BD'
values: []
}
losers = {
key: 'Losses'
color: '#F3005D'
values: []
}
_.each(data.data, (dataPoint)->
dataPoint.x = dataPoint.delta
dataPoint.y = dataPoint.eloGain
delete dataPoint.delta
delete dataPoint.eloGain
if parseInt(dataPoint.y) > 0
winners.values.push(dataPoint)
else if parseInt(dataPoint.y) < 0
losers.values.push(dataPoint)
)
@eloStats = [winners, losers]
console.log 'loaded elostats'
getEloLeaderboard: =>
@http.get('/api/statistics/eloleaderboard')
.success(@loadLeaders)
.error((error)->
console.log(error)
)
getGlobalStats: =>
@http.get('/api/statistics/globalstats')
.success(@loadStats)
.error((error)->
console.log(error)
)
getEloStats: ($scope)=>
console.log 'getting elo report'
@scope = $scope
@http.get('/api/statistics/elostats')
.success(@loadEloStats)
.error((error)->
console.log(error)
)
] | 163392 | 'use strict'
angular.module 'spicyPartyApp'
.service 'Statistics', ['$http',
class Statistics
constructor: ($http)->
@http = $http
@leaders = []
@globalStats = {}
@eloStats = []
loadLeaders: (data)=>
console.log "loaded leaderboard"
@leaders = data.data
loadStats: (data)=>
console.log "loaded stats"
@globalStats.champStats = _.map(data.data.champStats, (el, key)->
return {
name: key
stats: el
}
)
@globalStats.packStats = _.map(data.data.packStats, (el, key)->
return {
name: key
stats: el
}
)
@globalStats.gamesAnalyzed = data.data.gamesAnalyzed
loadEloStats: (data)=>
winners = {
key: '<KEY>'
color: '#0049BD'
values: []
}
losers = {
key: '<KEY>'
color: '#F3005D'
values: []
}
_.each(data.data, (dataPoint)->
dataPoint.x = dataPoint.delta
dataPoint.y = dataPoint.eloGain
delete dataPoint.delta
delete dataPoint.eloGain
if parseInt(dataPoint.y) > 0
winners.values.push(dataPoint)
else if parseInt(dataPoint.y) < 0
losers.values.push(dataPoint)
)
@eloStats = [winners, losers]
console.log 'loaded elostats'
getEloLeaderboard: =>
@http.get('/api/statistics/eloleaderboard')
.success(@loadLeaders)
.error((error)->
console.log(error)
)
getGlobalStats: =>
@http.get('/api/statistics/globalstats')
.success(@loadStats)
.error((error)->
console.log(error)
)
getEloStats: ($scope)=>
console.log 'getting elo report'
@scope = $scope
@http.get('/api/statistics/elostats')
.success(@loadEloStats)
.error((error)->
console.log(error)
)
] | true | 'use strict'
angular.module 'spicyPartyApp'
.service 'Statistics', ['$http',
class Statistics
constructor: ($http)->
@http = $http
@leaders = []
@globalStats = {}
@eloStats = []
loadLeaders: (data)=>
console.log "loaded leaderboard"
@leaders = data.data
loadStats: (data)=>
console.log "loaded stats"
@globalStats.champStats = _.map(data.data.champStats, (el, key)->
return {
name: key
stats: el
}
)
@globalStats.packStats = _.map(data.data.packStats, (el, key)->
return {
name: key
stats: el
}
)
@globalStats.gamesAnalyzed = data.data.gamesAnalyzed
loadEloStats: (data)=>
winners = {
key: 'PI:KEY:<KEY>END_PI'
color: '#0049BD'
values: []
}
losers = {
key: 'PI:KEY:<KEY>END_PI'
color: '#F3005D'
values: []
}
_.each(data.data, (dataPoint)->
dataPoint.x = dataPoint.delta
dataPoint.y = dataPoint.eloGain
delete dataPoint.delta
delete dataPoint.eloGain
if parseInt(dataPoint.y) > 0
winners.values.push(dataPoint)
else if parseInt(dataPoint.y) < 0
losers.values.push(dataPoint)
)
@eloStats = [winners, losers]
console.log 'loaded elostats'
getEloLeaderboard: =>
@http.get('/api/statistics/eloleaderboard')
.success(@loadLeaders)
.error((error)->
console.log(error)
)
getGlobalStats: =>
@http.get('/api/statistics/globalstats')
.success(@loadStats)
.error((error)->
console.log(error)
)
getEloStats: ($scope)=>
console.log 'getting elo report'
@scope = $scope
@http.get('/api/statistics/elostats')
.success(@loadEloStats)
.error((error)->
console.log(error)
)
] |
[
{
"context": "tator = require '../src/coffee/Mutator'\n\nalice = 'alice'\nbob = 'bob'\ncharlie = 'charlie'\ndavid = 'david'\n",
"end": 206,
"score": 0.9978002309799194,
"start": 201,
"tag": "NAME",
"value": "alice"
},
{
"context": "e '../src/coffee/Mutator'\n\nalice = 'alice'\nbob = 'bob'\ncharlie = 'charlie'\ndavid = 'david'\n\ndescribe 'M",
"end": 218,
"score": 0.9985696077346802,
"start": 215,
"tag": "NAME",
"value": "bob"
},
{
"context": "/src/coffee/Mutator'\n\nalice = 'alice'\nbob = 'bob'\ncharlie = 'charlie'\ndavid = 'david'\n\ndescribe 'Mutator in",
"end": 227,
"score": 0.9906599521636963,
"start": 220,
"tag": "NAME",
"value": "charlie"
},
{
"context": "/Mutator'\n\nalice = 'alice'\nbob = 'bob'\ncharlie = 'charlie'\ndavid = 'david'\n\ndescribe 'Mutator instance', ->",
"end": 238,
"score": 0.9992881417274475,
"start": 231,
"tag": "NAME",
"value": "charlie"
},
{
"context": "\n\nalice = 'alice'\nbob = 'bob'\ncharlie = 'charlie'\ndavid = 'david'\n\ndescribe 'Mutator instance', ->\n it '",
"end": 245,
"score": 0.927745521068573,
"start": 240,
"tag": "NAME",
"value": "david"
},
{
"context": " 'alice'\nbob = 'bob'\ncharlie = 'charlie'\ndavid = 'david'\n\ndescribe 'Mutator instance', ->\n it 'should on",
"end": 254,
"score": 0.9979287981987,
"start": 249,
"tag": "NAME",
"value": "david"
},
{
"context": "on', ->\n mutator = new Mutator new Schedule [[[alice, bob, charlie, david]]]\n for i in [1..100]\n ",
"end": 727,
"score": 0.9980639219284058,
"start": 722,
"tag": "NAME",
"value": "alice"
},
{
"context": ">\n mutator = new Mutator new Schedule [[[alice, bob, charlie, david]]]\n for i in [1..100]\n mu",
"end": 732,
"score": 0.9979175925254822,
"start": 729,
"tag": "NAME",
"value": "bob"
},
{
"context": " mutator = new Mutator new Schedule [[[alice, bob, charlie, david]]]\n for i in [1..100]\n mutator.cho",
"end": 741,
"score": 0.9965565204620361,
"start": 734,
"tag": "NAME",
"value": "charlie"
},
{
"context": "= new Mutator new Schedule [[[alice, bob, charlie, david]]]\n for i in [1..100]\n mutator.chooseInst",
"end": 748,
"score": 0.9674429893493652,
"start": 743,
"tag": "NAME",
"value": "david"
},
{
"context": "for i in [1..100]\n mutator.chooseInstructor([alice], 0, 0).should.not.equal alice\n\n it 'should muta",
"end": 811,
"score": 0.9964903593063354,
"start": 806,
"tag": "NAME",
"value": "alice"
},
{
"context": " schedule', ->\n availability = new Schedule [[[alice, bob, charlie, david]]]\n mutator = new Mutator",
"end": 928,
"score": 0.9966379404067993,
"start": 923,
"tag": "NAME",
"value": "alice"
},
{
"context": "ule', ->\n availability = new Schedule [[[alice, bob, charlie, david]]]\n mutator = new Mutator avai",
"end": 933,
"score": 0.9946534633636475,
"start": 930,
"tag": "NAME",
"value": "bob"
},
{
"context": " ->\n availability = new Schedule [[[alice, bob, charlie, david]]]\n mutator = new Mutator availability\n",
"end": 942,
"score": 0.9675561189651489,
"start": 935,
"tag": "NAME",
"value": "charlie"
},
{
"context": "vailability = new Schedule [[[alice, bob, charlie, david]]]\n mutator = new Mutator availability\n ",
"end": 945,
"score": 0.937973141670227,
"start": 944,
"tag": "NAME",
"value": "d"
},
{
"context": "ilability = new Schedule [[[alice, bob, charlie, david]]]\n mutator = new Mutator availability\n for",
"end": 949,
"score": 0.785683274269104,
"start": 945,
"tag": "NAME",
"value": "avid"
}
] | test/mutatorTest.coffee | paulmand3l/schedule-optimizer | 0 | _ = require 'lodash'
chai = require 'chai'
chai.should()
Schedule = require '../src/coffee/Schedule'
Evaluator = require '../src/coffee/Evaluator'
Mutator = require '../src/coffee/Mutator'
alice = 'alice'
bob = 'bob'
charlie = 'charlie'
david = 'david'
describe 'Mutator instance', ->
it 'should only add to lessons shorter than 2', ->
mutator = new Mutator []
for i in [1..100]
mutator.getMove(['foo', 'bar']).should.not.equal '+'
it 'should only remove from lessons longer than 1', ->
mutator = new Mutator []
for i in [1..100]
mutator.getMove(['foo']).should.not.equal '-'
it 'should not suggest an instructor already in the lesson', ->
mutator = new Mutator new Schedule [[[alice, bob, charlie, david]]]
for i in [1..100]
mutator.chooseInstructor([alice], 0, 0).should.not.equal alice
it 'should mutate the input schedule', ->
availability = new Schedule [[[alice, bob, charlie, david]]]
mutator = new Mutator availability
for i in [1..100]
schedule = availability.createRandomSchedule()
mutated = mutator.mutate schedule.nights
_.isEqual(schedule, ).should.not.be.true
| 37666 | _ = require 'lodash'
chai = require 'chai'
chai.should()
Schedule = require '../src/coffee/Schedule'
Evaluator = require '../src/coffee/Evaluator'
Mutator = require '../src/coffee/Mutator'
alice = '<NAME>'
bob = '<NAME>'
<NAME> = '<NAME>'
<NAME> = '<NAME>'
describe 'Mutator instance', ->
it 'should only add to lessons shorter than 2', ->
mutator = new Mutator []
for i in [1..100]
mutator.getMove(['foo', 'bar']).should.not.equal '+'
it 'should only remove from lessons longer than 1', ->
mutator = new Mutator []
for i in [1..100]
mutator.getMove(['foo']).should.not.equal '-'
it 'should not suggest an instructor already in the lesson', ->
mutator = new Mutator new Schedule [[[<NAME>, <NAME>, <NAME>, <NAME>]]]
for i in [1..100]
mutator.chooseInstructor([<NAME>], 0, 0).should.not.equal alice
it 'should mutate the input schedule', ->
availability = new Schedule [[[<NAME>, <NAME>, <NAME>, <NAME> <NAME>]]]
mutator = new Mutator availability
for i in [1..100]
schedule = availability.createRandomSchedule()
mutated = mutator.mutate schedule.nights
_.isEqual(schedule, ).should.not.be.true
| true | _ = require 'lodash'
chai = require 'chai'
chai.should()
Schedule = require '../src/coffee/Schedule'
Evaluator = require '../src/coffee/Evaluator'
Mutator = require '../src/coffee/Mutator'
alice = 'PI:NAME:<NAME>END_PI'
bob = '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'
describe 'Mutator instance', ->
it 'should only add to lessons shorter than 2', ->
mutator = new Mutator []
for i in [1..100]
mutator.getMove(['foo', 'bar']).should.not.equal '+'
it 'should only remove from lessons longer than 1', ->
mutator = new Mutator []
for i in [1..100]
mutator.getMove(['foo']).should.not.equal '-'
it 'should not suggest an instructor already in the lesson', ->
mutator = new Mutator new Schedule [[[PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI]]]
for i in [1..100]
mutator.chooseInstructor([PI:NAME:<NAME>END_PI], 0, 0).should.not.equal alice
it 'should mutate the input schedule', ->
availability = new Schedule [[[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]]]
mutator = new Mutator availability
for i in [1..100]
schedule = availability.createRandomSchedule()
mutated = mutator.mutate schedule.nights
_.isEqual(schedule, ).should.not.be.true
|
[
{
"context": "rom the service in the past minute\n#\n# Author:\n# pstack\n\nmodule.exports = (robot) ->\n\n user = process.en",
"end": 1048,
"score": 0.9996904134750366,
"start": 1042,
"tag": "USERNAME",
"value": "pstack"
},
{
"context": "UBOT_APPDYNAMICS_USER\n password = process.env.HUBOT_APPDYNAMICS_PASSWORD\n account = process.env.HUBO",
"end": 1153,
"score": 0.5611571073532104,
"start": 1151,
"tag": "PASSWORD",
"value": "OT"
},
{
"context": "S_USER\n password = process.env.HUBOT_APPDYNAMICS_PASSWORD\n account = process.env.HUBOT_APPDYNAMICS_ACCOUNT",
"end": 1174,
"score": 0.5068891048431396,
"start": 1166,
"tag": "PASSWORD",
"value": "PASSWORD"
}
] | src/scripts/appdynamics.coffee | ryantomlinson/hubot-scripts | 0 | # Description:
# Display current app performance stats from AppDynamics
#
# Configuration:
# HUBOT_APPDYNAMICS_ACCOUNTID
# HUBOT_APPDYNAMICS_USER
# HUBOT_APPDYNAMICS_PASSWORD
# HUBOT_APPDYNAMICS_CONTROLLER
#
# Commands:
# hubot appd applications - Returns the application listing from appdynamics
# hubot appd response time [service] - Returns the last recorded response time (ms) for the service
# hubot appd calls [service] - Returns the calls made to the service in the past minute
# hubot appd errors [service] - Returns the errors returned from the service in the past minute
# hubot appd exceptions [service] - Returns the exceptions returned from the service in the past minute
# hubot appd httperrors [service] - Returns the errors returned from the service in the past minute
# hubot appd slowcalls [service] - Returns the slow calls returned from the service in the past minute
# hubot appd veryslowcalls [service] - Returns the very slow calls returned from the service in the past minute
#
# Author:
# pstack
module.exports = (robot) ->
user = process.env.HUBOT_APPDYNAMICS_USER
password = process.env.HUBOT_APPDYNAMICS_PASSWORD
account = process.env.HUBOT_APPDYNAMICS_ACCOUNTID
auth = 'Basic ' + new Buffer("#{user}@#{account}:#{password}").toString('base64');
url = "#{process.env.HUBOT_APPDYNAMICS_CONTROLLER}/rest/applications?output=JSON"
applications = (msg) ->
msg.http(url)
.headers
'Authorization': auth
.get() (err, res, body) ->
msg.send(body)
robot.respond /appd applications/i, (msg) ->
if msg.message.user.id is robot.name
return
applications msg, (text) ->
msg.send(text)
robot.respond /appd response time (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd calls (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd errors (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd exceptions (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd httperrors (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd slowcalls (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd veryslowcalls (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
| 38850 | # Description:
# Display current app performance stats from AppDynamics
#
# Configuration:
# HUBOT_APPDYNAMICS_ACCOUNTID
# HUBOT_APPDYNAMICS_USER
# HUBOT_APPDYNAMICS_PASSWORD
# HUBOT_APPDYNAMICS_CONTROLLER
#
# Commands:
# hubot appd applications - Returns the application listing from appdynamics
# hubot appd response time [service] - Returns the last recorded response time (ms) for the service
# hubot appd calls [service] - Returns the calls made to the service in the past minute
# hubot appd errors [service] - Returns the errors returned from the service in the past minute
# hubot appd exceptions [service] - Returns the exceptions returned from the service in the past minute
# hubot appd httperrors [service] - Returns the errors returned from the service in the past minute
# hubot appd slowcalls [service] - Returns the slow calls returned from the service in the past minute
# hubot appd veryslowcalls [service] - Returns the very slow calls returned from the service in the past minute
#
# Author:
# pstack
module.exports = (robot) ->
user = process.env.HUBOT_APPDYNAMICS_USER
password = process.env.HUB<PASSWORD>_APPDYNAMICS_<PASSWORD>
account = process.env.HUBOT_APPDYNAMICS_ACCOUNTID
auth = 'Basic ' + new Buffer("#{user}@#{account}:#{password}").toString('base64');
url = "#{process.env.HUBOT_APPDYNAMICS_CONTROLLER}/rest/applications?output=JSON"
applications = (msg) ->
msg.http(url)
.headers
'Authorization': auth
.get() (err, res, body) ->
msg.send(body)
robot.respond /appd applications/i, (msg) ->
if msg.message.user.id is robot.name
return
applications msg, (text) ->
msg.send(text)
robot.respond /appd response time (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd calls (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd errors (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd exceptions (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd httperrors (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd slowcalls (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd veryslowcalls (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
| true | # Description:
# Display current app performance stats from AppDynamics
#
# Configuration:
# HUBOT_APPDYNAMICS_ACCOUNTID
# HUBOT_APPDYNAMICS_USER
# HUBOT_APPDYNAMICS_PASSWORD
# HUBOT_APPDYNAMICS_CONTROLLER
#
# Commands:
# hubot appd applications - Returns the application listing from appdynamics
# hubot appd response time [service] - Returns the last recorded response time (ms) for the service
# hubot appd calls [service] - Returns the calls made to the service in the past minute
# hubot appd errors [service] - Returns the errors returned from the service in the past minute
# hubot appd exceptions [service] - Returns the exceptions returned from the service in the past minute
# hubot appd httperrors [service] - Returns the errors returned from the service in the past minute
# hubot appd slowcalls [service] - Returns the slow calls returned from the service in the past minute
# hubot appd veryslowcalls [service] - Returns the very slow calls returned from the service in the past minute
#
# Author:
# pstack
module.exports = (robot) ->
user = process.env.HUBOT_APPDYNAMICS_USER
password = process.env.HUBPI:PASSWORD:<PASSWORD>END_PI_APPDYNAMICS_PI:PASSWORD:<PASSWORD>END_PI
account = process.env.HUBOT_APPDYNAMICS_ACCOUNTID
auth = 'Basic ' + new Buffer("#{user}@#{account}:#{password}").toString('base64');
url = "#{process.env.HUBOT_APPDYNAMICS_CONTROLLER}/rest/applications?output=JSON"
applications = (msg) ->
msg.http(url)
.headers
'Authorization': auth
.get() (err, res, body) ->
msg.send(body)
robot.respond /appd applications/i, (msg) ->
if msg.message.user.id is robot.name
return
applications msg, (text) ->
msg.send(text)
robot.respond /appd response time (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd calls (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd errors (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd exceptions (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd httperrors (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd slowcalls (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
robot.respond /appd veryslowcalls (.*)/i, (msg) ->
if msg.message.user.id is robot.name
return
|
[
{
"context": "The standard prompt dialogs\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\nclass Dialog.Prompt extends Dialog\n\n construct",
"end": 72,
"score": 0.9998838305473328,
"start": 55,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | ui/dialog/src/prompt.coffee | lovely-io/lovely.io-stl | 2 | #
# The standard prompt dialogs
#
# Copyright (C) 2012 Nikolay Nemshilov
#
class Dialog.Prompt extends Dialog
constructor: (options)->
options or= {}
options.title or= 'Prompt'
options.icon or= 'edit'
input_type = options.type || 'text'
delete(options.type)
super(options)
@addClass('lui-dialog-prompt')
@input = new Input(type: input_type).insertTo(@)
unless input_type is 'textarea'
@input.on 'enter', => @emit('ok')
@on 'ok', 'hide'
@on 'show', => @input.focus()
#
# Automatically adding the `value` parameter
# to the `ok` events, so you could get the entered
# value immediatelly
#
emit: (name, options)->
if name is 'ok'
options or= {}
options.value = @input.value()
super name, options | 210606 | #
# The standard prompt dialogs
#
# Copyright (C) 2012 <NAME>
#
class Dialog.Prompt extends Dialog
constructor: (options)->
options or= {}
options.title or= 'Prompt'
options.icon or= 'edit'
input_type = options.type || 'text'
delete(options.type)
super(options)
@addClass('lui-dialog-prompt')
@input = new Input(type: input_type).insertTo(@)
unless input_type is 'textarea'
@input.on 'enter', => @emit('ok')
@on 'ok', 'hide'
@on 'show', => @input.focus()
#
# Automatically adding the `value` parameter
# to the `ok` events, so you could get the entered
# value immediatelly
#
emit: (name, options)->
if name is 'ok'
options or= {}
options.value = @input.value()
super name, options | true | #
# The standard prompt dialogs
#
# Copyright (C) 2012 PI:NAME:<NAME>END_PI
#
class Dialog.Prompt extends Dialog
constructor: (options)->
options or= {}
options.title or= 'Prompt'
options.icon or= 'edit'
input_type = options.type || 'text'
delete(options.type)
super(options)
@addClass('lui-dialog-prompt')
@input = new Input(type: input_type).insertTo(@)
unless input_type is 'textarea'
@input.on 'enter', => @emit('ok')
@on 'ok', 'hide'
@on 'show', => @input.focus()
#
# Automatically adding the `value` parameter
# to the `ok` events, so you could get the entered
# value immediatelly
#
emit: (name, options)->
if name is 'ok'
options or= {}
options.value = @input.value()
super name, options |
[
{
"context": "text\" bsSize=\"large\" rel=\"input\" placeholder=\"User name\" value={me.state.account.name} onChange={me.chang",
"end": 1749,
"score": 0.7772437334060669,
"start": 1745,
"tag": "NAME",
"value": "name"
},
{
"context": "password\" bsSize=\"large\" rel=\"input\" placeholder=\"Password\" value={me.state.account.password} onChange={me.c",
"end": 2042,
"score": 0.994137167930603,
"start": 2034,
"tag": "PASSWORD",
"value": "Password"
}
] | assets/views/account.cjsx | DevReljp/Yokoso | 0 | 'use strict'
React = require 'react'
Addons = require 'react/addons'
Router = require 'react-router'
Bootstrap = require 'react-bootstrap'
Link = Router.Link
Menu = require './menu'
Col = Bootstrap.Col
Input = Bootstrap.Input
ButtonInput = Bootstrap.ButtonInput
Alert = Bootstrap.Alert
TransitionHook = Router.TransitionHook
Navigation = Router.Navigation
module.exports = React.createClass
displayName: 'account'
mixins: [Navigation, TransitionHook]
getInitialState: ->
account:
name: ""
email: ""
password: ""
alert:
show: false
message: ""
type: ""
submit_form: (e) ->
e.preventDefault()
data = this.state.account
me = this
jQuery.ajax
data: data
url: '/accounts'
type: 'post'
dataType: 'json'
.then (data) ->
me.setState React.addons.update me.state, alert:
show: $set: true
message: $set: "Registration successful"
type: $set: "success"
me.transitionTo '/sign_in'
console.log data
, (error) ->
console.log error
handleAlertDismiss: (e) ->
@setState React.addons.update @state, alert:
show: $set: false
changeAccountName: (e) ->
@setState React.addons.update @state, account:
name: $set: e.target.value
changeEmail: (e) ->
@setState React.addons.update @state, account:
email: $set: e.target.value
changePassword: (e) ->
@setState React.addons.update @state, account:
password: $set: e.target.value
render: ->
me = this
<div id='App'>
<Menu />
<Col md={6} xsOffset={3}>
<h1>Sign up</h1>
<form onSubmit={me.submit_form}>
<Input type="text" bsSize="large" rel="input" placeholder="User name" value={me.state.account.name} onChange={me.changeAccountName} />
<Input type="email" bsSize="large" rel="input" placeholder="Email address" value={me.state.account.email} onChange={me.changeEmail} />
<Input type="password" bsSize="large" rel="input" placeholder="Password" value={me.state.account.password} onChange={me.changePassword} />
{
if me.state.alert.show
<Alert bsStyle={me.state.alert.type} onDismiss={me.handleAlertDismiss} dismissAfter={2000}>
<p>{me.state.alert.message}</p>
</Alert>
}
<ButtonInput onClick={me.submit_form} bsStyle="primary" bsSize="large">Register</ButtonInput> or <Link to="/sign_in">Sign in</Link>.
</form>
</Col>
</div>
| 189659 | 'use strict'
React = require 'react'
Addons = require 'react/addons'
Router = require 'react-router'
Bootstrap = require 'react-bootstrap'
Link = Router.Link
Menu = require './menu'
Col = Bootstrap.Col
Input = Bootstrap.Input
ButtonInput = Bootstrap.ButtonInput
Alert = Bootstrap.Alert
TransitionHook = Router.TransitionHook
Navigation = Router.Navigation
module.exports = React.createClass
displayName: 'account'
mixins: [Navigation, TransitionHook]
getInitialState: ->
account:
name: ""
email: ""
password: ""
alert:
show: false
message: ""
type: ""
submit_form: (e) ->
e.preventDefault()
data = this.state.account
me = this
jQuery.ajax
data: data
url: '/accounts'
type: 'post'
dataType: 'json'
.then (data) ->
me.setState React.addons.update me.state, alert:
show: $set: true
message: $set: "Registration successful"
type: $set: "success"
me.transitionTo '/sign_in'
console.log data
, (error) ->
console.log error
handleAlertDismiss: (e) ->
@setState React.addons.update @state, alert:
show: $set: false
changeAccountName: (e) ->
@setState React.addons.update @state, account:
name: $set: e.target.value
changeEmail: (e) ->
@setState React.addons.update @state, account:
email: $set: e.target.value
changePassword: (e) ->
@setState React.addons.update @state, account:
password: $set: e.target.value
render: ->
me = this
<div id='App'>
<Menu />
<Col md={6} xsOffset={3}>
<h1>Sign up</h1>
<form onSubmit={me.submit_form}>
<Input type="text" bsSize="large" rel="input" placeholder="User <NAME>" value={me.state.account.name} onChange={me.changeAccountName} />
<Input type="email" bsSize="large" rel="input" placeholder="Email address" value={me.state.account.email} onChange={me.changeEmail} />
<Input type="password" bsSize="large" rel="input" placeholder="<PASSWORD>" value={me.state.account.password} onChange={me.changePassword} />
{
if me.state.alert.show
<Alert bsStyle={me.state.alert.type} onDismiss={me.handleAlertDismiss} dismissAfter={2000}>
<p>{me.state.alert.message}</p>
</Alert>
}
<ButtonInput onClick={me.submit_form} bsStyle="primary" bsSize="large">Register</ButtonInput> or <Link to="/sign_in">Sign in</Link>.
</form>
</Col>
</div>
| true | 'use strict'
React = require 'react'
Addons = require 'react/addons'
Router = require 'react-router'
Bootstrap = require 'react-bootstrap'
Link = Router.Link
Menu = require './menu'
Col = Bootstrap.Col
Input = Bootstrap.Input
ButtonInput = Bootstrap.ButtonInput
Alert = Bootstrap.Alert
TransitionHook = Router.TransitionHook
Navigation = Router.Navigation
module.exports = React.createClass
displayName: 'account'
mixins: [Navigation, TransitionHook]
getInitialState: ->
account:
name: ""
email: ""
password: ""
alert:
show: false
message: ""
type: ""
submit_form: (e) ->
e.preventDefault()
data = this.state.account
me = this
jQuery.ajax
data: data
url: '/accounts'
type: 'post'
dataType: 'json'
.then (data) ->
me.setState React.addons.update me.state, alert:
show: $set: true
message: $set: "Registration successful"
type: $set: "success"
me.transitionTo '/sign_in'
console.log data
, (error) ->
console.log error
handleAlertDismiss: (e) ->
@setState React.addons.update @state, alert:
show: $set: false
changeAccountName: (e) ->
@setState React.addons.update @state, account:
name: $set: e.target.value
changeEmail: (e) ->
@setState React.addons.update @state, account:
email: $set: e.target.value
changePassword: (e) ->
@setState React.addons.update @state, account:
password: $set: e.target.value
render: ->
me = this
<div id='App'>
<Menu />
<Col md={6} xsOffset={3}>
<h1>Sign up</h1>
<form onSubmit={me.submit_form}>
<Input type="text" bsSize="large" rel="input" placeholder="User PI:NAME:<NAME>END_PI" value={me.state.account.name} onChange={me.changeAccountName} />
<Input type="email" bsSize="large" rel="input" placeholder="Email address" value={me.state.account.email} onChange={me.changeEmail} />
<Input type="password" bsSize="large" rel="input" placeholder="PI:PASSWORD:<PASSWORD>END_PI" value={me.state.account.password} onChange={me.changePassword} />
{
if me.state.alert.show
<Alert bsStyle={me.state.alert.type} onDismiss={me.handleAlertDismiss} dismissAfter={2000}>
<p>{me.state.alert.message}</p>
</Alert>
}
<ButtonInput onClick={me.submit_form} bsStyle="primary" bsSize="large">Register</ButtonInput> or <Link to="/sign_in">Sign in</Link>.
</form>
</Col>
</div>
|
[
{
"context": "# parsing PHP code\n#\n# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# L",
"end": 56,
"score": 0.9998645782470703,
"start": 42,
"tag": "NAME",
"value": "JeongHoon Byun"
},
{
"context": "P code\n#\n# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# Licensed under ",
"end": 70,
"score": 0.9535346031188965,
"start": 62,
"tag": "USERNAME",
"value": "Outsider"
},
{
"context": " \"\"\"\n }\n {\n key: \"capssnake\", display: \"Class Name in CAPS_SNAKE_CASE\",\n ",
"end": 13752,
"score": 0.7040369510650635,
"start": 13746,
"tag": "USERNAME",
"value": "ssnake"
},
{
"context": " \"\"\"\n }\n {\n key: \"snakepascal\", display: \"Class Name in Snake_Pascal_Case\",\n ",
"end": 13963,
"score": 0.5378371477127075,
"start": 13960,
"tag": "USERNAME",
"value": "cal"
},
{
"context": " \"\"\"\n }\n {\n key: \"uppersnake\", display: \"Class Snake_first_letter_uppercase\",\n",
"end": 14375,
"score": 0.8816890120506287,
"start": 14365,
"tag": "USERNAME",
"value": "uppersnake"
}
] | src/parser/php-parser.coffee | uppalapatisujitha/CodingConventionofCommitHistory | 421 | # parsing PHP code
#
# Copyright (c) 2013 JeongHoon Byun aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
helpers = require '../helpers'
_ = require 'underscore'
phpParser = module.exports =
lang: 'php'
parse: (line, convention, commitUrl) ->
convention = this.indent line, convention, commitUrl
convention = this.classBrace line, convention, commitUrl
convention = this.controlBrace line, convention, commitUrl
convention = this.methodBrace line, convention, commitUrl
convention = this.spaceAroundControl line, convention, commitUrl
convention = this.spaceInsideControl line, convention, commitUrl
convention = this.spaceAroundMethod line, convention, commitUrl
convention = this.spaceInsideMethod line, convention, commitUrl
convention = this.className line, convention, commitUrl
convention = this.constName line, convention, commitUrl
convention = this.functionName line, convention, commitUrl
convention = this.methodDeclare line, convention, commitUrl
convention = this.linelength line, convention, commitUrl
indent: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.indent =
title: "Space vs. Tab"
column: [
{
key: "tab", display: "Tab",
code: """
class Foo {
function bar($baz) {
// uses one tab for indentation
}
}
"""
}
{
key: "space", display: "Space",
code: """
class Foo {
function bar($baz) {
// uses spaces for indentation
}
}
"""
}
]
tab: 0
space: 0
commits: []
) unless convention.indent
tab = /^\t+.*/
space = /^\s+.*/
convention.indent.tab = convention.indent.tab + 1 if tab.test line
convention.indent.space = convention.indent.space + 1 if space.test line
convention.indent.commits.push commitUrl if tab.test(line) or space.test(line)
convention.indent.commits = _.uniq convention.indent.commits
convention
classBrace: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.classBrace =
title: "Brace Placement (Class)"
column: [
{
key: "newline", display: "Class opening/closing braces on seperate line (Allman)",
code: """
class Foo
{
// ...
}
"""
}
{
key: "sameline", display: "Class structure opening/closing braces on same line as declaration (OTBS)",
code: """
class Foo {
// ...
}
"""
}
]
newline: 0
sameline: 0
commits: []
) unless convention.classBrace
newline = (line) ->
temp = line.replace /\/\/.*/g, ''
///^(\s|\\t)*class\s+\w+\s*(extends\s*\w+)?\s*$///.test temp
sameline = (line) ->
temp = line.replace /\/\/.*/g, ''
///^(\s|\\t)*class\s+\w+\s*(extends\s*\w+)?\s+{///.test temp
convention.classBrace.newline = convention.classBrace.newline + 1 if newline line
convention.classBrace.sameline = convention.classBrace.sameline + 1 if sameline line
convention.classBrace.commits.push commitUrl if newline(line) or sameline(line)
convention.classBrace.commits = _.uniq convention.classBrace.commits
convention
controlBrace: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.controlBrace =
title: "Brace Placement (Control Structures)"
column: [
{
key: "sameline", display: "Control structure opening/closing braces on same line as declaration",
code: """
if($baz) {
// ..
} elseif($bar) {
// ..
} else {
// ..
}
while ($i <= 10) {
// ..
}
switch($beer) {
// ..
}
"""
}
{
key: "newline", display: "Control structure opening/closing braces on seperate line from declaration",
code: """
if($baz)
{
// ..
}
elseif($bar)
{
// ..
}
else
{
// ..
}
while ($i <= 10)
{
// ..
}
switch($beer)
{
// ..
}
"""
}
]
sameline: 0
newline: 0
commits: []
) unless convention.controlBrace
sameline = (line) ->
temp = line.replace /\/\/.*/g, ''
///((if|while|switch).*{)|(}\s*(else|elseif).*{)///.test temp
newline = (line) ->
temp = line.replace /\/\/.*/g, ''
///^\s*(((if|while|switch).*)|(\s*(else|elseif).*))[^{|:]$///.test temp
convention.controlBrace.sameline = convention.controlBrace.sameline + 1 if sameline line
convention.controlBrace.newline = convention.controlBrace.newline + 1 if newline line
convention.controlBrace.commits.push commitUrl if newline(line) or sameline(line)
convention.controlBrace.commits = _.uniq convention.controlBrace.commits
convention
methodBrace: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.methodBrace =
title: "Brace Placement (Methods)"
column: [
{
key: "sameline", display: "Method structure opening braces on same line as declaration (OTBS)",
code: """
function bar($baz) {
// ...
}
"""
}
{
key: "newline", display: "Method opening/closing braces on seperate line (Allman)",
code: """
function bar($baz)
{
// ...
}
"""
}
]
sameline: 0
newline: 0
commits: []
) unless convention.methodBrace
sameline = (line) ->
temp = line.replace /\/\/.*/g, ''
///^[\s|\t]*function\s+\w+\(.*?\)\s*{///.test temp
newline = (line) ->
temp = line.replace /\/\/.*/g, ''
///^[\s|\t]*function\s+\w+\(.*?\)\s*$///.test temp
convention.methodBrace.sameline = convention.methodBrace.sameline + 1 if sameline line
convention.methodBrace.newline = convention.methodBrace.newline + 1 if newline line
convention.methodBrace.commits.push commitUrl if newline(line) or sameline(line)
convention.methodBrace.commits = _.uniq convention.methodBrace.commits
convention
spaceAroundControl: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.spaceAroundControl =
title: "Space Around Control Structure Evaluation Block"
column: [
{
key: "space", display: "Space around control structure Evaluation block",
code: """
if ($baz) {
// ...
} elseif ($bar) {
// ...
} else {
// ...
}
while ($i <= 10) {
// ...
}
switch ($beer) {
// ...
}
"""
}
{
key: "nospace", display: "No space around control structure Evaluation block",
code: """
if($baz){
// ...
}elseif($bar){
// ...
}else{
// ...
}
while($i <= 10){
// ...
}
switch($beer){
// ...
}
"""
}
]
space: 0
nospace: 0
commits: []
) unless convention.spaceAroundControl
space = /((if|elseif|while|for)\s+\(.*?\)\s+({|:))|(do\s+{)/
nospace = /((if|elseif|while|for)\(.*?\)({|:))|(do{)/
convention.spaceAroundControl.space = convention.spaceAroundControl.space + 1 if space.test line
convention.spaceAroundControl.nospace = convention.spaceAroundControl.nospace + 1 if nospace.test line
convention.spaceAroundControl.commits.push commitUrl if nospace.test(line) or space.test(line)
convention.spaceAroundControl.commits = _.uniq convention.spaceAroundControl.commits
convention
spaceInsideControl: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.spaceInsideControl =
title: "Space Inside Control Structure Evaluation Block"
column: [
{
key: "space", display: "Space inside control structure Evaluation block",
code: """
if ( $baz ) {
// ...
} elseif ( $bar ) {
// ...
}
while ( $i <= 10 ) {
// ...
}
switch ( $beer ) {
// ...
}
"""
}
{
key: "nospace", display: "No space inside control structure Evaluation block",
code: """
if ($baz) {
// ...
} elseif ($bar) {
// ...
}
while ($i <= 10) {
// ...
}
switch ($beer) {
// ...
}
"""
}
]
space: 0
nospace: 0
commits: []
) unless convention.spaceInsideControl
space = /(if|elseif|while|for)\s*\(\s+.+?\s+\)/
nospace = /(if|elseif|while|for)\s*\(\S+.*?\S\)/
convention.spaceInsideControl.space = convention.spaceInsideControl.space + 1 if space.test line
convention.spaceInsideControl.nospace = convention.spaceInsideControl.nospace + 1 if nospace.test line
convention.spaceInsideControl.commits.push commitUrl if nospace.test(line) or space.test(line)
convention.spaceInsideControl.commits = _.uniq convention.spaceInsideControl.commits
convention
spaceAroundMethod: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.spaceAroundMethod =
title: "Space Around Method Declaration Param Block"
column: [
{
key: "space", display: "Space around parameter declaration block",
code: """
function bar ($baz) {
// ...
}
"""
}
{
key: "nospace", display: "No space around parameter declaration block",
code: """
function bar($baz){
// ...
}
"""
}
]
space: 0
nospace: 0
commits: []
) unless convention.spaceAroundMethod
space = /^[\s\t]*function\s+\w+\s+\(.*?\)\s+{/
nospace = /^[\s\t]*function\s+\w+\(.*?\){/
convention.spaceAroundMethod.space = convention.spaceAroundMethod.space + 1 if space.test line
convention.spaceAroundMethod.nospace = convention.spaceAroundMethod.nospace + 1 if nospace.test line
convention.spaceAroundMethod.commits.push commitUrl if nospace.test(line) or space.test(line)
convention.spaceAroundMethod.commits = _.uniq convention.spaceAroundMethod.commits
convention
spaceInsideMethod: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.spaceInsideMethod =
title: "Space Inside Method Declaration Param Block"
column: [
{
key: "space", display: "Space inside parameter declaration block",
code: """
function bar( $baz ){
// ...
}
"""
}
{
key: "nospace", display: "No space inside parameter declaration block",
code: """
function bar($baz){
// ...
}
"""
}
]
space: 0
nospace: 0
commits: []
) unless convention.spaceInsideMethod
space = /^[\s|\t]*function\s+\w+\s*\(\s+.+?\s+\)/
nospace = /^[\s|\t]*function\s+\w+\s*\(\S+.*?\S\)/
convention.spaceInsideMethod.space = convention.spaceInsideMethod.space + 1 if space.test line
convention.spaceInsideMethod.nospace = convention.spaceInsideMethod.nospace + 1 if nospace.test line
convention.spaceInsideMethod.commits.push commitUrl if nospace.test(line) or space.test(line)
convention.spaceInsideMethod.commits = _.uniq convention.spaceInsideMethod.commits
convention
className: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.className =
title: "Class Names"
column: [
{
key: "camel", display: "Class Name in camelCase",
code: """
class fooBarBaz {
// ...
}
"""
}
{
key: "pascal", display: "Class Name in PascalCase",
code: """
class FooBarBaz {
// ...
}
"""
}
{
key: "capssnake", display: "Class Name in CAPS_SNAKE_CASE",
code: """
class FOO_BAR_BAZ {
// ...
}
"""
}
{
key: "snakepascal", display: "Class Name in Snake_Pascal_Case",
code: """
class Foo_Bar_Baz {
// ...
}
"""
}
{
key: "snake", display: "Class Name in snake_case",
code: """
class foo_bar_baz {
// ...
}
"""
}
{
key: "uppersnake", display: "Class Snake_first_letter_uppercase",
code: """
class Foo_bar_baz {
// ...
}
"""
}
]
camel: 0
pascal: 0
capssnake: 0
snakepascal: 0
snake: 0
uppersnake: 0
commits: []
) unless convention.className
camel = /^[\s|\t]*class\s+[a-z][a-z0-9]*([A-Z][a-z0-9]+)+(\b|\s|{)/
pascal = /^[\s|\t]*class\s+([A-Z][a-z0-9]+){2,}(\b|\s|{)/
capssnake = /^[\s|\t]*class\s+([A-Z0-9]+_)+[A-Z0-9]+(\b|\s|{)/
snakepascal = /^[\s|\t]*class\s+(([A-Z][a-z0-9]+)_)+[A-Z][a-z0-9]+(\b|\s|{)/
snake = /^[\s|\t]*class\s+(([a-z][a-z0-9]+)_)+[a-z][a-z0-9]+(\b|\s|{)/
uppersnake = /^[\s|\t]*class\s+(([A-Z][a-z0-9]+)_)([a-z][a-z0-9]+_)+[a-z][a-z0-9]+(\b|\s|{)/
convention.className.camel = convention.className.camel + 1 if camel.test line
convention.className.pascal = convention.className.pascal + 1 if pascal.test line
convention.className.capssnake = convention.className.capssnake + 1 if capssnake.test line
convention.className.snakepascal = convention.className.snakepascal + 1 if snakepascal.test line
convention.className.snake = convention.className.snake + 1 if snake.test line
convention.className.uppersnake = convention.className.uppersnake + 1 if uppersnake.test line
convention.className.commits.push commitUrl if camel.test(line) or pascal.test(line) or
capssnake.test(line) or snakepascal.test(line) or
snake.test(line) or uppersnake.test(line)
convention.className.commits = _.uniq convention.className.commits
convention
constName: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.constName =
title: "Constant Names"
column: [
{
key: "camel", display: "Constant Name in camelCase",
code: """
const barBaz = 0;
define('barBaz', 0);
"""
}
{
key: "pascal", display: "Constant Name in PascalCase",
code: """
const BarBaz = 0;
define('BarBaz', 0);
"""
}
{
key: "capssnake", display: "Constant Name in CAPS_SNAKE_CASE",
code: """
const BAR_BAZ = 0;
define('BAR_BAZ', 0);
"""
}
{
key: "snakepascal", display: "Constant Name in Snake_Pascal_Case",
code: """
const Bar_Baz = 0;
define('Bar_Baz', 0);
"""
}
{
key: "snake", display: "Constant Name in snake_case",
code: """
const bar_baz = 0;
define('bar_baz', 0);
"""
}
]
camel: 0
pascal: 0
capssnake: 0
snakepascal: 0
snake: 0
commits: []
) unless convention.constName
camel = /(^[\s|\t]*const\s+[a-z][a-z0-9]*([A-Z][a-z0-9]+)+\s*=)|([\s|\t]*define\(s*['"][a-z][a-z0-9]*([A-Z][a-z0-9]+)+['"]s*,)/
pascal = /(^[\s|\t]*const\s+([A-Z][a-z0-9]+){2,}\s*=)|([\s|\t]*define\(s*['"]([A-Z][a-z0-9]+){2,}['"]s*,)/
capssnake = /(^[\s|\t]*const\s+([A-Z0-9]+_)+[A-Z0-9]+\s*=)|([\s|\t]*define\(s*['"]([A-Z0-9]+_)+[A-Z0-9]+['"]s*,)/
snakepascal = /(^[\s|\t]*const\s+(([A-Z][a-z0-9]+)_)+[A-Z][a-z0-9]+\s*=)|([\s|\t]*define\(s*['"](([A-Z][a-z0-9]+)_)+[A-Z][a-z0-9]+['"]s*,)/
snake = /(^[\s|\t]*const\s+(([a-z][a-z0-9]+)_)+[a-z][a-z0-9]+\s*=)|([\s|\t]*define\(s*['"](([a-z][a-z0-9]+)_)+[a-z][a-z0-9]+['"]s*,)/
convention.constName.camel = convention.constName.camel + 1 if camel.test line
convention.constName.pascal = convention.constName.pascal + 1 if pascal.test line
convention.constName.capssnake = convention.constName.capssnake + 1 if capssnake.test line
convention.constName.snakepascal = convention.constName.snakepascal + 1 if snakepascal.test line
convention.constName.snake = convention.constName.snake + 1 if snake.test line
convention.constName.commits.push commitUrl if camel.test(line) or pascal.test(line) or
capssnake.test(line) or snakepascal.test(line) or
snake.test(line)
convention.constName.commits = _.uniq convention.constName.commits
convention
functionName: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.functionName =
title: "Function Names"
column: [
{
key: "camel", display: "Function Name in camelCase",
code: """
function barBaz(){
// ...
}
"""
}
{
key: "pascal", display: "Function Name in PascalCase",
code: """
function BarBaz(){
// ...
}
"""
}
{
key: "capssnake", display: "Function Name in CAPS_SNAKE_CASE",
code: """
function BAR_BAZ(){
// ...
}
"""
}
{
key: "snakepascal", display: "Function Name in Snake_Pascal_Case",
code: """
function Bar_Baz(){
// ...
}
"""
}
{
key: "snake", display: "Function Name in snake_case",
code: """
function bar_baz(){
// ...
}
"""
}
]
camel: 0
pascal: 0
capssnake: 0
snakepascal: 0
snake: 0
commits: []
) unless convention.functionName
camel = /function\s+[a-z][a-z0-9]*([A-Z][a-z0-9]+)+\s*\(/
pascal = /function\s+([A-Z][a-z0-9]+){2,}\s*\(/
capssnake = /function\s+([A-Z0-9]+_)+[A-Z0-9]+\s*\(/
snakepascal = /function\s+(([A-Z][a-z0-9]+)_)+[A-Z][a-z0-9]+\s*\(/
snake = /function\s+(([a-z][a-z0-9]+)_)+[a-z][a-z0-9]+\s*\(/
convention.functionName.camel = convention.functionName.camel + 1 if camel.test line
convention.functionName.pascal = convention.functionName.pascal + 1 if pascal.test line
convention.functionName.capssnake = convention.functionName.capssnake + 1 if capssnake.test line
convention.functionName.snakepascal = convention.functionName.snakepascal + 1 if snakepascal.test line
convention.functionName.snake = convention.functionName.snake + 1 if snake.test line
convention.functionName.commits.push commitUrl if camel.test(line) or pascal.test(line) or
capssnake.test(line) or snakepascal.test(line) or
snake.test(line)
convention.functionName.commits = _.uniq convention.functionName.commits
convention
methodDeclare: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.methodDeclare =
title: "Method Declare Order"
column: [
{
key: "staticlate", display: "static declared after visibility",
code: """
class Foo
{
public static function bar($baz)
{
// ...
}
}
"""
}
{
key: "staticfirst", display: "static declared before visibility",
code: """
class Foo
{
static public function bar($baz)
{
// ...
}
}
"""
}
{
key: "abstractlate", display: "abstract (or final) declared after visibility",
code: """
class Foo
{
public abstract function bar($baz);
// ...
}
"""
}
{
key: "abstractfirst", display: "abstract (or final) declared before visibility",
code: """
class Foo
{
abstract public function bar($baz);
// ...
}
"""
}
]
staticlate: 0
staticfirst: 0
abstractlate: 0
abstractfirst: 0
commits: []
) unless convention.methodDeclare
staticlate = /(public|protected|private)\s+static\s+\$*\w*/
staticfirst = /static\s+(public|protected|private)\s+\$*\w*/
abstractlate = /(public|protected|private)\s+(abstract|final)\s+\$*\w*/
abstractfirst = /(abstract|final)\s+(public|protected|private)\s+\$*\w*/
convention.methodDeclare.staticlate = convention.methodDeclare.staticlate + 1 if staticlate.test line
convention.methodDeclare.staticfirst = convention.methodDeclare.staticfirst + 1 if staticfirst.test line
convention.methodDeclare.abstractlate = convention.methodDeclare.abstractlate + 1 if abstractlate.test line
convention.methodDeclare.abstractfirst = convention.methodDeclare.abstractfirst + 1 if abstractfirst.test line
convention.methodDeclare.commits.push commitUrl if staticlate.test(line) or staticfirst.test(line) or
abstractlate.test(line) or abstractfirst.test(line)
convention.methodDeclare.commits = _.uniq convention.methodDeclare.commits
convention
linelength: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.linelength =
title: "Line length is over 80 characters?"
column: [
{
key: "char80", display: "Line length is within 80 characters.",
code: "/* width is within 80 characters */"
}
{
key: "char120", display: "Line length is within 120 characters",
code: "/* width is within 120 characters */"
}
{
key: "char150", display: "Line length is within 150 characters",
code: "/* width is within 150 characters */"
}
]
char80: 0
char120: 0
char150: 0
commits: []
) unless convention.linelength
width = line.length
tabcount = line.split('\t').length - 1
# assume tab size is 4 space
width += tabcount * 3
if width < 80
convention.linelength.char80 = convention.linelength.char80 + 1
else if width < 120
convention.linelength.char120 = convention.linelength.char120 + 1
else
convention.linelength.char150 = convention.linelength.char150 + 1
convention.linelength.commits.push commitUrl
convention.linelength.commits = _.uniq convention.linelength.commits
convention
| 84884 | # parsing PHP code
#
# Copyright (c) 2013 <NAME> aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
helpers = require '../helpers'
_ = require 'underscore'
phpParser = module.exports =
lang: 'php'
parse: (line, convention, commitUrl) ->
convention = this.indent line, convention, commitUrl
convention = this.classBrace line, convention, commitUrl
convention = this.controlBrace line, convention, commitUrl
convention = this.methodBrace line, convention, commitUrl
convention = this.spaceAroundControl line, convention, commitUrl
convention = this.spaceInsideControl line, convention, commitUrl
convention = this.spaceAroundMethod line, convention, commitUrl
convention = this.spaceInsideMethod line, convention, commitUrl
convention = this.className line, convention, commitUrl
convention = this.constName line, convention, commitUrl
convention = this.functionName line, convention, commitUrl
convention = this.methodDeclare line, convention, commitUrl
convention = this.linelength line, convention, commitUrl
indent: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.indent =
title: "Space vs. Tab"
column: [
{
key: "tab", display: "Tab",
code: """
class Foo {
function bar($baz) {
// uses one tab for indentation
}
}
"""
}
{
key: "space", display: "Space",
code: """
class Foo {
function bar($baz) {
// uses spaces for indentation
}
}
"""
}
]
tab: 0
space: 0
commits: []
) unless convention.indent
tab = /^\t+.*/
space = /^\s+.*/
convention.indent.tab = convention.indent.tab + 1 if tab.test line
convention.indent.space = convention.indent.space + 1 if space.test line
convention.indent.commits.push commitUrl if tab.test(line) or space.test(line)
convention.indent.commits = _.uniq convention.indent.commits
convention
classBrace: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.classBrace =
title: "Brace Placement (Class)"
column: [
{
key: "newline", display: "Class opening/closing braces on seperate line (Allman)",
code: """
class Foo
{
// ...
}
"""
}
{
key: "sameline", display: "Class structure opening/closing braces on same line as declaration (OTBS)",
code: """
class Foo {
// ...
}
"""
}
]
newline: 0
sameline: 0
commits: []
) unless convention.classBrace
newline = (line) ->
temp = line.replace /\/\/.*/g, ''
///^(\s|\\t)*class\s+\w+\s*(extends\s*\w+)?\s*$///.test temp
sameline = (line) ->
temp = line.replace /\/\/.*/g, ''
///^(\s|\\t)*class\s+\w+\s*(extends\s*\w+)?\s+{///.test temp
convention.classBrace.newline = convention.classBrace.newline + 1 if newline line
convention.classBrace.sameline = convention.classBrace.sameline + 1 if sameline line
convention.classBrace.commits.push commitUrl if newline(line) or sameline(line)
convention.classBrace.commits = _.uniq convention.classBrace.commits
convention
controlBrace: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.controlBrace =
title: "Brace Placement (Control Structures)"
column: [
{
key: "sameline", display: "Control structure opening/closing braces on same line as declaration",
code: """
if($baz) {
// ..
} elseif($bar) {
// ..
} else {
// ..
}
while ($i <= 10) {
// ..
}
switch($beer) {
// ..
}
"""
}
{
key: "newline", display: "Control structure opening/closing braces on seperate line from declaration",
code: """
if($baz)
{
// ..
}
elseif($bar)
{
// ..
}
else
{
// ..
}
while ($i <= 10)
{
// ..
}
switch($beer)
{
// ..
}
"""
}
]
sameline: 0
newline: 0
commits: []
) unless convention.controlBrace
sameline = (line) ->
temp = line.replace /\/\/.*/g, ''
///((if|while|switch).*{)|(}\s*(else|elseif).*{)///.test temp
newline = (line) ->
temp = line.replace /\/\/.*/g, ''
///^\s*(((if|while|switch).*)|(\s*(else|elseif).*))[^{|:]$///.test temp
convention.controlBrace.sameline = convention.controlBrace.sameline + 1 if sameline line
convention.controlBrace.newline = convention.controlBrace.newline + 1 if newline line
convention.controlBrace.commits.push commitUrl if newline(line) or sameline(line)
convention.controlBrace.commits = _.uniq convention.controlBrace.commits
convention
methodBrace: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.methodBrace =
title: "Brace Placement (Methods)"
column: [
{
key: "sameline", display: "Method structure opening braces on same line as declaration (OTBS)",
code: """
function bar($baz) {
// ...
}
"""
}
{
key: "newline", display: "Method opening/closing braces on seperate line (Allman)",
code: """
function bar($baz)
{
// ...
}
"""
}
]
sameline: 0
newline: 0
commits: []
) unless convention.methodBrace
sameline = (line) ->
temp = line.replace /\/\/.*/g, ''
///^[\s|\t]*function\s+\w+\(.*?\)\s*{///.test temp
newline = (line) ->
temp = line.replace /\/\/.*/g, ''
///^[\s|\t]*function\s+\w+\(.*?\)\s*$///.test temp
convention.methodBrace.sameline = convention.methodBrace.sameline + 1 if sameline line
convention.methodBrace.newline = convention.methodBrace.newline + 1 if newline line
convention.methodBrace.commits.push commitUrl if newline(line) or sameline(line)
convention.methodBrace.commits = _.uniq convention.methodBrace.commits
convention
spaceAroundControl: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.spaceAroundControl =
title: "Space Around Control Structure Evaluation Block"
column: [
{
key: "space", display: "Space around control structure Evaluation block",
code: """
if ($baz) {
// ...
} elseif ($bar) {
// ...
} else {
// ...
}
while ($i <= 10) {
// ...
}
switch ($beer) {
// ...
}
"""
}
{
key: "nospace", display: "No space around control structure Evaluation block",
code: """
if($baz){
// ...
}elseif($bar){
// ...
}else{
// ...
}
while($i <= 10){
// ...
}
switch($beer){
// ...
}
"""
}
]
space: 0
nospace: 0
commits: []
) unless convention.spaceAroundControl
space = /((if|elseif|while|for)\s+\(.*?\)\s+({|:))|(do\s+{)/
nospace = /((if|elseif|while|for)\(.*?\)({|:))|(do{)/
convention.spaceAroundControl.space = convention.spaceAroundControl.space + 1 if space.test line
convention.spaceAroundControl.nospace = convention.spaceAroundControl.nospace + 1 if nospace.test line
convention.spaceAroundControl.commits.push commitUrl if nospace.test(line) or space.test(line)
convention.spaceAroundControl.commits = _.uniq convention.spaceAroundControl.commits
convention
spaceInsideControl: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.spaceInsideControl =
title: "Space Inside Control Structure Evaluation Block"
column: [
{
key: "space", display: "Space inside control structure Evaluation block",
code: """
if ( $baz ) {
// ...
} elseif ( $bar ) {
// ...
}
while ( $i <= 10 ) {
// ...
}
switch ( $beer ) {
// ...
}
"""
}
{
key: "nospace", display: "No space inside control structure Evaluation block",
code: """
if ($baz) {
// ...
} elseif ($bar) {
// ...
}
while ($i <= 10) {
// ...
}
switch ($beer) {
// ...
}
"""
}
]
space: 0
nospace: 0
commits: []
) unless convention.spaceInsideControl
space = /(if|elseif|while|for)\s*\(\s+.+?\s+\)/
nospace = /(if|elseif|while|for)\s*\(\S+.*?\S\)/
convention.spaceInsideControl.space = convention.spaceInsideControl.space + 1 if space.test line
convention.spaceInsideControl.nospace = convention.spaceInsideControl.nospace + 1 if nospace.test line
convention.spaceInsideControl.commits.push commitUrl if nospace.test(line) or space.test(line)
convention.spaceInsideControl.commits = _.uniq convention.spaceInsideControl.commits
convention
spaceAroundMethod: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.spaceAroundMethod =
title: "Space Around Method Declaration Param Block"
column: [
{
key: "space", display: "Space around parameter declaration block",
code: """
function bar ($baz) {
// ...
}
"""
}
{
key: "nospace", display: "No space around parameter declaration block",
code: """
function bar($baz){
// ...
}
"""
}
]
space: 0
nospace: 0
commits: []
) unless convention.spaceAroundMethod
space = /^[\s\t]*function\s+\w+\s+\(.*?\)\s+{/
nospace = /^[\s\t]*function\s+\w+\(.*?\){/
convention.spaceAroundMethod.space = convention.spaceAroundMethod.space + 1 if space.test line
convention.spaceAroundMethod.nospace = convention.spaceAroundMethod.nospace + 1 if nospace.test line
convention.spaceAroundMethod.commits.push commitUrl if nospace.test(line) or space.test(line)
convention.spaceAroundMethod.commits = _.uniq convention.spaceAroundMethod.commits
convention
spaceInsideMethod: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.spaceInsideMethod =
title: "Space Inside Method Declaration Param Block"
column: [
{
key: "space", display: "Space inside parameter declaration block",
code: """
function bar( $baz ){
// ...
}
"""
}
{
key: "nospace", display: "No space inside parameter declaration block",
code: """
function bar($baz){
// ...
}
"""
}
]
space: 0
nospace: 0
commits: []
) unless convention.spaceInsideMethod
space = /^[\s|\t]*function\s+\w+\s*\(\s+.+?\s+\)/
nospace = /^[\s|\t]*function\s+\w+\s*\(\S+.*?\S\)/
convention.spaceInsideMethod.space = convention.spaceInsideMethod.space + 1 if space.test line
convention.spaceInsideMethod.nospace = convention.spaceInsideMethod.nospace + 1 if nospace.test line
convention.spaceInsideMethod.commits.push commitUrl if nospace.test(line) or space.test(line)
convention.spaceInsideMethod.commits = _.uniq convention.spaceInsideMethod.commits
convention
className: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.className =
title: "Class Names"
column: [
{
key: "camel", display: "Class Name in camelCase",
code: """
class fooBarBaz {
// ...
}
"""
}
{
key: "pascal", display: "Class Name in PascalCase",
code: """
class FooBarBaz {
// ...
}
"""
}
{
key: "capssnake", display: "Class Name in CAPS_SNAKE_CASE",
code: """
class FOO_BAR_BAZ {
// ...
}
"""
}
{
key: "snakepascal", display: "Class Name in Snake_Pascal_Case",
code: """
class Foo_Bar_Baz {
// ...
}
"""
}
{
key: "snake", display: "Class Name in snake_case",
code: """
class foo_bar_baz {
// ...
}
"""
}
{
key: "uppersnake", display: "Class Snake_first_letter_uppercase",
code: """
class Foo_bar_baz {
// ...
}
"""
}
]
camel: 0
pascal: 0
capssnake: 0
snakepascal: 0
snake: 0
uppersnake: 0
commits: []
) unless convention.className
camel = /^[\s|\t]*class\s+[a-z][a-z0-9]*([A-Z][a-z0-9]+)+(\b|\s|{)/
pascal = /^[\s|\t]*class\s+([A-Z][a-z0-9]+){2,}(\b|\s|{)/
capssnake = /^[\s|\t]*class\s+([A-Z0-9]+_)+[A-Z0-9]+(\b|\s|{)/
snakepascal = /^[\s|\t]*class\s+(([A-Z][a-z0-9]+)_)+[A-Z][a-z0-9]+(\b|\s|{)/
snake = /^[\s|\t]*class\s+(([a-z][a-z0-9]+)_)+[a-z][a-z0-9]+(\b|\s|{)/
uppersnake = /^[\s|\t]*class\s+(([A-Z][a-z0-9]+)_)([a-z][a-z0-9]+_)+[a-z][a-z0-9]+(\b|\s|{)/
convention.className.camel = convention.className.camel + 1 if camel.test line
convention.className.pascal = convention.className.pascal + 1 if pascal.test line
convention.className.capssnake = convention.className.capssnake + 1 if capssnake.test line
convention.className.snakepascal = convention.className.snakepascal + 1 if snakepascal.test line
convention.className.snake = convention.className.snake + 1 if snake.test line
convention.className.uppersnake = convention.className.uppersnake + 1 if uppersnake.test line
convention.className.commits.push commitUrl if camel.test(line) or pascal.test(line) or
capssnake.test(line) or snakepascal.test(line) or
snake.test(line) or uppersnake.test(line)
convention.className.commits = _.uniq convention.className.commits
convention
constName: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.constName =
title: "Constant Names"
column: [
{
key: "camel", display: "Constant Name in camelCase",
code: """
const barBaz = 0;
define('barBaz', 0);
"""
}
{
key: "pascal", display: "Constant Name in PascalCase",
code: """
const BarBaz = 0;
define('BarBaz', 0);
"""
}
{
key: "capssnake", display: "Constant Name in CAPS_SNAKE_CASE",
code: """
const BAR_BAZ = 0;
define('BAR_BAZ', 0);
"""
}
{
key: "snakepascal", display: "Constant Name in Snake_Pascal_Case",
code: """
const Bar_Baz = 0;
define('Bar_Baz', 0);
"""
}
{
key: "snake", display: "Constant Name in snake_case",
code: """
const bar_baz = 0;
define('bar_baz', 0);
"""
}
]
camel: 0
pascal: 0
capssnake: 0
snakepascal: 0
snake: 0
commits: []
) unless convention.constName
camel = /(^[\s|\t]*const\s+[a-z][a-z0-9]*([A-Z][a-z0-9]+)+\s*=)|([\s|\t]*define\(s*['"][a-z][a-z0-9]*([A-Z][a-z0-9]+)+['"]s*,)/
pascal = /(^[\s|\t]*const\s+([A-Z][a-z0-9]+){2,}\s*=)|([\s|\t]*define\(s*['"]([A-Z][a-z0-9]+){2,}['"]s*,)/
capssnake = /(^[\s|\t]*const\s+([A-Z0-9]+_)+[A-Z0-9]+\s*=)|([\s|\t]*define\(s*['"]([A-Z0-9]+_)+[A-Z0-9]+['"]s*,)/
snakepascal = /(^[\s|\t]*const\s+(([A-Z][a-z0-9]+)_)+[A-Z][a-z0-9]+\s*=)|([\s|\t]*define\(s*['"](([A-Z][a-z0-9]+)_)+[A-Z][a-z0-9]+['"]s*,)/
snake = /(^[\s|\t]*const\s+(([a-z][a-z0-9]+)_)+[a-z][a-z0-9]+\s*=)|([\s|\t]*define\(s*['"](([a-z][a-z0-9]+)_)+[a-z][a-z0-9]+['"]s*,)/
convention.constName.camel = convention.constName.camel + 1 if camel.test line
convention.constName.pascal = convention.constName.pascal + 1 if pascal.test line
convention.constName.capssnake = convention.constName.capssnake + 1 if capssnake.test line
convention.constName.snakepascal = convention.constName.snakepascal + 1 if snakepascal.test line
convention.constName.snake = convention.constName.snake + 1 if snake.test line
convention.constName.commits.push commitUrl if camel.test(line) or pascal.test(line) or
capssnake.test(line) or snakepascal.test(line) or
snake.test(line)
convention.constName.commits = _.uniq convention.constName.commits
convention
functionName: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.functionName =
title: "Function Names"
column: [
{
key: "camel", display: "Function Name in camelCase",
code: """
function barBaz(){
// ...
}
"""
}
{
key: "pascal", display: "Function Name in PascalCase",
code: """
function BarBaz(){
// ...
}
"""
}
{
key: "capssnake", display: "Function Name in CAPS_SNAKE_CASE",
code: """
function BAR_BAZ(){
// ...
}
"""
}
{
key: "snakepascal", display: "Function Name in Snake_Pascal_Case",
code: """
function Bar_Baz(){
// ...
}
"""
}
{
key: "snake", display: "Function Name in snake_case",
code: """
function bar_baz(){
// ...
}
"""
}
]
camel: 0
pascal: 0
capssnake: 0
snakepascal: 0
snake: 0
commits: []
) unless convention.functionName
camel = /function\s+[a-z][a-z0-9]*([A-Z][a-z0-9]+)+\s*\(/
pascal = /function\s+([A-Z][a-z0-9]+){2,}\s*\(/
capssnake = /function\s+([A-Z0-9]+_)+[A-Z0-9]+\s*\(/
snakepascal = /function\s+(([A-Z][a-z0-9]+)_)+[A-Z][a-z0-9]+\s*\(/
snake = /function\s+(([a-z][a-z0-9]+)_)+[a-z][a-z0-9]+\s*\(/
convention.functionName.camel = convention.functionName.camel + 1 if camel.test line
convention.functionName.pascal = convention.functionName.pascal + 1 if pascal.test line
convention.functionName.capssnake = convention.functionName.capssnake + 1 if capssnake.test line
convention.functionName.snakepascal = convention.functionName.snakepascal + 1 if snakepascal.test line
convention.functionName.snake = convention.functionName.snake + 1 if snake.test line
convention.functionName.commits.push commitUrl if camel.test(line) or pascal.test(line) or
capssnake.test(line) or snakepascal.test(line) or
snake.test(line)
convention.functionName.commits = _.uniq convention.functionName.commits
convention
methodDeclare: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.methodDeclare =
title: "Method Declare Order"
column: [
{
key: "staticlate", display: "static declared after visibility",
code: """
class Foo
{
public static function bar($baz)
{
// ...
}
}
"""
}
{
key: "staticfirst", display: "static declared before visibility",
code: """
class Foo
{
static public function bar($baz)
{
// ...
}
}
"""
}
{
key: "abstractlate", display: "abstract (or final) declared after visibility",
code: """
class Foo
{
public abstract function bar($baz);
// ...
}
"""
}
{
key: "abstractfirst", display: "abstract (or final) declared before visibility",
code: """
class Foo
{
abstract public function bar($baz);
// ...
}
"""
}
]
staticlate: 0
staticfirst: 0
abstractlate: 0
abstractfirst: 0
commits: []
) unless convention.methodDeclare
staticlate = /(public|protected|private)\s+static\s+\$*\w*/
staticfirst = /static\s+(public|protected|private)\s+\$*\w*/
abstractlate = /(public|protected|private)\s+(abstract|final)\s+\$*\w*/
abstractfirst = /(abstract|final)\s+(public|protected|private)\s+\$*\w*/
convention.methodDeclare.staticlate = convention.methodDeclare.staticlate + 1 if staticlate.test line
convention.methodDeclare.staticfirst = convention.methodDeclare.staticfirst + 1 if staticfirst.test line
convention.methodDeclare.abstractlate = convention.methodDeclare.abstractlate + 1 if abstractlate.test line
convention.methodDeclare.abstractfirst = convention.methodDeclare.abstractfirst + 1 if abstractfirst.test line
convention.methodDeclare.commits.push commitUrl if staticlate.test(line) or staticfirst.test(line) or
abstractlate.test(line) or abstractfirst.test(line)
convention.methodDeclare.commits = _.uniq convention.methodDeclare.commits
convention
linelength: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.linelength =
title: "Line length is over 80 characters?"
column: [
{
key: "char80", display: "Line length is within 80 characters.",
code: "/* width is within 80 characters */"
}
{
key: "char120", display: "Line length is within 120 characters",
code: "/* width is within 120 characters */"
}
{
key: "char150", display: "Line length is within 150 characters",
code: "/* width is within 150 characters */"
}
]
char80: 0
char120: 0
char150: 0
commits: []
) unless convention.linelength
width = line.length
tabcount = line.split('\t').length - 1
# assume tab size is 4 space
width += tabcount * 3
if width < 80
convention.linelength.char80 = convention.linelength.char80 + 1
else if width < 120
convention.linelength.char120 = convention.linelength.char120 + 1
else
convention.linelength.char150 = convention.linelength.char150 + 1
convention.linelength.commits.push commitUrl
convention.linelength.commits = _.uniq convention.linelength.commits
convention
| true | # parsing PHP code
#
# Copyright (c) 2013 PI:NAME:<NAME>END_PI aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
helpers = require '../helpers'
_ = require 'underscore'
phpParser = module.exports =
lang: 'php'
parse: (line, convention, commitUrl) ->
convention = this.indent line, convention, commitUrl
convention = this.classBrace line, convention, commitUrl
convention = this.controlBrace line, convention, commitUrl
convention = this.methodBrace line, convention, commitUrl
convention = this.spaceAroundControl line, convention, commitUrl
convention = this.spaceInsideControl line, convention, commitUrl
convention = this.spaceAroundMethod line, convention, commitUrl
convention = this.spaceInsideMethod line, convention, commitUrl
convention = this.className line, convention, commitUrl
convention = this.constName line, convention, commitUrl
convention = this.functionName line, convention, commitUrl
convention = this.methodDeclare line, convention, commitUrl
convention = this.linelength line, convention, commitUrl
indent: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.indent =
title: "Space vs. Tab"
column: [
{
key: "tab", display: "Tab",
code: """
class Foo {
function bar($baz) {
// uses one tab for indentation
}
}
"""
}
{
key: "space", display: "Space",
code: """
class Foo {
function bar($baz) {
// uses spaces for indentation
}
}
"""
}
]
tab: 0
space: 0
commits: []
) unless convention.indent
tab = /^\t+.*/
space = /^\s+.*/
convention.indent.tab = convention.indent.tab + 1 if tab.test line
convention.indent.space = convention.indent.space + 1 if space.test line
convention.indent.commits.push commitUrl if tab.test(line) or space.test(line)
convention.indent.commits = _.uniq convention.indent.commits
convention
classBrace: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.classBrace =
title: "Brace Placement (Class)"
column: [
{
key: "newline", display: "Class opening/closing braces on seperate line (Allman)",
code: """
class Foo
{
// ...
}
"""
}
{
key: "sameline", display: "Class structure opening/closing braces on same line as declaration (OTBS)",
code: """
class Foo {
// ...
}
"""
}
]
newline: 0
sameline: 0
commits: []
) unless convention.classBrace
newline = (line) ->
temp = line.replace /\/\/.*/g, ''
///^(\s|\\t)*class\s+\w+\s*(extends\s*\w+)?\s*$///.test temp
sameline = (line) ->
temp = line.replace /\/\/.*/g, ''
///^(\s|\\t)*class\s+\w+\s*(extends\s*\w+)?\s+{///.test temp
convention.classBrace.newline = convention.classBrace.newline + 1 if newline line
convention.classBrace.sameline = convention.classBrace.sameline + 1 if sameline line
convention.classBrace.commits.push commitUrl if newline(line) or sameline(line)
convention.classBrace.commits = _.uniq convention.classBrace.commits
convention
controlBrace: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.controlBrace =
title: "Brace Placement (Control Structures)"
column: [
{
key: "sameline", display: "Control structure opening/closing braces on same line as declaration",
code: """
if($baz) {
// ..
} elseif($bar) {
// ..
} else {
// ..
}
while ($i <= 10) {
// ..
}
switch($beer) {
// ..
}
"""
}
{
key: "newline", display: "Control structure opening/closing braces on seperate line from declaration",
code: """
if($baz)
{
// ..
}
elseif($bar)
{
// ..
}
else
{
// ..
}
while ($i <= 10)
{
// ..
}
switch($beer)
{
// ..
}
"""
}
]
sameline: 0
newline: 0
commits: []
) unless convention.controlBrace
sameline = (line) ->
temp = line.replace /\/\/.*/g, ''
///((if|while|switch).*{)|(}\s*(else|elseif).*{)///.test temp
newline = (line) ->
temp = line.replace /\/\/.*/g, ''
///^\s*(((if|while|switch).*)|(\s*(else|elseif).*))[^{|:]$///.test temp
convention.controlBrace.sameline = convention.controlBrace.sameline + 1 if sameline line
convention.controlBrace.newline = convention.controlBrace.newline + 1 if newline line
convention.controlBrace.commits.push commitUrl if newline(line) or sameline(line)
convention.controlBrace.commits = _.uniq convention.controlBrace.commits
convention
methodBrace: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.methodBrace =
title: "Brace Placement (Methods)"
column: [
{
key: "sameline", display: "Method structure opening braces on same line as declaration (OTBS)",
code: """
function bar($baz) {
// ...
}
"""
}
{
key: "newline", display: "Method opening/closing braces on seperate line (Allman)",
code: """
function bar($baz)
{
// ...
}
"""
}
]
sameline: 0
newline: 0
commits: []
) unless convention.methodBrace
sameline = (line) ->
temp = line.replace /\/\/.*/g, ''
///^[\s|\t]*function\s+\w+\(.*?\)\s*{///.test temp
newline = (line) ->
temp = line.replace /\/\/.*/g, ''
///^[\s|\t]*function\s+\w+\(.*?\)\s*$///.test temp
convention.methodBrace.sameline = convention.methodBrace.sameline + 1 if sameline line
convention.methodBrace.newline = convention.methodBrace.newline + 1 if newline line
convention.methodBrace.commits.push commitUrl if newline(line) or sameline(line)
convention.methodBrace.commits = _.uniq convention.methodBrace.commits
convention
spaceAroundControl: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.spaceAroundControl =
title: "Space Around Control Structure Evaluation Block"
column: [
{
key: "space", display: "Space around control structure Evaluation block",
code: """
if ($baz) {
// ...
} elseif ($bar) {
// ...
} else {
// ...
}
while ($i <= 10) {
// ...
}
switch ($beer) {
// ...
}
"""
}
{
key: "nospace", display: "No space around control structure Evaluation block",
code: """
if($baz){
// ...
}elseif($bar){
// ...
}else{
// ...
}
while($i <= 10){
// ...
}
switch($beer){
// ...
}
"""
}
]
space: 0
nospace: 0
commits: []
) unless convention.spaceAroundControl
space = /((if|elseif|while|for)\s+\(.*?\)\s+({|:))|(do\s+{)/
nospace = /((if|elseif|while|for)\(.*?\)({|:))|(do{)/
convention.spaceAroundControl.space = convention.spaceAroundControl.space + 1 if space.test line
convention.spaceAroundControl.nospace = convention.spaceAroundControl.nospace + 1 if nospace.test line
convention.spaceAroundControl.commits.push commitUrl if nospace.test(line) or space.test(line)
convention.spaceAroundControl.commits = _.uniq convention.spaceAroundControl.commits
convention
spaceInsideControl: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.spaceInsideControl =
title: "Space Inside Control Structure Evaluation Block"
column: [
{
key: "space", display: "Space inside control structure Evaluation block",
code: """
if ( $baz ) {
// ...
} elseif ( $bar ) {
// ...
}
while ( $i <= 10 ) {
// ...
}
switch ( $beer ) {
// ...
}
"""
}
{
key: "nospace", display: "No space inside control structure Evaluation block",
code: """
if ($baz) {
// ...
} elseif ($bar) {
// ...
}
while ($i <= 10) {
// ...
}
switch ($beer) {
// ...
}
"""
}
]
space: 0
nospace: 0
commits: []
) unless convention.spaceInsideControl
space = /(if|elseif|while|for)\s*\(\s+.+?\s+\)/
nospace = /(if|elseif|while|for)\s*\(\S+.*?\S\)/
convention.spaceInsideControl.space = convention.spaceInsideControl.space + 1 if space.test line
convention.spaceInsideControl.nospace = convention.spaceInsideControl.nospace + 1 if nospace.test line
convention.spaceInsideControl.commits.push commitUrl if nospace.test(line) or space.test(line)
convention.spaceInsideControl.commits = _.uniq convention.spaceInsideControl.commits
convention
spaceAroundMethod: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.spaceAroundMethod =
title: "Space Around Method Declaration Param Block"
column: [
{
key: "space", display: "Space around parameter declaration block",
code: """
function bar ($baz) {
// ...
}
"""
}
{
key: "nospace", display: "No space around parameter declaration block",
code: """
function bar($baz){
// ...
}
"""
}
]
space: 0
nospace: 0
commits: []
) unless convention.spaceAroundMethod
space = /^[\s\t]*function\s+\w+\s+\(.*?\)\s+{/
nospace = /^[\s\t]*function\s+\w+\(.*?\){/
convention.spaceAroundMethod.space = convention.spaceAroundMethod.space + 1 if space.test line
convention.spaceAroundMethod.nospace = convention.spaceAroundMethod.nospace + 1 if nospace.test line
convention.spaceAroundMethod.commits.push commitUrl if nospace.test(line) or space.test(line)
convention.spaceAroundMethod.commits = _.uniq convention.spaceAroundMethod.commits
convention
spaceInsideMethod: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.spaceInsideMethod =
title: "Space Inside Method Declaration Param Block"
column: [
{
key: "space", display: "Space inside parameter declaration block",
code: """
function bar( $baz ){
// ...
}
"""
}
{
key: "nospace", display: "No space inside parameter declaration block",
code: """
function bar($baz){
// ...
}
"""
}
]
space: 0
nospace: 0
commits: []
) unless convention.spaceInsideMethod
space = /^[\s|\t]*function\s+\w+\s*\(\s+.+?\s+\)/
nospace = /^[\s|\t]*function\s+\w+\s*\(\S+.*?\S\)/
convention.spaceInsideMethod.space = convention.spaceInsideMethod.space + 1 if space.test line
convention.spaceInsideMethod.nospace = convention.spaceInsideMethod.nospace + 1 if nospace.test line
convention.spaceInsideMethod.commits.push commitUrl if nospace.test(line) or space.test(line)
convention.spaceInsideMethod.commits = _.uniq convention.spaceInsideMethod.commits
convention
className: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.className =
title: "Class Names"
column: [
{
key: "camel", display: "Class Name in camelCase",
code: """
class fooBarBaz {
// ...
}
"""
}
{
key: "pascal", display: "Class Name in PascalCase",
code: """
class FooBarBaz {
// ...
}
"""
}
{
key: "capssnake", display: "Class Name in CAPS_SNAKE_CASE",
code: """
class FOO_BAR_BAZ {
// ...
}
"""
}
{
key: "snakepascal", display: "Class Name in Snake_Pascal_Case",
code: """
class Foo_Bar_Baz {
// ...
}
"""
}
{
key: "snake", display: "Class Name in snake_case",
code: """
class foo_bar_baz {
// ...
}
"""
}
{
key: "uppersnake", display: "Class Snake_first_letter_uppercase",
code: """
class Foo_bar_baz {
// ...
}
"""
}
]
camel: 0
pascal: 0
capssnake: 0
snakepascal: 0
snake: 0
uppersnake: 0
commits: []
) unless convention.className
camel = /^[\s|\t]*class\s+[a-z][a-z0-9]*([A-Z][a-z0-9]+)+(\b|\s|{)/
pascal = /^[\s|\t]*class\s+([A-Z][a-z0-9]+){2,}(\b|\s|{)/
capssnake = /^[\s|\t]*class\s+([A-Z0-9]+_)+[A-Z0-9]+(\b|\s|{)/
snakepascal = /^[\s|\t]*class\s+(([A-Z][a-z0-9]+)_)+[A-Z][a-z0-9]+(\b|\s|{)/
snake = /^[\s|\t]*class\s+(([a-z][a-z0-9]+)_)+[a-z][a-z0-9]+(\b|\s|{)/
uppersnake = /^[\s|\t]*class\s+(([A-Z][a-z0-9]+)_)([a-z][a-z0-9]+_)+[a-z][a-z0-9]+(\b|\s|{)/
convention.className.camel = convention.className.camel + 1 if camel.test line
convention.className.pascal = convention.className.pascal + 1 if pascal.test line
convention.className.capssnake = convention.className.capssnake + 1 if capssnake.test line
convention.className.snakepascal = convention.className.snakepascal + 1 if snakepascal.test line
convention.className.snake = convention.className.snake + 1 if snake.test line
convention.className.uppersnake = convention.className.uppersnake + 1 if uppersnake.test line
convention.className.commits.push commitUrl if camel.test(line) or pascal.test(line) or
capssnake.test(line) or snakepascal.test(line) or
snake.test(line) or uppersnake.test(line)
convention.className.commits = _.uniq convention.className.commits
convention
constName: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.constName =
title: "Constant Names"
column: [
{
key: "camel", display: "Constant Name in camelCase",
code: """
const barBaz = 0;
define('barBaz', 0);
"""
}
{
key: "pascal", display: "Constant Name in PascalCase",
code: """
const BarBaz = 0;
define('BarBaz', 0);
"""
}
{
key: "capssnake", display: "Constant Name in CAPS_SNAKE_CASE",
code: """
const BAR_BAZ = 0;
define('BAR_BAZ', 0);
"""
}
{
key: "snakepascal", display: "Constant Name in Snake_Pascal_Case",
code: """
const Bar_Baz = 0;
define('Bar_Baz', 0);
"""
}
{
key: "snake", display: "Constant Name in snake_case",
code: """
const bar_baz = 0;
define('bar_baz', 0);
"""
}
]
camel: 0
pascal: 0
capssnake: 0
snakepascal: 0
snake: 0
commits: []
) unless convention.constName
camel = /(^[\s|\t]*const\s+[a-z][a-z0-9]*([A-Z][a-z0-9]+)+\s*=)|([\s|\t]*define\(s*['"][a-z][a-z0-9]*([A-Z][a-z0-9]+)+['"]s*,)/
pascal = /(^[\s|\t]*const\s+([A-Z][a-z0-9]+){2,}\s*=)|([\s|\t]*define\(s*['"]([A-Z][a-z0-9]+){2,}['"]s*,)/
capssnake = /(^[\s|\t]*const\s+([A-Z0-9]+_)+[A-Z0-9]+\s*=)|([\s|\t]*define\(s*['"]([A-Z0-9]+_)+[A-Z0-9]+['"]s*,)/
snakepascal = /(^[\s|\t]*const\s+(([A-Z][a-z0-9]+)_)+[A-Z][a-z0-9]+\s*=)|([\s|\t]*define\(s*['"](([A-Z][a-z0-9]+)_)+[A-Z][a-z0-9]+['"]s*,)/
snake = /(^[\s|\t]*const\s+(([a-z][a-z0-9]+)_)+[a-z][a-z0-9]+\s*=)|([\s|\t]*define\(s*['"](([a-z][a-z0-9]+)_)+[a-z][a-z0-9]+['"]s*,)/
convention.constName.camel = convention.constName.camel + 1 if camel.test line
convention.constName.pascal = convention.constName.pascal + 1 if pascal.test line
convention.constName.capssnake = convention.constName.capssnake + 1 if capssnake.test line
convention.constName.snakepascal = convention.constName.snakepascal + 1 if snakepascal.test line
convention.constName.snake = convention.constName.snake + 1 if snake.test line
convention.constName.commits.push commitUrl if camel.test(line) or pascal.test(line) or
capssnake.test(line) or snakepascal.test(line) or
snake.test(line)
convention.constName.commits = _.uniq convention.constName.commits
convention
functionName: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.functionName =
title: "Function Names"
column: [
{
key: "camel", display: "Function Name in camelCase",
code: """
function barBaz(){
// ...
}
"""
}
{
key: "pascal", display: "Function Name in PascalCase",
code: """
function BarBaz(){
// ...
}
"""
}
{
key: "capssnake", display: "Function Name in CAPS_SNAKE_CASE",
code: """
function BAR_BAZ(){
// ...
}
"""
}
{
key: "snakepascal", display: "Function Name in Snake_Pascal_Case",
code: """
function Bar_Baz(){
// ...
}
"""
}
{
key: "snake", display: "Function Name in snake_case",
code: """
function bar_baz(){
// ...
}
"""
}
]
camel: 0
pascal: 0
capssnake: 0
snakepascal: 0
snake: 0
commits: []
) unless convention.functionName
camel = /function\s+[a-z][a-z0-9]*([A-Z][a-z0-9]+)+\s*\(/
pascal = /function\s+([A-Z][a-z0-9]+){2,}\s*\(/
capssnake = /function\s+([A-Z0-9]+_)+[A-Z0-9]+\s*\(/
snakepascal = /function\s+(([A-Z][a-z0-9]+)_)+[A-Z][a-z0-9]+\s*\(/
snake = /function\s+(([a-z][a-z0-9]+)_)+[a-z][a-z0-9]+\s*\(/
convention.functionName.camel = convention.functionName.camel + 1 if camel.test line
convention.functionName.pascal = convention.functionName.pascal + 1 if pascal.test line
convention.functionName.capssnake = convention.functionName.capssnake + 1 if capssnake.test line
convention.functionName.snakepascal = convention.functionName.snakepascal + 1 if snakepascal.test line
convention.functionName.snake = convention.functionName.snake + 1 if snake.test line
convention.functionName.commits.push commitUrl if camel.test(line) or pascal.test(line) or
capssnake.test(line) or snakepascal.test(line) or
snake.test(line)
convention.functionName.commits = _.uniq convention.functionName.commits
convention
methodDeclare: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.methodDeclare =
title: "Method Declare Order"
column: [
{
key: "staticlate", display: "static declared after visibility",
code: """
class Foo
{
public static function bar($baz)
{
// ...
}
}
"""
}
{
key: "staticfirst", display: "static declared before visibility",
code: """
class Foo
{
static public function bar($baz)
{
// ...
}
}
"""
}
{
key: "abstractlate", display: "abstract (or final) declared after visibility",
code: """
class Foo
{
public abstract function bar($baz);
// ...
}
"""
}
{
key: "abstractfirst", display: "abstract (or final) declared before visibility",
code: """
class Foo
{
abstract public function bar($baz);
// ...
}
"""
}
]
staticlate: 0
staticfirst: 0
abstractlate: 0
abstractfirst: 0
commits: []
) unless convention.methodDeclare
staticlate = /(public|protected|private)\s+static\s+\$*\w*/
staticfirst = /static\s+(public|protected|private)\s+\$*\w*/
abstractlate = /(public|protected|private)\s+(abstract|final)\s+\$*\w*/
abstractfirst = /(abstract|final)\s+(public|protected|private)\s+\$*\w*/
convention.methodDeclare.staticlate = convention.methodDeclare.staticlate + 1 if staticlate.test line
convention.methodDeclare.staticfirst = convention.methodDeclare.staticfirst + 1 if staticfirst.test line
convention.methodDeclare.abstractlate = convention.methodDeclare.abstractlate + 1 if abstractlate.test line
convention.methodDeclare.abstractfirst = convention.methodDeclare.abstractfirst + 1 if abstractfirst.test line
convention.methodDeclare.commits.push commitUrl if staticlate.test(line) or staticfirst.test(line) or
abstractlate.test(line) or abstractfirst.test(line)
convention.methodDeclare.commits = _.uniq convention.methodDeclare.commits
convention
linelength: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.linelength =
title: "Line length is over 80 characters?"
column: [
{
key: "char80", display: "Line length is within 80 characters.",
code: "/* width is within 80 characters */"
}
{
key: "char120", display: "Line length is within 120 characters",
code: "/* width is within 120 characters */"
}
{
key: "char150", display: "Line length is within 150 characters",
code: "/* width is within 150 characters */"
}
]
char80: 0
char120: 0
char150: 0
commits: []
) unless convention.linelength
width = line.length
tabcount = line.split('\t').length - 1
# assume tab size is 4 space
width += tabcount * 3
if width < 80
convention.linelength.char80 = convention.linelength.char80 + 1
else if width < 120
convention.linelength.char120 = convention.linelength.char120 + 1
else
convention.linelength.char150 = convention.linelength.char150 + 1
convention.linelength.commits.push commitUrl
convention.linelength.commits = _.uniq convention.linelength.commits
convention
|
[
{
"context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http://o",
"end": 67,
"score": 0.8619314432144165,
"start": 62,
"tag": "NAME",
"value": "Hatio"
}
] | src/spec/SpecGuideLayer.coffee | heartyoh/infopik | 0 | # ==========================================
# Copyright 2014 Hatio, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'KineticJS'
], (
kin
) ->
"use strict"
view_factory = (attributes) ->
new kin.Layer(attributes)
onchange = (component, before, after, e) ->
controller = this
model = e.listener
view = controller.getAttachedViews(model)[0]
self = model._track = model._track || {}
self.changes = (self.changes || 0) + 1
if not self.text
self.text = new kin.Text
x: 10
y: 10
listening: false
fontSize: 12
fontFamily: 'Calibri'
fill: 'green'
view.add self.text
msg = "[ PropertyChange ] #{component.type} : #{component.get('id')}\n[ Before ] #{JSON.stringify(before)}\n[ After ] #{JSON.stringify(after)}"
self.text.setAttr 'text', msg
view.draw()
setTimeout ->
return if (--self.changes) > 0
tween = new Kinetic.Tween({
node: self.text
opacity: 0
duration: 1
easing: kin.Easings.EaseOut
})
tween.play();
setTimeout ->
if self.changes > 0
tween.reset()
tween.destroy()
return
tween.finish()
tween.destroy()
self.text.remove()
delete self.text
view.draw()
, 1000
, 5000
_nodeTracker = (guideLayer, node) ->
guideLayerOffset = guideLayer.offset()
nodeLayerOffset = node.getLayer().offset()
nodeAbsPosition = node.getAbsolutePosition()
scale = node.getStage().scale()
{
x: nodeAbsPosition.x / scale.x + guideLayerOffset.x
y: nodeAbsPosition.y / scale.y + guideLayerOffset.y
}
ondragstart = (e) ->
layer = @listener
node = e.targetNode
stage = layer.getStage()
@scale = stage.getScale()
@width = stage.getWidth()
@height = stage.getHeight()
guidePosition = _nodeTracker(layer, node)
@vert = new kin.Line
stroke: 'red'
tension: 1
points: [guidePosition.x, 0, guidePosition.x, @height]
@hori = new kin.Line
stroke: 'red'
tension: 1
points: [0, guidePosition.y, @width, guidePosition.y]
@text = new kin.Text
listening: false
fontSize: 12
fontFamily: 'Calibri'
fill: 'green'
@text.setAttrs
text: "[ #{guidePosition.x}(#{node.x()}), #{guidePosition.y}(#{node.y()}) ]"
x: if Math.max(guidePosition.x, 0) > (@text.width() + 10) then guidePosition.x - (@text.width() + 10) else Math.max(guidePosition.x + 10, 10)
y: if Math.max(guidePosition.y, 0) > (@text.height() + 10) then guidePosition.y - (@text.height() + 10) else Math.max(guidePosition.y + 10, 10)
layer.add(@vert)
layer.add(@hori)
layer.add(@text)
layer.batchDraw()
ondragmove = (e) ->
controller = @context
layer = @listener
node = e.targetNode
nodePositionCurrent = node.position()
node.position
x: Math.round(nodePositionCurrent.x / 10) * 10
y: Math.round(nodePositionCurrent.y / 10) * 10
guidePosition = _nodeTracker(layer, node)
@vert.setAttrs({points:[guidePosition.x, 0, guidePosition.x, @height]})
@hori.setAttrs({points:[0, guidePosition.y, @width, guidePosition.y]})
@text.setAttrs
text: "[ #{guidePosition.x}(#{node.x()}), #{guidePosition.y}(#{node.y()}) ]"
x: if Math.max(guidePosition.x, 0) > (@text.width() + 10) then guidePosition.x - (@text.width() + 10) else Math.max(guidePosition.x + 10, 10)
y: if Math.max(guidePosition.y, 0) > (@text.height() + 10) then guidePosition.y - (@text.height() + 10) else Math.max(guidePosition.y + 10, 10)
scale = node.getStage().scale()
autoMovingLeft = (node.getStage().width() + layer.offset().x) / scale.x * 1 / 5
autoMovingRight = (node.getStage().width() + layer.offset().x) / scale.x * 4 / 5
autoMovingTop = (node.getStage().height() + layer.offset().y) / scale.y * 1 / 5
autoMovingBottom = (node.getStage().height() + layer.offset().y) / scale.y * 4 / 5
console.log autoMovingLeft, autoMovingRight, autoMovingTop, autoMovingBottom
if guidePosition.x < autoMovingLeft or guidePosition.x > autoMovingRight or guidePosition.y < autoMovingTop or guidePosition.y > autoMovingBottom
nodeLayer = node.getLayer()
oldOffset = nodeLayer.offset()
x = if guidePosition.x <= autoMovingLeft
Math.max(oldOffset.x - 10, -20)
else if guidePosition.x >= autoMovingRight
oldOffset.x + 10
else oldOffset.x
y = if guidePosition.y <= autoMovingTop
Math.max(oldOffset.y - 10, -20)
else if guidePosition.y >= autoMovingBottom
oldOffset.y + 10
else oldOffset.y
console.log guidePosition, x, y
# TODO remove implicit dependency to content-edit-layer
if oldOffset.x != x or oldOffset.y != y
controller.offset
x: x
y: y
layer.batchDraw()
ondragend = (e) ->
layer = @listener
@vert.remove()
@hori.remove()
@text.remove()
layer.batchDraw()
onadded = (container, component, index, e) ->
onremoved = (container, component, e) ->
model_event_map =
'(root)' :
'(all)' :
'change' : onchange
'(self)' :
'(self)' :
'added' : onadded
'removed' : onremoved
view_event_map =
'(root)' :
dragstart : ondragstart
dragmove : ondragmove
dragend : ondragend
{
type: 'guide-layer'
name: 'guide-layer'
containable: true
container_type: 'layer'
description: 'Editing Guide Specification'
defaults: {
draggable: false
}
model_event_map: model_event_map
view_event_map: view_event_map
view_factory_fn: view_factory
toolbox_image: 'images/toolbox_guide_layer.png'
}
| 107214 | # ==========================================
# Copyright 2014 <NAME>, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'KineticJS'
], (
kin
) ->
"use strict"
view_factory = (attributes) ->
new kin.Layer(attributes)
onchange = (component, before, after, e) ->
controller = this
model = e.listener
view = controller.getAttachedViews(model)[0]
self = model._track = model._track || {}
self.changes = (self.changes || 0) + 1
if not self.text
self.text = new kin.Text
x: 10
y: 10
listening: false
fontSize: 12
fontFamily: 'Calibri'
fill: 'green'
view.add self.text
msg = "[ PropertyChange ] #{component.type} : #{component.get('id')}\n[ Before ] #{JSON.stringify(before)}\n[ After ] #{JSON.stringify(after)}"
self.text.setAttr 'text', msg
view.draw()
setTimeout ->
return if (--self.changes) > 0
tween = new Kinetic.Tween({
node: self.text
opacity: 0
duration: 1
easing: kin.Easings.EaseOut
})
tween.play();
setTimeout ->
if self.changes > 0
tween.reset()
tween.destroy()
return
tween.finish()
tween.destroy()
self.text.remove()
delete self.text
view.draw()
, 1000
, 5000
_nodeTracker = (guideLayer, node) ->
guideLayerOffset = guideLayer.offset()
nodeLayerOffset = node.getLayer().offset()
nodeAbsPosition = node.getAbsolutePosition()
scale = node.getStage().scale()
{
x: nodeAbsPosition.x / scale.x + guideLayerOffset.x
y: nodeAbsPosition.y / scale.y + guideLayerOffset.y
}
ondragstart = (e) ->
layer = @listener
node = e.targetNode
stage = layer.getStage()
@scale = stage.getScale()
@width = stage.getWidth()
@height = stage.getHeight()
guidePosition = _nodeTracker(layer, node)
@vert = new kin.Line
stroke: 'red'
tension: 1
points: [guidePosition.x, 0, guidePosition.x, @height]
@hori = new kin.Line
stroke: 'red'
tension: 1
points: [0, guidePosition.y, @width, guidePosition.y]
@text = new kin.Text
listening: false
fontSize: 12
fontFamily: 'Calibri'
fill: 'green'
@text.setAttrs
text: "[ #{guidePosition.x}(#{node.x()}), #{guidePosition.y}(#{node.y()}) ]"
x: if Math.max(guidePosition.x, 0) > (@text.width() + 10) then guidePosition.x - (@text.width() + 10) else Math.max(guidePosition.x + 10, 10)
y: if Math.max(guidePosition.y, 0) > (@text.height() + 10) then guidePosition.y - (@text.height() + 10) else Math.max(guidePosition.y + 10, 10)
layer.add(@vert)
layer.add(@hori)
layer.add(@text)
layer.batchDraw()
ondragmove = (e) ->
controller = @context
layer = @listener
node = e.targetNode
nodePositionCurrent = node.position()
node.position
x: Math.round(nodePositionCurrent.x / 10) * 10
y: Math.round(nodePositionCurrent.y / 10) * 10
guidePosition = _nodeTracker(layer, node)
@vert.setAttrs({points:[guidePosition.x, 0, guidePosition.x, @height]})
@hori.setAttrs({points:[0, guidePosition.y, @width, guidePosition.y]})
@text.setAttrs
text: "[ #{guidePosition.x}(#{node.x()}), #{guidePosition.y}(#{node.y()}) ]"
x: if Math.max(guidePosition.x, 0) > (@text.width() + 10) then guidePosition.x - (@text.width() + 10) else Math.max(guidePosition.x + 10, 10)
y: if Math.max(guidePosition.y, 0) > (@text.height() + 10) then guidePosition.y - (@text.height() + 10) else Math.max(guidePosition.y + 10, 10)
scale = node.getStage().scale()
autoMovingLeft = (node.getStage().width() + layer.offset().x) / scale.x * 1 / 5
autoMovingRight = (node.getStage().width() + layer.offset().x) / scale.x * 4 / 5
autoMovingTop = (node.getStage().height() + layer.offset().y) / scale.y * 1 / 5
autoMovingBottom = (node.getStage().height() + layer.offset().y) / scale.y * 4 / 5
console.log autoMovingLeft, autoMovingRight, autoMovingTop, autoMovingBottom
if guidePosition.x < autoMovingLeft or guidePosition.x > autoMovingRight or guidePosition.y < autoMovingTop or guidePosition.y > autoMovingBottom
nodeLayer = node.getLayer()
oldOffset = nodeLayer.offset()
x = if guidePosition.x <= autoMovingLeft
Math.max(oldOffset.x - 10, -20)
else if guidePosition.x >= autoMovingRight
oldOffset.x + 10
else oldOffset.x
y = if guidePosition.y <= autoMovingTop
Math.max(oldOffset.y - 10, -20)
else if guidePosition.y >= autoMovingBottom
oldOffset.y + 10
else oldOffset.y
console.log guidePosition, x, y
# TODO remove implicit dependency to content-edit-layer
if oldOffset.x != x or oldOffset.y != y
controller.offset
x: x
y: y
layer.batchDraw()
ondragend = (e) ->
layer = @listener
@vert.remove()
@hori.remove()
@text.remove()
layer.batchDraw()
onadded = (container, component, index, e) ->
onremoved = (container, component, e) ->
model_event_map =
'(root)' :
'(all)' :
'change' : onchange
'(self)' :
'(self)' :
'added' : onadded
'removed' : onremoved
view_event_map =
'(root)' :
dragstart : ondragstart
dragmove : ondragmove
dragend : ondragend
{
type: 'guide-layer'
name: 'guide-layer'
containable: true
container_type: 'layer'
description: 'Editing Guide Specification'
defaults: {
draggable: false
}
model_event_map: model_event_map
view_event_map: view_event_map
view_factory_fn: view_factory
toolbox_image: 'images/toolbox_guide_layer.png'
}
| true | # ==========================================
# Copyright 2014 PI:NAME:<NAME>END_PI, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'KineticJS'
], (
kin
) ->
"use strict"
view_factory = (attributes) ->
new kin.Layer(attributes)
onchange = (component, before, after, e) ->
controller = this
model = e.listener
view = controller.getAttachedViews(model)[0]
self = model._track = model._track || {}
self.changes = (self.changes || 0) + 1
if not self.text
self.text = new kin.Text
x: 10
y: 10
listening: false
fontSize: 12
fontFamily: 'Calibri'
fill: 'green'
view.add self.text
msg = "[ PropertyChange ] #{component.type} : #{component.get('id')}\n[ Before ] #{JSON.stringify(before)}\n[ After ] #{JSON.stringify(after)}"
self.text.setAttr 'text', msg
view.draw()
setTimeout ->
return if (--self.changes) > 0
tween = new Kinetic.Tween({
node: self.text
opacity: 0
duration: 1
easing: kin.Easings.EaseOut
})
tween.play();
setTimeout ->
if self.changes > 0
tween.reset()
tween.destroy()
return
tween.finish()
tween.destroy()
self.text.remove()
delete self.text
view.draw()
, 1000
, 5000
_nodeTracker = (guideLayer, node) ->
guideLayerOffset = guideLayer.offset()
nodeLayerOffset = node.getLayer().offset()
nodeAbsPosition = node.getAbsolutePosition()
scale = node.getStage().scale()
{
x: nodeAbsPosition.x / scale.x + guideLayerOffset.x
y: nodeAbsPosition.y / scale.y + guideLayerOffset.y
}
ondragstart = (e) ->
layer = @listener
node = e.targetNode
stage = layer.getStage()
@scale = stage.getScale()
@width = stage.getWidth()
@height = stage.getHeight()
guidePosition = _nodeTracker(layer, node)
@vert = new kin.Line
stroke: 'red'
tension: 1
points: [guidePosition.x, 0, guidePosition.x, @height]
@hori = new kin.Line
stroke: 'red'
tension: 1
points: [0, guidePosition.y, @width, guidePosition.y]
@text = new kin.Text
listening: false
fontSize: 12
fontFamily: 'Calibri'
fill: 'green'
@text.setAttrs
text: "[ #{guidePosition.x}(#{node.x()}), #{guidePosition.y}(#{node.y()}) ]"
x: if Math.max(guidePosition.x, 0) > (@text.width() + 10) then guidePosition.x - (@text.width() + 10) else Math.max(guidePosition.x + 10, 10)
y: if Math.max(guidePosition.y, 0) > (@text.height() + 10) then guidePosition.y - (@text.height() + 10) else Math.max(guidePosition.y + 10, 10)
layer.add(@vert)
layer.add(@hori)
layer.add(@text)
layer.batchDraw()
ondragmove = (e) ->
controller = @context
layer = @listener
node = e.targetNode
nodePositionCurrent = node.position()
node.position
x: Math.round(nodePositionCurrent.x / 10) * 10
y: Math.round(nodePositionCurrent.y / 10) * 10
guidePosition = _nodeTracker(layer, node)
@vert.setAttrs({points:[guidePosition.x, 0, guidePosition.x, @height]})
@hori.setAttrs({points:[0, guidePosition.y, @width, guidePosition.y]})
@text.setAttrs
text: "[ #{guidePosition.x}(#{node.x()}), #{guidePosition.y}(#{node.y()}) ]"
x: if Math.max(guidePosition.x, 0) > (@text.width() + 10) then guidePosition.x - (@text.width() + 10) else Math.max(guidePosition.x + 10, 10)
y: if Math.max(guidePosition.y, 0) > (@text.height() + 10) then guidePosition.y - (@text.height() + 10) else Math.max(guidePosition.y + 10, 10)
scale = node.getStage().scale()
autoMovingLeft = (node.getStage().width() + layer.offset().x) / scale.x * 1 / 5
autoMovingRight = (node.getStage().width() + layer.offset().x) / scale.x * 4 / 5
autoMovingTop = (node.getStage().height() + layer.offset().y) / scale.y * 1 / 5
autoMovingBottom = (node.getStage().height() + layer.offset().y) / scale.y * 4 / 5
console.log autoMovingLeft, autoMovingRight, autoMovingTop, autoMovingBottom
if guidePosition.x < autoMovingLeft or guidePosition.x > autoMovingRight or guidePosition.y < autoMovingTop or guidePosition.y > autoMovingBottom
nodeLayer = node.getLayer()
oldOffset = nodeLayer.offset()
x = if guidePosition.x <= autoMovingLeft
Math.max(oldOffset.x - 10, -20)
else if guidePosition.x >= autoMovingRight
oldOffset.x + 10
else oldOffset.x
y = if guidePosition.y <= autoMovingTop
Math.max(oldOffset.y - 10, -20)
else if guidePosition.y >= autoMovingBottom
oldOffset.y + 10
else oldOffset.y
console.log guidePosition, x, y
# TODO remove implicit dependency to content-edit-layer
if oldOffset.x != x or oldOffset.y != y
controller.offset
x: x
y: y
layer.batchDraw()
ondragend = (e) ->
layer = @listener
@vert.remove()
@hori.remove()
@text.remove()
layer.batchDraw()
onadded = (container, component, index, e) ->
onremoved = (container, component, e) ->
model_event_map =
'(root)' :
'(all)' :
'change' : onchange
'(self)' :
'(self)' :
'added' : onadded
'removed' : onremoved
view_event_map =
'(root)' :
dragstart : ondragstart
dragmove : ondragmove
dragend : ondragend
{
type: 'guide-layer'
name: 'guide-layer'
containable: true
container_type: 'layer'
description: 'Editing Guide Specification'
defaults: {
draggable: false
}
model_event_map: model_event_map
view_event_map: view_event_map
view_factory_fn: view_factory
toolbox_image: 'images/toolbox_guide_layer.png'
}
|
[
{
"context": "s) ->\n key = req.body.key\n token = randToken.generate 24\n challenge = pad(\"#{Math.floor 10000*Math.r",
"end": 454,
"score": 0.8459597229957581,
"start": 436,
"tag": "KEY",
"value": "randToken.generate"
},
{
"context": " req.body.key\n token = randToken.generate 24\n challenge = pad(\"#{Math.floor 10000*Math.rand",
"end": 457,
"score": 0.6923798322677612,
"start": 456,
"tag": "KEY",
"value": "4"
}
] | server/index.coffee | macaullyjames/flopbox | 0 | require "coffee-script"
express = require "express"
cors = require "cors"
bodyParser = require "body-parser"
randToken = require "rand-token"
fs = require "fs"
pad = require "pad-left"
auth = require "./auth"
{users, sessions} = require("./db") "flopbox"
api = express()
api.use cors()
api.use bodyParser.json()
api.use auth
api.put "/login", (req, res) ->
key = req.body.key
token = randToken.generate 24
challenge = pad("#{Math.floor 10000*Math.random()}", 4, 0)
users.get key
.then (row) -> sessions.add row.id, token, challenge
.then -> res.json token: token
.catch -> res.status(400).send()
api.put "/2fa", (req, res) ->
challenge = req.body.challenge
session = req.session
token = req.session.token
if challenge is session.challenge
sessions.validate(token)
res.status(200).send()
else
res.status(400).send()
api.get "/files", (req, res) ->
fs.readdir './shared/', (_, files) -> res.json files
api.listen 8081
| 130383 | require "coffee-script"
express = require "express"
cors = require "cors"
bodyParser = require "body-parser"
randToken = require "rand-token"
fs = require "fs"
pad = require "pad-left"
auth = require "./auth"
{users, sessions} = require("./db") "flopbox"
api = express()
api.use cors()
api.use bodyParser.json()
api.use auth
api.put "/login", (req, res) ->
key = req.body.key
token = <KEY> 2<KEY>
challenge = pad("#{Math.floor 10000*Math.random()}", 4, 0)
users.get key
.then (row) -> sessions.add row.id, token, challenge
.then -> res.json token: token
.catch -> res.status(400).send()
api.put "/2fa", (req, res) ->
challenge = req.body.challenge
session = req.session
token = req.session.token
if challenge is session.challenge
sessions.validate(token)
res.status(200).send()
else
res.status(400).send()
api.get "/files", (req, res) ->
fs.readdir './shared/', (_, files) -> res.json files
api.listen 8081
| true | require "coffee-script"
express = require "express"
cors = require "cors"
bodyParser = require "body-parser"
randToken = require "rand-token"
fs = require "fs"
pad = require "pad-left"
auth = require "./auth"
{users, sessions} = require("./db") "flopbox"
api = express()
api.use cors()
api.use bodyParser.json()
api.use auth
api.put "/login", (req, res) ->
key = req.body.key
token = PI:KEY:<KEY>END_PI 2PI:KEY:<KEY>END_PI
challenge = pad("#{Math.floor 10000*Math.random()}", 4, 0)
users.get key
.then (row) -> sessions.add row.id, token, challenge
.then -> res.json token: token
.catch -> res.status(400).send()
api.put "/2fa", (req, res) ->
challenge = req.body.challenge
session = req.session
token = req.session.token
if challenge is session.challenge
sessions.validate(token)
res.status(200).send()
else
res.status(400).send()
api.get "/files", (req, res) ->
fs.readdir './shared/', (_, files) -> res.json files
api.listen 8081
|
[
{
"context": "# Projector.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Projector c",
"end": 27,
"score": 0.9538125395774841,
"start": 21,
"tag": "NAME",
"value": "Tomasz"
},
{
"context": "# Projector.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Projector class display",
"end": 41,
"score": 0.9992351531982422,
"start": 29,
"tag": "NAME",
"value": "Tomek) Zemla"
},
{
"context": "# Projector.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Projector class displays the data visualizatio",
"end": 64,
"score": 0.9999306201934814,
"start": 44,
"tag": "EMAIL",
"value": "tomek@datacratic.com"
},
{
"context": "cMaterial(), THREE.LineStrip)\n\n @viewport.add(@view1) # top\n @viewport.add(@view2) # front\n ",
"end": 10449,
"score": 0.9607254862785339,
"start": 10443,
"tag": "USERNAME",
"value": "@view1"
},
{
"context": " @viewport.add(@view1) # top\n @viewport.add(@view2) # front\n @viewport.add(@view3) # side\n\n ",
"end": 10483,
"score": 0.8519337773323059,
"start": 10477,
"tag": "USERNAME",
"value": "@view2"
}
] | src/Projector.coffee | SachithDassanayaka/sachithdassanayaka.github.io | 0 | # Projector.coffee
# Tomasz (Tomek) Zemla
# tomek@datacratic.com
# Projector class displays the data visualization.
# Images are rendered in WebGL on HTML5 Canvas using Three.js library.
# TODO Extend selection to work in ORTHOGRAPHIC and PERSPECTIVE, not only DUAL mode.
Subject = require('./Subject.coffee')
Utility = require('./Utility.coffee')
Palette = require('./Palette.coffee')
Selector = require('./Selector.coffee')
class Projector extends Subject
# E V E N T S
@EVENT_DATA_LOADED : "EVENT_DATA_LOADED"
@EVENT_POINTS_SELECTED : "EVENT_POINTS_SELECTED"
@EVENT_CLUSTER_SELECTED : "EVENT_CLUSTER_SELECTED"
# C O N S T A N T S
# three view/display modes
@VIEW : { NONE: -1, PERSPECTIVE: 0, ORTHOGRAPHIC: 1, DUAL: 2 }
# spin clock or counter clockwise
@SPIN : { LEFT: -1, NONE: 0, RIGHT: +1 }
@SPIN_STEP : Utility.DEGREE / 10 # 0.1 degree - default step
# M E M B E R S
# these are pseudo constants which are redefined when browser resizes
SCREEN_WIDTH : window.innerWidth
SCREEN_HEIGHT : window.innerHeight
mode : Projector.VIEW.DUAL # starting default
storage : null # reference to the data storage
colors : null # Array<THREE.Color> generated color values for visualization
scene : null # THREE.Scene
# perspective (3D) and orthographic (2D) projection cameras
cameraPerspective : null # THREE.PerspectiveCamera
cameraOrthographic : null # THREE.OrthographicCamera
renderer : null # THREE.WebGLRenderer
# mouse tracking variables
mouse : new THREE.Vector3() # current mouse coordinates when selecting
mouseStart : new THREE.Vector3() # mouse down coordinates when selecting
mouseEnd : new THREE.Vector3() # mouse up coordinates when selecting
dragging : false # true when rubber banding...
selector : null # Selector
# visual helpers for data display
box : null # THREE.Mesh - data cage
viewport : null # parent of selectable view rectangles
direction : Utility.DIRECTION.TOP # default 2D view is from top
view1 : null # THREE.Line - 2D orthographic view box - top
view2 : null # THREE.Line - 2D orthographic view box - front
view3 : null # THREE.Line - 2D orthographic view box - side
# visual representations of loaded data
points : null # Array<THREE.Geometry>
particles : null # Array<THREE.ParticleSystem>
clusters : null # array of particle systems one per cluster
selected : -1 # currently selected cluster
controls : null # THREE.TrackballControls
timeStamp : 0
# C O N S T R U C T O R
# Create projector.
# Constructor creates all initial setup to make projector ready for data.
constructor: ->
super()
@addUIListeners() # listen for UI events
@scene = new THREE.Scene() # 3D world
@createPerspectiveCamera() # left side (dual mode): 3D perspective camera
@createOrthographicCamera() # right side (dual mode): 2D ortographic projection camera
@createControls() # trackball simulation controls
@createBox() # bounding box for the data
@cameraPerspective.lookAt( @box.position )
@cameraOrthographic.lookAt( @box.position )
@createViews()
@updateView(true)
@selector = new Selector(@box) # 3D rubber band selector
@createRenderingEngine() # set up WebGL renderer on canvas
@onWindowResize(null)
@animate() # start rendering loop!
# E V E N T H A N D L E R S
# Make updates related to window size changes.
# Also used when view configuration is switched.
onWindowResize : (event) =>
@SCREEN_WIDTH = window.innerWidth
@SCREEN_HEIGHT = window.innerHeight
console.log "Screen #{@SCREEN_WIDTH} x #{@SCREEN_HEIGHT}"
if @renderer?
@renderer.setSize( @SCREEN_WIDTH, @SCREEN_HEIGHT )
switch @mode
when Projector.VIEW.PERSPECTIVE
@cameraPerspective.aspect = @SCREEN_WIDTH / @SCREEN_HEIGHT
@cameraPerspective.updateProjectionMatrix()
when Projector.VIEW.ORTHOGRAPHIC
@cameraOrthographic.left = - (@SCREEN_WIDTH / 8)
@cameraOrthographic.right = + (@SCREEN_WIDTH / 8)
@cameraOrthographic.top = + (@SCREEN_HEIGHT / 8)
@cameraOrthographic.bottom = - (@SCREEN_HEIGHT / 8)
@cameraOrthographic.updateProjectionMatrix()
when Projector.VIEW.DUAL
# left side
@cameraPerspective.aspect = 0.5 * @SCREEN_WIDTH / @SCREEN_HEIGHT
@cameraPerspective.updateProjectionMatrix()
# right side
@cameraOrthographic.left = - (@SCREEN_WIDTH / 10)
@cameraOrthographic.right = + (@SCREEN_WIDTH / 10)
@cameraOrthographic.top = + (@SCREEN_HEIGHT / 5)
@cameraOrthographic.bottom = - (@SCREEN_HEIGHT / 5)
@cameraOrthographic.updateProjectionMatrix()
@controls.handleResize()
onMouseDown : (event) =>
if @mode is Projector.VIEW.DUAL
event.preventDefault()
if event.shiftKey
@dragging = true
@updateMouse3D()
@mouseStart.copy(@mouse)
@selector.start(@mouseStart.clone())
event.stopPropagation()
onMouseMove : (event) =>
if @mode is Projector.VIEW.DUAL
event.preventDefault()
if @dragging
@updateMouse3D()
@selector.update(@mouse)
event.stopPropagation()
onMouseUp : (event) =>
if @mode is Projector.VIEW.DUAL
event.preventDefault()
if @dragging
@dragging = false
@updateMouse3D()
@mouseEnd.copy(@mouse)
@selector.end(@mouseEnd.clone())
@updateSelection()
event.stopPropagation()
# Toggle next cluster during the animated walk through.
onTimer : (index) =>
@toggleClusterVisibility(index)
if ++index is @storage.getClusters() then index = 0
if @animateOn then @startTimer(index)
# M E T H O D S
# Set the current mode.
setMode : (@mode) =>
@onWindowResize(null)
# Use given color set for visualization.
setColors : (@colors) =>
# Toggle box visibility. Return current state.
toggleBox : => return (@box.visible = not @box.visible)
# Toggle viewport visibility. Return current state.
toggleViewport : => return @updateView(not @viewport.visible)
toggleSelector : =>
state = @selector.toggle()
@updateSelection()
return state
# Get the base 64 encoded image of the current state of the projector.
getImage : =>
return document.getElementById("renderer").toDataURL("image/png")
# Hook up to browser and mouse events.
addUIListeners : =>
window.addEventListener('resize', @onWindowResize, false)
# container will hold WebGL canvas
$('#container').mousedown(@onMouseDown)
$('#container').mousemove(@onMouseMove)
$('#container').mouseup(@onMouseUp)
# Proper 3D camera.
createPerspectiveCamera : =>
# NOTE Cameras aspect ratio setup matches the half screen viewports for initial dual mode
@cameraPerspective = new THREE.PerspectiveCamera( 50, 0.5 * @SCREEN_WIDTH / @SCREEN_HEIGHT, 150, 1000 )
@cameraPerspective.position.set(0, 0, 550)
@scene.add( @cameraPerspective )
# Flat, 2D, no perspective camera.
createOrthographicCamera : =>
@cameraOrthographic = new THREE.OrthographicCamera( - (@SCREEN_WIDTH / 8),
+ (@SCREEN_WIDTH / 8),
+ (@SCREEN_HEIGHT / 4),
- (@SCREEN_HEIGHT / 4),
250, 750 )
@cameraOrthographic.position.set(0, 500, 0)
@scene.add( @cameraOrthographic )
# Initialize simulated trackball navigation controls
createControls : =>
@controls = new THREE.TrackballControls( @cameraPerspective )
@controls.rotateSpeed = 1.0
@controls.zoomSpeed = 1.0
@controls.panSpeed = 0.8
@controls.noZoom = false
@controls.noPan = false
@controls.staticMoving = true
@controls.dynamicDampingFactor = 0.3
@controls.addEventListener('change', @render)
# Bounding box where the data is displayed.
createBox : =>
@box = new THREE.Mesh(new THREE.CubeGeometry(200, 200, 200),
new THREE.MeshBasicMaterial({ color: 0x404040, wireframe: true }))
@scene.add(@box)
# Create a set of highlights that indicate ortographic projection in perspective view.
# Each rectangle simply indicates where 2D view is within the 3D space.
createViews : =>
@viewport = new THREE.Object3D()
# top view
geometry1 = new THREE.Geometry()
geometry1.vertices.push( new THREE.Vector3( +100, +101, +100 ) )
geometry1.vertices.push( new THREE.Vector3( -100, +101, +100 ) )
geometry1.vertices.push( new THREE.Vector3( -100, +101, -100 ) )
geometry1.vertices.push( new THREE.Vector3( +100, +101, -100 ) )
geometry1.vertices.push( new THREE.Vector3( +100, +101, +100 ) )
@view1 = new THREE.Line(geometry1, new THREE.LineBasicMaterial(), THREE.LineStrip)
# front view
geometry2 = new THREE.Geometry()
geometry2.vertices.push( new THREE.Vector3( +100, +100, +101 ) )
geometry2.vertices.push( new THREE.Vector3( -100, +100, +101 ) )
geometry2.vertices.push( new THREE.Vector3( -100, -100, +101 ) )
geometry2.vertices.push( new THREE.Vector3( +100, -100, +101 ) )
geometry2.vertices.push( new THREE.Vector3( +100, +100, +101 ) )
@view2 = new THREE.Line(geometry2, new THREE.LineBasicMaterial(), THREE.LineStrip)
# side view
geometry3 = new THREE.Geometry()
geometry3.vertices.push( new THREE.Vector3( +101, +100, +100 ) )
geometry3.vertices.push( new THREE.Vector3( +101, -100, +100 ) )
geometry3.vertices.push( new THREE.Vector3( +101, -100, -100 ) )
geometry3.vertices.push( new THREE.Vector3( +101, +100, -100 ) )
geometry3.vertices.push( new THREE.Vector3( +101, +100, +100 ) )
@view3 = new THREE.Line(geometry3, new THREE.LineBasicMaterial(), THREE.LineStrip)
@viewport.add(@view1) # top
@viewport.add(@view2) # front
@viewport.add(@view3) # side
@box.add(@viewport)
createRenderingEngine : =>
# basically canvas in WebGL mode
@renderer = new THREE.WebGLRenderer( { antialias: true, preserveDrawingBuffer: true } )
@renderer.setSize( @SCREEN_WIDTH, @SCREEN_HEIGHT )
@renderer.setClearColor( Palette.BACKGROUND.getHex(), 1 )
@renderer.domElement.style.position = "relative"
@renderer.domElement.id = "renderer"
@renderer.autoClear = false
# container is the display area placeholder in HTML
container = $('#container').get(0)
container.appendChild( @renderer.domElement )
# Load JSON data to visualize.
load : (@storage) =>
data = @storage.getData() # JSON
clusters = @storage.getClusters() # number of clusters
# create point clouds first for each cluster
@points = new Array()
for c in [0...clusters]
@points[c] = new THREE.Geometry()
@points[c].colorsNeedUpdate = true
# process JSON data
$.each(data.points, @processPoint)
# create particle systems for each cluster (with point clouds within)
@particles = new Array()
for p in [0...clusters]
material = new THREE.ParticleBasicMaterial( { size: 1.0, sizeAttenuation: false, vertexColors: true } )
@particles[p] = new THREE.ParticleSystem( @points[p], material )
@box.add( @particles[p] ) # put them in the data cage
@notify(Projector.EVENT_DATA_LOADED)
# Called for each data point loaded in JSON file.
processPoint : (nodeName, nodeData) =>
# cluster index
index = parseInt(nodeData.cid)
vertex = new THREE.Vector3()
vertex.x = parseFloat( nodeData.x )
vertex.y = parseFloat( nodeData.y )
vertex.z = parseFloat( nodeData.z )
@points[index].vertices.push( vertex )
# NOTE Although initially all points in the same cluster have the same color
# they do take individual colors during the selection interactions therefore
# each point needs its own individual color object instead of shared one...
color = @colors[index].clone()
@points[index].colors.push( color )
# Rendering loop - animate calls itself forever.
animate : =>
requestAnimationFrame( @animate )
@controls.update()
@render()
# Rendering done on each frame.
# Rendering configuration depends on the current view mode.
render : =>
@renderer.clear()
switch @mode
# one viewport: perspective camera only
when Projector.VIEW.PERSPECTIVE
if @spin isnt Projector.SPIN.NONE then @spinCamera()
@cameraPerspective.lookAt( @box.position )
# RENDERING
@renderer.setViewport( 0, 0, @SCREEN_WIDTH, @SCREEN_HEIGHT )
@renderer.render( @scene, @cameraPerspective )
# one viewport: orthographic camera only
when Projector.VIEW.ORTHOGRAPHIC
# RENDERING
@cameraOrthographic.rotation.z = 0
@renderer.setViewport( 0, 0, @SCREEN_WIDTH, @SCREEN_HEIGHT )
@renderer.render( @scene, @cameraOrthographic )
# dual perspective and orthographic cameras view
when Projector.VIEW.DUAL
# synchronize camera with rotation
if @spin isnt Projector.SPIN.NONE then @spinCamera()
@cameraPerspective.lookAt( @box.position )
# RENDERING
# left side viewport: perspective camera
@renderer.setViewport( 0, 0, @SCREEN_WIDTH/2, @SCREEN_HEIGHT )
@renderer.render( @scene, @cameraPerspective )
# right side viewport: orthographic camera
@cameraOrthographic.rotation.z = 0
@renderer.setViewport( @SCREEN_WIDTH/2, 0, @SCREEN_WIDTH/2, @SCREEN_HEIGHT )
@renderer.render( @scene, @cameraOrthographic )
updateSelection : =>
# algorithm:
# loop through all clusters
# if cluster is visible then process it
# for each point check if it's inside selection
# if inside (and selector is active) set color to highlight
# else set color to original cluster color
counter = 0
for i in [0...@storage.getClusters()]
if @particles[i].visible
cloud = @points[i]
all = cloud.vertices.length
for j in [0...all]
vertex = cloud.vertices[j]
color = cloud.colors[j]
if @selector.isActive() and @selector.contains(vertex, Utility.DIRECTION.ALL)
color.setHex(Palette.HIGHLIGHT.getHex())
counter++
# Utility.printVector3(vertex)
else
color.setHex(@colors[i].getHex())
cloud.colorsNeedUpdate = true;
@notify(Projector.EVENT_POINTS_SELECTED, { points : counter })
updateMouse3D : =>
# NOTE This works only in DUAL mode
# TODO Extend this to other modes
ratio = 100 / 250 # ?
switch @direction
when Utility.DIRECTION.TOP
@mouse.x = (event.pageX - (3 * @SCREEN_WIDTH / 4)) * ratio
@mouse.y = 100
@mouse.z = (event.pageY - (@SCREEN_HEIGHT / 2)) * ratio
when Utility.DIRECTION.FRONT
@mouse.x = (event.pageX - (3 * @SCREEN_WIDTH / 4)) * ratio
@mouse.y = - (event.pageY - (@SCREEN_HEIGHT / 2)) * ratio
@mouse.z = 100
when Utility.DIRECTION.SIDE
@mouse.x = 100
@mouse.y = - (event.pageY - (@SCREEN_HEIGHT / 2)) * ratio
@mouse.z = - (event.pageX - (3 * @SCREEN_WIDTH / 4)) * ratio
# Returns 3D camera to its starting orientation and optionally position.
# Position is only reset if location argument is true.
resetCamera : (location) =>
if location then TweenLite.to( @cameraPerspective.position, 1, {x:0, y:0, z:550} )
TweenLite.to( @cameraPerspective.rotation, 1, {x:0, y:0, z:0} )
TweenLite.to( @cameraPerspective.up, 1, {x:0, y:1, z:0} )
# Set the visibility of orthographic view (top, front, side) indicator.
updateView : (visible) =>
@viewport.visible = visible
# NOTE Changing visibility of the viewport alone does not work as the change
# of visibility of the parent is an ongoing bug/issue of the ThreeJS library...
# ...so toggle all three separately
if @viewport.visible
switch @direction
when Utility.DIRECTION.TOP
@setViewsVisible(true, false, false)
@cameraOrthographic.position.set(0, 500, 0)
when Utility.DIRECTION.FRONT
@setViewsVisible(false, true, false)
@cameraOrthographic.position.set(0, 0, 500)
when Utility.DIRECTION.SIDE
@setViewsVisible(false, false, true)
@cameraOrthographic.position.set(500, 0, 0)
@cameraOrthographic.lookAt(@box.position)
else
@setViewsVisible(false, false, false)
return @viewport.visible
# Set visibility of view indicators.
setViewsVisible : (top, front, side) =>
@view1.visible = top
@view2.visible = front
@view3.visible = side
changeView : (@direction) =>
@updateView(@viewport.visible)
@selector.setDirection(@direction)
toggleAnimation : =>
@animateOn = not @animateOn
if @animateOn
@setAllClustersVisible(false)
@startTimer(0)
else
@setAllClustersVisible(true)
return @animateOn
setSpin : (@spin) =>
switch @spin
when Projector.SPIN.LEFT
@resetCamera(false)
when Projector.SPIN.NONE
@timeStamp = 0
when Projector.SPIN.RIGHT
@resetCamera(false)
# Spin camera in a circle around the center.
spinCamera : =>
STEP = @getSpinStep()
cx = @cameraPerspective.position.x
cy = -1 * @cameraPerspective.position.z
radians = Math.atan2(cy, cx)
radius = Math.sqrt(cx * cx + cy * cy)
switch @spin
when Projector.SPIN.LEFT
radians += STEP
if radians > Math.PI then radians = radians - (2 * Math.PI)
when Projector.SPIN.RIGHT
radians -= STEP
if radians < -Math.PI then radians = (2 * Math.PI) + radians
x = radius * Math.cos(radians)
y = radius * Math.sin(radians)
@cameraPerspective.position.x = x
@cameraPerspective.position.z = -1 * y
# Adjust the rotation step depending on time elapsed between the frames.
getSpinStep : =>
step = Projector.SPIN_STEP # default
if @timeStamp isnt 0
date = new Date()
timeNow = date.getTime()
delta = timeNow - @timeStamp
@timeStamp = timeNow
step = delta * step / 10
return step
# Toggle visibility of the cluster given by its index.
toggleClusterVisibility : (index) =>
@particles[index].visible = not @particles[index].visible
setAllClustersVisible : (visible) =>
p.visible = visible for p in @particles
# Select or unselect cluster of given index.
toggleClusterSelection : (index) =>
# clear old selected
if @selected > -1
# restore color coding on previous selection
hexColor = @colors[@selected].getHex()
@updatePoints(@selected, hexColor)
if @selected is index
# unselecting
@selected = -1
else
# selecting
@selected = index
# highlight new selected
@updatePoints(@selected, Palette.HIGHLIGHT.getHex())
if @selected > -1
@notify(Projector.EVENT_CLUSTER_SELECTED, { id : index })
else
@notify(Projector.EVENT_CLUSTER_SELECTED, { id : -1 })
# Color code given points cloud (cluster).
updatePoints : (index, color) =>
cloud = @points[index]
all = cloud.vertices.length
for i in [0...all]
cloud.colors[i].setHex(color)
@points[index].colorsNeedUpdate = true
startTimer : (index) =>
@toggleClusterVisibility(index)
window.setTimeout(@onTimer, 2 * Utility.SECOND, index)
# Count visible clusters.
clustersVisible : =>
result = 0
result++ for cloud in @particles when cloud.visible
return result
module.exports = Projector | 93223 | # Projector.coffee
# <NAME> (<NAME>
# <EMAIL>
# Projector class displays the data visualization.
# Images are rendered in WebGL on HTML5 Canvas using Three.js library.
# TODO Extend selection to work in ORTHOGRAPHIC and PERSPECTIVE, not only DUAL mode.
Subject = require('./Subject.coffee')
Utility = require('./Utility.coffee')
Palette = require('./Palette.coffee')
Selector = require('./Selector.coffee')
class Projector extends Subject
# E V E N T S
@EVENT_DATA_LOADED : "EVENT_DATA_LOADED"
@EVENT_POINTS_SELECTED : "EVENT_POINTS_SELECTED"
@EVENT_CLUSTER_SELECTED : "EVENT_CLUSTER_SELECTED"
# C O N S T A N T S
# three view/display modes
@VIEW : { NONE: -1, PERSPECTIVE: 0, ORTHOGRAPHIC: 1, DUAL: 2 }
# spin clock or counter clockwise
@SPIN : { LEFT: -1, NONE: 0, RIGHT: +1 }
@SPIN_STEP : Utility.DEGREE / 10 # 0.1 degree - default step
# M E M B E R S
# these are pseudo constants which are redefined when browser resizes
SCREEN_WIDTH : window.innerWidth
SCREEN_HEIGHT : window.innerHeight
mode : Projector.VIEW.DUAL # starting default
storage : null # reference to the data storage
colors : null # Array<THREE.Color> generated color values for visualization
scene : null # THREE.Scene
# perspective (3D) and orthographic (2D) projection cameras
cameraPerspective : null # THREE.PerspectiveCamera
cameraOrthographic : null # THREE.OrthographicCamera
renderer : null # THREE.WebGLRenderer
# mouse tracking variables
mouse : new THREE.Vector3() # current mouse coordinates when selecting
mouseStart : new THREE.Vector3() # mouse down coordinates when selecting
mouseEnd : new THREE.Vector3() # mouse up coordinates when selecting
dragging : false # true when rubber banding...
selector : null # Selector
# visual helpers for data display
box : null # THREE.Mesh - data cage
viewport : null # parent of selectable view rectangles
direction : Utility.DIRECTION.TOP # default 2D view is from top
view1 : null # THREE.Line - 2D orthographic view box - top
view2 : null # THREE.Line - 2D orthographic view box - front
view3 : null # THREE.Line - 2D orthographic view box - side
# visual representations of loaded data
points : null # Array<THREE.Geometry>
particles : null # Array<THREE.ParticleSystem>
clusters : null # array of particle systems one per cluster
selected : -1 # currently selected cluster
controls : null # THREE.TrackballControls
timeStamp : 0
# C O N S T R U C T O R
# Create projector.
# Constructor creates all initial setup to make projector ready for data.
constructor: ->
super()
@addUIListeners() # listen for UI events
@scene = new THREE.Scene() # 3D world
@createPerspectiveCamera() # left side (dual mode): 3D perspective camera
@createOrthographicCamera() # right side (dual mode): 2D ortographic projection camera
@createControls() # trackball simulation controls
@createBox() # bounding box for the data
@cameraPerspective.lookAt( @box.position )
@cameraOrthographic.lookAt( @box.position )
@createViews()
@updateView(true)
@selector = new Selector(@box) # 3D rubber band selector
@createRenderingEngine() # set up WebGL renderer on canvas
@onWindowResize(null)
@animate() # start rendering loop!
# E V E N T H A N D L E R S
# Make updates related to window size changes.
# Also used when view configuration is switched.
onWindowResize : (event) =>
@SCREEN_WIDTH = window.innerWidth
@SCREEN_HEIGHT = window.innerHeight
console.log "Screen #{@SCREEN_WIDTH} x #{@SCREEN_HEIGHT}"
if @renderer?
@renderer.setSize( @SCREEN_WIDTH, @SCREEN_HEIGHT )
switch @mode
when Projector.VIEW.PERSPECTIVE
@cameraPerspective.aspect = @SCREEN_WIDTH / @SCREEN_HEIGHT
@cameraPerspective.updateProjectionMatrix()
when Projector.VIEW.ORTHOGRAPHIC
@cameraOrthographic.left = - (@SCREEN_WIDTH / 8)
@cameraOrthographic.right = + (@SCREEN_WIDTH / 8)
@cameraOrthographic.top = + (@SCREEN_HEIGHT / 8)
@cameraOrthographic.bottom = - (@SCREEN_HEIGHT / 8)
@cameraOrthographic.updateProjectionMatrix()
when Projector.VIEW.DUAL
# left side
@cameraPerspective.aspect = 0.5 * @SCREEN_WIDTH / @SCREEN_HEIGHT
@cameraPerspective.updateProjectionMatrix()
# right side
@cameraOrthographic.left = - (@SCREEN_WIDTH / 10)
@cameraOrthographic.right = + (@SCREEN_WIDTH / 10)
@cameraOrthographic.top = + (@SCREEN_HEIGHT / 5)
@cameraOrthographic.bottom = - (@SCREEN_HEIGHT / 5)
@cameraOrthographic.updateProjectionMatrix()
@controls.handleResize()
onMouseDown : (event) =>
if @mode is Projector.VIEW.DUAL
event.preventDefault()
if event.shiftKey
@dragging = true
@updateMouse3D()
@mouseStart.copy(@mouse)
@selector.start(@mouseStart.clone())
event.stopPropagation()
onMouseMove : (event) =>
if @mode is Projector.VIEW.DUAL
event.preventDefault()
if @dragging
@updateMouse3D()
@selector.update(@mouse)
event.stopPropagation()
onMouseUp : (event) =>
if @mode is Projector.VIEW.DUAL
event.preventDefault()
if @dragging
@dragging = false
@updateMouse3D()
@mouseEnd.copy(@mouse)
@selector.end(@mouseEnd.clone())
@updateSelection()
event.stopPropagation()
# Toggle next cluster during the animated walk through.
onTimer : (index) =>
@toggleClusterVisibility(index)
if ++index is @storage.getClusters() then index = 0
if @animateOn then @startTimer(index)
# M E T H O D S
# Set the current mode.
setMode : (@mode) =>
@onWindowResize(null)
# Use given color set for visualization.
setColors : (@colors) =>
# Toggle box visibility. Return current state.
toggleBox : => return (@box.visible = not @box.visible)
# Toggle viewport visibility. Return current state.
toggleViewport : => return @updateView(not @viewport.visible)
toggleSelector : =>
state = @selector.toggle()
@updateSelection()
return state
# Get the base 64 encoded image of the current state of the projector.
getImage : =>
return document.getElementById("renderer").toDataURL("image/png")
# Hook up to browser and mouse events.
addUIListeners : =>
window.addEventListener('resize', @onWindowResize, false)
# container will hold WebGL canvas
$('#container').mousedown(@onMouseDown)
$('#container').mousemove(@onMouseMove)
$('#container').mouseup(@onMouseUp)
# Proper 3D camera.
createPerspectiveCamera : =>
# NOTE Cameras aspect ratio setup matches the half screen viewports for initial dual mode
@cameraPerspective = new THREE.PerspectiveCamera( 50, 0.5 * @SCREEN_WIDTH / @SCREEN_HEIGHT, 150, 1000 )
@cameraPerspective.position.set(0, 0, 550)
@scene.add( @cameraPerspective )
# Flat, 2D, no perspective camera.
createOrthographicCamera : =>
@cameraOrthographic = new THREE.OrthographicCamera( - (@SCREEN_WIDTH / 8),
+ (@SCREEN_WIDTH / 8),
+ (@SCREEN_HEIGHT / 4),
- (@SCREEN_HEIGHT / 4),
250, 750 )
@cameraOrthographic.position.set(0, 500, 0)
@scene.add( @cameraOrthographic )
# Initialize simulated trackball navigation controls
createControls : =>
@controls = new THREE.TrackballControls( @cameraPerspective )
@controls.rotateSpeed = 1.0
@controls.zoomSpeed = 1.0
@controls.panSpeed = 0.8
@controls.noZoom = false
@controls.noPan = false
@controls.staticMoving = true
@controls.dynamicDampingFactor = 0.3
@controls.addEventListener('change', @render)
# Bounding box where the data is displayed.
createBox : =>
@box = new THREE.Mesh(new THREE.CubeGeometry(200, 200, 200),
new THREE.MeshBasicMaterial({ color: 0x404040, wireframe: true }))
@scene.add(@box)
# Create a set of highlights that indicate ortographic projection in perspective view.
# Each rectangle simply indicates where 2D view is within the 3D space.
createViews : =>
@viewport = new THREE.Object3D()
# top view
geometry1 = new THREE.Geometry()
geometry1.vertices.push( new THREE.Vector3( +100, +101, +100 ) )
geometry1.vertices.push( new THREE.Vector3( -100, +101, +100 ) )
geometry1.vertices.push( new THREE.Vector3( -100, +101, -100 ) )
geometry1.vertices.push( new THREE.Vector3( +100, +101, -100 ) )
geometry1.vertices.push( new THREE.Vector3( +100, +101, +100 ) )
@view1 = new THREE.Line(geometry1, new THREE.LineBasicMaterial(), THREE.LineStrip)
# front view
geometry2 = new THREE.Geometry()
geometry2.vertices.push( new THREE.Vector3( +100, +100, +101 ) )
geometry2.vertices.push( new THREE.Vector3( -100, +100, +101 ) )
geometry2.vertices.push( new THREE.Vector3( -100, -100, +101 ) )
geometry2.vertices.push( new THREE.Vector3( +100, -100, +101 ) )
geometry2.vertices.push( new THREE.Vector3( +100, +100, +101 ) )
@view2 = new THREE.Line(geometry2, new THREE.LineBasicMaterial(), THREE.LineStrip)
# side view
geometry3 = new THREE.Geometry()
geometry3.vertices.push( new THREE.Vector3( +101, +100, +100 ) )
geometry3.vertices.push( new THREE.Vector3( +101, -100, +100 ) )
geometry3.vertices.push( new THREE.Vector3( +101, -100, -100 ) )
geometry3.vertices.push( new THREE.Vector3( +101, +100, -100 ) )
geometry3.vertices.push( new THREE.Vector3( +101, +100, +100 ) )
@view3 = new THREE.Line(geometry3, new THREE.LineBasicMaterial(), THREE.LineStrip)
@viewport.add(@view1) # top
@viewport.add(@view2) # front
@viewport.add(@view3) # side
@box.add(@viewport)
createRenderingEngine : =>
# basically canvas in WebGL mode
@renderer = new THREE.WebGLRenderer( { antialias: true, preserveDrawingBuffer: true } )
@renderer.setSize( @SCREEN_WIDTH, @SCREEN_HEIGHT )
@renderer.setClearColor( Palette.BACKGROUND.getHex(), 1 )
@renderer.domElement.style.position = "relative"
@renderer.domElement.id = "renderer"
@renderer.autoClear = false
# container is the display area placeholder in HTML
container = $('#container').get(0)
container.appendChild( @renderer.domElement )
# Load JSON data to visualize.
load : (@storage) =>
data = @storage.getData() # JSON
clusters = @storage.getClusters() # number of clusters
# create point clouds first for each cluster
@points = new Array()
for c in [0...clusters]
@points[c] = new THREE.Geometry()
@points[c].colorsNeedUpdate = true
# process JSON data
$.each(data.points, @processPoint)
# create particle systems for each cluster (with point clouds within)
@particles = new Array()
for p in [0...clusters]
material = new THREE.ParticleBasicMaterial( { size: 1.0, sizeAttenuation: false, vertexColors: true } )
@particles[p] = new THREE.ParticleSystem( @points[p], material )
@box.add( @particles[p] ) # put them in the data cage
@notify(Projector.EVENT_DATA_LOADED)
# Called for each data point loaded in JSON file.
processPoint : (nodeName, nodeData) =>
# cluster index
index = parseInt(nodeData.cid)
vertex = new THREE.Vector3()
vertex.x = parseFloat( nodeData.x )
vertex.y = parseFloat( nodeData.y )
vertex.z = parseFloat( nodeData.z )
@points[index].vertices.push( vertex )
# NOTE Although initially all points in the same cluster have the same color
# they do take individual colors during the selection interactions therefore
# each point needs its own individual color object instead of shared one...
color = @colors[index].clone()
@points[index].colors.push( color )
# Rendering loop - animate calls itself forever.
animate : =>
requestAnimationFrame( @animate )
@controls.update()
@render()
# Rendering done on each frame.
# Rendering configuration depends on the current view mode.
render : =>
@renderer.clear()
switch @mode
# one viewport: perspective camera only
when Projector.VIEW.PERSPECTIVE
if @spin isnt Projector.SPIN.NONE then @spinCamera()
@cameraPerspective.lookAt( @box.position )
# RENDERING
@renderer.setViewport( 0, 0, @SCREEN_WIDTH, @SCREEN_HEIGHT )
@renderer.render( @scene, @cameraPerspective )
# one viewport: orthographic camera only
when Projector.VIEW.ORTHOGRAPHIC
# RENDERING
@cameraOrthographic.rotation.z = 0
@renderer.setViewport( 0, 0, @SCREEN_WIDTH, @SCREEN_HEIGHT )
@renderer.render( @scene, @cameraOrthographic )
# dual perspective and orthographic cameras view
when Projector.VIEW.DUAL
# synchronize camera with rotation
if @spin isnt Projector.SPIN.NONE then @spinCamera()
@cameraPerspective.lookAt( @box.position )
# RENDERING
# left side viewport: perspective camera
@renderer.setViewport( 0, 0, @SCREEN_WIDTH/2, @SCREEN_HEIGHT )
@renderer.render( @scene, @cameraPerspective )
# right side viewport: orthographic camera
@cameraOrthographic.rotation.z = 0
@renderer.setViewport( @SCREEN_WIDTH/2, 0, @SCREEN_WIDTH/2, @SCREEN_HEIGHT )
@renderer.render( @scene, @cameraOrthographic )
updateSelection : =>
# algorithm:
# loop through all clusters
# if cluster is visible then process it
# for each point check if it's inside selection
# if inside (and selector is active) set color to highlight
# else set color to original cluster color
counter = 0
for i in [0...@storage.getClusters()]
if @particles[i].visible
cloud = @points[i]
all = cloud.vertices.length
for j in [0...all]
vertex = cloud.vertices[j]
color = cloud.colors[j]
if @selector.isActive() and @selector.contains(vertex, Utility.DIRECTION.ALL)
color.setHex(Palette.HIGHLIGHT.getHex())
counter++
# Utility.printVector3(vertex)
else
color.setHex(@colors[i].getHex())
cloud.colorsNeedUpdate = true;
@notify(Projector.EVENT_POINTS_SELECTED, { points : counter })
updateMouse3D : =>
# NOTE This works only in DUAL mode
# TODO Extend this to other modes
ratio = 100 / 250 # ?
switch @direction
when Utility.DIRECTION.TOP
@mouse.x = (event.pageX - (3 * @SCREEN_WIDTH / 4)) * ratio
@mouse.y = 100
@mouse.z = (event.pageY - (@SCREEN_HEIGHT / 2)) * ratio
when Utility.DIRECTION.FRONT
@mouse.x = (event.pageX - (3 * @SCREEN_WIDTH / 4)) * ratio
@mouse.y = - (event.pageY - (@SCREEN_HEIGHT / 2)) * ratio
@mouse.z = 100
when Utility.DIRECTION.SIDE
@mouse.x = 100
@mouse.y = - (event.pageY - (@SCREEN_HEIGHT / 2)) * ratio
@mouse.z = - (event.pageX - (3 * @SCREEN_WIDTH / 4)) * ratio
# Returns 3D camera to its starting orientation and optionally position.
# Position is only reset if location argument is true.
resetCamera : (location) =>
if location then TweenLite.to( @cameraPerspective.position, 1, {x:0, y:0, z:550} )
TweenLite.to( @cameraPerspective.rotation, 1, {x:0, y:0, z:0} )
TweenLite.to( @cameraPerspective.up, 1, {x:0, y:1, z:0} )
# Set the visibility of orthographic view (top, front, side) indicator.
updateView : (visible) =>
@viewport.visible = visible
# NOTE Changing visibility of the viewport alone does not work as the change
# of visibility of the parent is an ongoing bug/issue of the ThreeJS library...
# ...so toggle all three separately
if @viewport.visible
switch @direction
when Utility.DIRECTION.TOP
@setViewsVisible(true, false, false)
@cameraOrthographic.position.set(0, 500, 0)
when Utility.DIRECTION.FRONT
@setViewsVisible(false, true, false)
@cameraOrthographic.position.set(0, 0, 500)
when Utility.DIRECTION.SIDE
@setViewsVisible(false, false, true)
@cameraOrthographic.position.set(500, 0, 0)
@cameraOrthographic.lookAt(@box.position)
else
@setViewsVisible(false, false, false)
return @viewport.visible
# Set visibility of view indicators.
setViewsVisible : (top, front, side) =>
@view1.visible = top
@view2.visible = front
@view3.visible = side
changeView : (@direction) =>
@updateView(@viewport.visible)
@selector.setDirection(@direction)
toggleAnimation : =>
@animateOn = not @animateOn
if @animateOn
@setAllClustersVisible(false)
@startTimer(0)
else
@setAllClustersVisible(true)
return @animateOn
setSpin : (@spin) =>
switch @spin
when Projector.SPIN.LEFT
@resetCamera(false)
when Projector.SPIN.NONE
@timeStamp = 0
when Projector.SPIN.RIGHT
@resetCamera(false)
# Spin camera in a circle around the center.
spinCamera : =>
STEP = @getSpinStep()
cx = @cameraPerspective.position.x
cy = -1 * @cameraPerspective.position.z
radians = Math.atan2(cy, cx)
radius = Math.sqrt(cx * cx + cy * cy)
switch @spin
when Projector.SPIN.LEFT
radians += STEP
if radians > Math.PI then radians = radians - (2 * Math.PI)
when Projector.SPIN.RIGHT
radians -= STEP
if radians < -Math.PI then radians = (2 * Math.PI) + radians
x = radius * Math.cos(radians)
y = radius * Math.sin(radians)
@cameraPerspective.position.x = x
@cameraPerspective.position.z = -1 * y
# Adjust the rotation step depending on time elapsed between the frames.
getSpinStep : =>
step = Projector.SPIN_STEP # default
if @timeStamp isnt 0
date = new Date()
timeNow = date.getTime()
delta = timeNow - @timeStamp
@timeStamp = timeNow
step = delta * step / 10
return step
# Toggle visibility of the cluster given by its index.
toggleClusterVisibility : (index) =>
@particles[index].visible = not @particles[index].visible
setAllClustersVisible : (visible) =>
p.visible = visible for p in @particles
# Select or unselect cluster of given index.
toggleClusterSelection : (index) =>
# clear old selected
if @selected > -1
# restore color coding on previous selection
hexColor = @colors[@selected].getHex()
@updatePoints(@selected, hexColor)
if @selected is index
# unselecting
@selected = -1
else
# selecting
@selected = index
# highlight new selected
@updatePoints(@selected, Palette.HIGHLIGHT.getHex())
if @selected > -1
@notify(Projector.EVENT_CLUSTER_SELECTED, { id : index })
else
@notify(Projector.EVENT_CLUSTER_SELECTED, { id : -1 })
# Color code given points cloud (cluster).
updatePoints : (index, color) =>
cloud = @points[index]
all = cloud.vertices.length
for i in [0...all]
cloud.colors[i].setHex(color)
@points[index].colorsNeedUpdate = true
startTimer : (index) =>
@toggleClusterVisibility(index)
window.setTimeout(@onTimer, 2 * Utility.SECOND, index)
# Count visible clusters.
clustersVisible : =>
result = 0
result++ for cloud in @particles when cloud.visible
return result
module.exports = Projector | true | # Projector.coffee
# PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI
# PI:EMAIL:<EMAIL>END_PI
# Projector class displays the data visualization.
# Images are rendered in WebGL on HTML5 Canvas using Three.js library.
# TODO Extend selection to work in ORTHOGRAPHIC and PERSPECTIVE, not only DUAL mode.
Subject = require('./Subject.coffee')
Utility = require('./Utility.coffee')
Palette = require('./Palette.coffee')
Selector = require('./Selector.coffee')
class Projector extends Subject
# E V E N T S
@EVENT_DATA_LOADED : "EVENT_DATA_LOADED"
@EVENT_POINTS_SELECTED : "EVENT_POINTS_SELECTED"
@EVENT_CLUSTER_SELECTED : "EVENT_CLUSTER_SELECTED"
# C O N S T A N T S
# three view/display modes
@VIEW : { NONE: -1, PERSPECTIVE: 0, ORTHOGRAPHIC: 1, DUAL: 2 }
# spin clock or counter clockwise
@SPIN : { LEFT: -1, NONE: 0, RIGHT: +1 }
@SPIN_STEP : Utility.DEGREE / 10 # 0.1 degree - default step
# M E M B E R S
# these are pseudo constants which are redefined when browser resizes
SCREEN_WIDTH : window.innerWidth
SCREEN_HEIGHT : window.innerHeight
mode : Projector.VIEW.DUAL # starting default
storage : null # reference to the data storage
colors : null # Array<THREE.Color> generated color values for visualization
scene : null # THREE.Scene
# perspective (3D) and orthographic (2D) projection cameras
cameraPerspective : null # THREE.PerspectiveCamera
cameraOrthographic : null # THREE.OrthographicCamera
renderer : null # THREE.WebGLRenderer
# mouse tracking variables
mouse : new THREE.Vector3() # current mouse coordinates when selecting
mouseStart : new THREE.Vector3() # mouse down coordinates when selecting
mouseEnd : new THREE.Vector3() # mouse up coordinates when selecting
dragging : false # true when rubber banding...
selector : null # Selector
# visual helpers for data display
box : null # THREE.Mesh - data cage
viewport : null # parent of selectable view rectangles
direction : Utility.DIRECTION.TOP # default 2D view is from top
view1 : null # THREE.Line - 2D orthographic view box - top
view2 : null # THREE.Line - 2D orthographic view box - front
view3 : null # THREE.Line - 2D orthographic view box - side
# visual representations of loaded data
points : null # Array<THREE.Geometry>
particles : null # Array<THREE.ParticleSystem>
clusters : null # array of particle systems one per cluster
selected : -1 # currently selected cluster
controls : null # THREE.TrackballControls
timeStamp : 0
# C O N S T R U C T O R
# Create projector.
# Constructor creates all initial setup to make projector ready for data.
constructor: ->
super()
@addUIListeners() # listen for UI events
@scene = new THREE.Scene() # 3D world
@createPerspectiveCamera() # left side (dual mode): 3D perspective camera
@createOrthographicCamera() # right side (dual mode): 2D ortographic projection camera
@createControls() # trackball simulation controls
@createBox() # bounding box for the data
@cameraPerspective.lookAt( @box.position )
@cameraOrthographic.lookAt( @box.position )
@createViews()
@updateView(true)
@selector = new Selector(@box) # 3D rubber band selector
@createRenderingEngine() # set up WebGL renderer on canvas
@onWindowResize(null)
@animate() # start rendering loop!
# E V E N T H A N D L E R S
# Make updates related to window size changes.
# Also used when view configuration is switched.
onWindowResize : (event) =>
@SCREEN_WIDTH = window.innerWidth
@SCREEN_HEIGHT = window.innerHeight
console.log "Screen #{@SCREEN_WIDTH} x #{@SCREEN_HEIGHT}"
if @renderer?
@renderer.setSize( @SCREEN_WIDTH, @SCREEN_HEIGHT )
switch @mode
when Projector.VIEW.PERSPECTIVE
@cameraPerspective.aspect = @SCREEN_WIDTH / @SCREEN_HEIGHT
@cameraPerspective.updateProjectionMatrix()
when Projector.VIEW.ORTHOGRAPHIC
@cameraOrthographic.left = - (@SCREEN_WIDTH / 8)
@cameraOrthographic.right = + (@SCREEN_WIDTH / 8)
@cameraOrthographic.top = + (@SCREEN_HEIGHT / 8)
@cameraOrthographic.bottom = - (@SCREEN_HEIGHT / 8)
@cameraOrthographic.updateProjectionMatrix()
when Projector.VIEW.DUAL
# left side
@cameraPerspective.aspect = 0.5 * @SCREEN_WIDTH / @SCREEN_HEIGHT
@cameraPerspective.updateProjectionMatrix()
# right side
@cameraOrthographic.left = - (@SCREEN_WIDTH / 10)
@cameraOrthographic.right = + (@SCREEN_WIDTH / 10)
@cameraOrthographic.top = + (@SCREEN_HEIGHT / 5)
@cameraOrthographic.bottom = - (@SCREEN_HEIGHT / 5)
@cameraOrthographic.updateProjectionMatrix()
@controls.handleResize()
onMouseDown : (event) =>
if @mode is Projector.VIEW.DUAL
event.preventDefault()
if event.shiftKey
@dragging = true
@updateMouse3D()
@mouseStart.copy(@mouse)
@selector.start(@mouseStart.clone())
event.stopPropagation()
onMouseMove : (event) =>
if @mode is Projector.VIEW.DUAL
event.preventDefault()
if @dragging
@updateMouse3D()
@selector.update(@mouse)
event.stopPropagation()
onMouseUp : (event) =>
if @mode is Projector.VIEW.DUAL
event.preventDefault()
if @dragging
@dragging = false
@updateMouse3D()
@mouseEnd.copy(@mouse)
@selector.end(@mouseEnd.clone())
@updateSelection()
event.stopPropagation()
# Toggle next cluster during the animated walk through.
onTimer : (index) =>
@toggleClusterVisibility(index)
if ++index is @storage.getClusters() then index = 0
if @animateOn then @startTimer(index)
# M E T H O D S
# Set the current mode.
setMode : (@mode) =>
@onWindowResize(null)
# Use given color set for visualization.
setColors : (@colors) =>
# Toggle box visibility. Return current state.
toggleBox : => return (@box.visible = not @box.visible)
# Toggle viewport visibility. Return current state.
toggleViewport : => return @updateView(not @viewport.visible)
toggleSelector : =>
state = @selector.toggle()
@updateSelection()
return state
# Get the base 64 encoded image of the current state of the projector.
getImage : =>
return document.getElementById("renderer").toDataURL("image/png")
# Hook up to browser and mouse events.
addUIListeners : =>
window.addEventListener('resize', @onWindowResize, false)
# container will hold WebGL canvas
$('#container').mousedown(@onMouseDown)
$('#container').mousemove(@onMouseMove)
$('#container').mouseup(@onMouseUp)
# Proper 3D camera.
createPerspectiveCamera : =>
# NOTE Cameras aspect ratio setup matches the half screen viewports for initial dual mode
@cameraPerspective = new THREE.PerspectiveCamera( 50, 0.5 * @SCREEN_WIDTH / @SCREEN_HEIGHT, 150, 1000 )
@cameraPerspective.position.set(0, 0, 550)
@scene.add( @cameraPerspective )
# Flat, 2D, no perspective camera.
createOrthographicCamera : =>
@cameraOrthographic = new THREE.OrthographicCamera( - (@SCREEN_WIDTH / 8),
+ (@SCREEN_WIDTH / 8),
+ (@SCREEN_HEIGHT / 4),
- (@SCREEN_HEIGHT / 4),
250, 750 )
@cameraOrthographic.position.set(0, 500, 0)
@scene.add( @cameraOrthographic )
# Initialize simulated trackball navigation controls
createControls : =>
@controls = new THREE.TrackballControls( @cameraPerspective )
@controls.rotateSpeed = 1.0
@controls.zoomSpeed = 1.0
@controls.panSpeed = 0.8
@controls.noZoom = false
@controls.noPan = false
@controls.staticMoving = true
@controls.dynamicDampingFactor = 0.3
@controls.addEventListener('change', @render)
# Bounding box where the data is displayed.
createBox : =>
@box = new THREE.Mesh(new THREE.CubeGeometry(200, 200, 200),
new THREE.MeshBasicMaterial({ color: 0x404040, wireframe: true }))
@scene.add(@box)
# Create a set of highlights that indicate ortographic projection in perspective view.
# Each rectangle simply indicates where 2D view is within the 3D space.
createViews : =>
@viewport = new THREE.Object3D()
# top view
geometry1 = new THREE.Geometry()
geometry1.vertices.push( new THREE.Vector3( +100, +101, +100 ) )
geometry1.vertices.push( new THREE.Vector3( -100, +101, +100 ) )
geometry1.vertices.push( new THREE.Vector3( -100, +101, -100 ) )
geometry1.vertices.push( new THREE.Vector3( +100, +101, -100 ) )
geometry1.vertices.push( new THREE.Vector3( +100, +101, +100 ) )
@view1 = new THREE.Line(geometry1, new THREE.LineBasicMaterial(), THREE.LineStrip)
# front view
geometry2 = new THREE.Geometry()
geometry2.vertices.push( new THREE.Vector3( +100, +100, +101 ) )
geometry2.vertices.push( new THREE.Vector3( -100, +100, +101 ) )
geometry2.vertices.push( new THREE.Vector3( -100, -100, +101 ) )
geometry2.vertices.push( new THREE.Vector3( +100, -100, +101 ) )
geometry2.vertices.push( new THREE.Vector3( +100, +100, +101 ) )
@view2 = new THREE.Line(geometry2, new THREE.LineBasicMaterial(), THREE.LineStrip)
# side view
geometry3 = new THREE.Geometry()
geometry3.vertices.push( new THREE.Vector3( +101, +100, +100 ) )
geometry3.vertices.push( new THREE.Vector3( +101, -100, +100 ) )
geometry3.vertices.push( new THREE.Vector3( +101, -100, -100 ) )
geometry3.vertices.push( new THREE.Vector3( +101, +100, -100 ) )
geometry3.vertices.push( new THREE.Vector3( +101, +100, +100 ) )
@view3 = new THREE.Line(geometry3, new THREE.LineBasicMaterial(), THREE.LineStrip)
@viewport.add(@view1) # top
@viewport.add(@view2) # front
@viewport.add(@view3) # side
@box.add(@viewport)
createRenderingEngine : =>
# basically canvas in WebGL mode
@renderer = new THREE.WebGLRenderer( { antialias: true, preserveDrawingBuffer: true } )
@renderer.setSize( @SCREEN_WIDTH, @SCREEN_HEIGHT )
@renderer.setClearColor( Palette.BACKGROUND.getHex(), 1 )
@renderer.domElement.style.position = "relative"
@renderer.domElement.id = "renderer"
@renderer.autoClear = false
# container is the display area placeholder in HTML
container = $('#container').get(0)
container.appendChild( @renderer.domElement )
# Load JSON data to visualize.
load : (@storage) =>
data = @storage.getData() # JSON
clusters = @storage.getClusters() # number of clusters
# create point clouds first for each cluster
@points = new Array()
for c in [0...clusters]
@points[c] = new THREE.Geometry()
@points[c].colorsNeedUpdate = true
# process JSON data
$.each(data.points, @processPoint)
# create particle systems for each cluster (with point clouds within)
@particles = new Array()
for p in [0...clusters]
material = new THREE.ParticleBasicMaterial( { size: 1.0, sizeAttenuation: false, vertexColors: true } )
@particles[p] = new THREE.ParticleSystem( @points[p], material )
@box.add( @particles[p] ) # put them in the data cage
@notify(Projector.EVENT_DATA_LOADED)
# Called for each data point loaded in JSON file.
processPoint : (nodeName, nodeData) =>
# cluster index
index = parseInt(nodeData.cid)
vertex = new THREE.Vector3()
vertex.x = parseFloat( nodeData.x )
vertex.y = parseFloat( nodeData.y )
vertex.z = parseFloat( nodeData.z )
@points[index].vertices.push( vertex )
# NOTE Although initially all points in the same cluster have the same color
# they do take individual colors during the selection interactions therefore
# each point needs its own individual color object instead of shared one...
color = @colors[index].clone()
@points[index].colors.push( color )
# Rendering loop - animate calls itself forever.
animate : =>
requestAnimationFrame( @animate )
@controls.update()
@render()
# Rendering done on each frame.
# Rendering configuration depends on the current view mode.
render : =>
@renderer.clear()
switch @mode
# one viewport: perspective camera only
when Projector.VIEW.PERSPECTIVE
if @spin isnt Projector.SPIN.NONE then @spinCamera()
@cameraPerspective.lookAt( @box.position )
# RENDERING
@renderer.setViewport( 0, 0, @SCREEN_WIDTH, @SCREEN_HEIGHT )
@renderer.render( @scene, @cameraPerspective )
# one viewport: orthographic camera only
when Projector.VIEW.ORTHOGRAPHIC
# RENDERING
@cameraOrthographic.rotation.z = 0
@renderer.setViewport( 0, 0, @SCREEN_WIDTH, @SCREEN_HEIGHT )
@renderer.render( @scene, @cameraOrthographic )
# dual perspective and orthographic cameras view
when Projector.VIEW.DUAL
# synchronize camera with rotation
if @spin isnt Projector.SPIN.NONE then @spinCamera()
@cameraPerspective.lookAt( @box.position )
# RENDERING
# left side viewport: perspective camera
@renderer.setViewport( 0, 0, @SCREEN_WIDTH/2, @SCREEN_HEIGHT )
@renderer.render( @scene, @cameraPerspective )
# right side viewport: orthographic camera
@cameraOrthographic.rotation.z = 0
@renderer.setViewport( @SCREEN_WIDTH/2, 0, @SCREEN_WIDTH/2, @SCREEN_HEIGHT )
@renderer.render( @scene, @cameraOrthographic )
updateSelection : =>
# algorithm:
# loop through all clusters
# if cluster is visible then process it
# for each point check if it's inside selection
# if inside (and selector is active) set color to highlight
# else set color to original cluster color
counter = 0
for i in [0...@storage.getClusters()]
if @particles[i].visible
cloud = @points[i]
all = cloud.vertices.length
for j in [0...all]
vertex = cloud.vertices[j]
color = cloud.colors[j]
if @selector.isActive() and @selector.contains(vertex, Utility.DIRECTION.ALL)
color.setHex(Palette.HIGHLIGHT.getHex())
counter++
# Utility.printVector3(vertex)
else
color.setHex(@colors[i].getHex())
cloud.colorsNeedUpdate = true;
@notify(Projector.EVENT_POINTS_SELECTED, { points : counter })
updateMouse3D : =>
# NOTE This works only in DUAL mode
# TODO Extend this to other modes
ratio = 100 / 250 # ?
switch @direction
when Utility.DIRECTION.TOP
@mouse.x = (event.pageX - (3 * @SCREEN_WIDTH / 4)) * ratio
@mouse.y = 100
@mouse.z = (event.pageY - (@SCREEN_HEIGHT / 2)) * ratio
when Utility.DIRECTION.FRONT
@mouse.x = (event.pageX - (3 * @SCREEN_WIDTH / 4)) * ratio
@mouse.y = - (event.pageY - (@SCREEN_HEIGHT / 2)) * ratio
@mouse.z = 100
when Utility.DIRECTION.SIDE
@mouse.x = 100
@mouse.y = - (event.pageY - (@SCREEN_HEIGHT / 2)) * ratio
@mouse.z = - (event.pageX - (3 * @SCREEN_WIDTH / 4)) * ratio
# Returns 3D camera to its starting orientation and optionally position.
# Position is only reset if location argument is true.
resetCamera : (location) =>
if location then TweenLite.to( @cameraPerspective.position, 1, {x:0, y:0, z:550} )
TweenLite.to( @cameraPerspective.rotation, 1, {x:0, y:0, z:0} )
TweenLite.to( @cameraPerspective.up, 1, {x:0, y:1, z:0} )
# Set the visibility of orthographic view (top, front, side) indicator.
updateView : (visible) =>
@viewport.visible = visible
# NOTE Changing visibility of the viewport alone does not work as the change
# of visibility of the parent is an ongoing bug/issue of the ThreeJS library...
# ...so toggle all three separately
if @viewport.visible
switch @direction
when Utility.DIRECTION.TOP
@setViewsVisible(true, false, false)
@cameraOrthographic.position.set(0, 500, 0)
when Utility.DIRECTION.FRONT
@setViewsVisible(false, true, false)
@cameraOrthographic.position.set(0, 0, 500)
when Utility.DIRECTION.SIDE
@setViewsVisible(false, false, true)
@cameraOrthographic.position.set(500, 0, 0)
@cameraOrthographic.lookAt(@box.position)
else
@setViewsVisible(false, false, false)
return @viewport.visible
# Set visibility of view indicators.
setViewsVisible : (top, front, side) =>
@view1.visible = top
@view2.visible = front
@view3.visible = side
changeView : (@direction) =>
@updateView(@viewport.visible)
@selector.setDirection(@direction)
toggleAnimation : =>
@animateOn = not @animateOn
if @animateOn
@setAllClustersVisible(false)
@startTimer(0)
else
@setAllClustersVisible(true)
return @animateOn
setSpin : (@spin) =>
switch @spin
when Projector.SPIN.LEFT
@resetCamera(false)
when Projector.SPIN.NONE
@timeStamp = 0
when Projector.SPIN.RIGHT
@resetCamera(false)
# Spin camera in a circle around the center.
spinCamera : =>
STEP = @getSpinStep()
cx = @cameraPerspective.position.x
cy = -1 * @cameraPerspective.position.z
radians = Math.atan2(cy, cx)
radius = Math.sqrt(cx * cx + cy * cy)
switch @spin
when Projector.SPIN.LEFT
radians += STEP
if radians > Math.PI then radians = radians - (2 * Math.PI)
when Projector.SPIN.RIGHT
radians -= STEP
if radians < -Math.PI then radians = (2 * Math.PI) + radians
x = radius * Math.cos(radians)
y = radius * Math.sin(radians)
@cameraPerspective.position.x = x
@cameraPerspective.position.z = -1 * y
# Adjust the rotation step depending on time elapsed between the frames.
getSpinStep : =>
step = Projector.SPIN_STEP # default
if @timeStamp isnt 0
date = new Date()
timeNow = date.getTime()
delta = timeNow - @timeStamp
@timeStamp = timeNow
step = delta * step / 10
return step
# Toggle visibility of the cluster given by its index.
toggleClusterVisibility : (index) =>
@particles[index].visible = not @particles[index].visible
setAllClustersVisible : (visible) =>
p.visible = visible for p in @particles
# Select or unselect cluster of given index.
toggleClusterSelection : (index) =>
# clear old selected
if @selected > -1
# restore color coding on previous selection
hexColor = @colors[@selected].getHex()
@updatePoints(@selected, hexColor)
if @selected is index
# unselecting
@selected = -1
else
# selecting
@selected = index
# highlight new selected
@updatePoints(@selected, Palette.HIGHLIGHT.getHex())
if @selected > -1
@notify(Projector.EVENT_CLUSTER_SELECTED, { id : index })
else
@notify(Projector.EVENT_CLUSTER_SELECTED, { id : -1 })
# Color code given points cloud (cluster).
updatePoints : (index, color) =>
cloud = @points[index]
all = cloud.vertices.length
for i in [0...all]
cloud.colors[i].setHex(color)
@points[index].colorsNeedUpdate = true
startTimer : (index) =>
@toggleClusterVisibility(index)
window.setTimeout(@onTimer, 2 * Utility.SECOND, index)
# Count visible clusters.
clustersVisible : =>
result = 0
result++ for cloud in @particles when cloud.visible
return result
module.exports = Projector |
[
{
"context": "\n Accounts.createUser {\n username: username,\n email: email,\n password: pass",
"end": 1572,
"score": 0.9923539161682129,
"start": 1564,
"tag": "USERNAME",
"value": "username"
},
{
"context": "rname,\n email: email,\n password: password\n }, (err) ->\n #TODO if err and er",
"end": 1626,
"score": 0.9967672824859619,
"start": 1618,
"tag": "PASSWORD",
"value": "password"
}
] | app/client/accounts/loginOrRegister.coffee | eribeiro9/CoLabs | 0 | Template.signInButton.events
"click": (event) ->
Modal.show "loginOrRegisterModal"
Template.loginOrRegisterModal.helpers
buttonClose: -> Render.buttonClose
id: 'closeLoginModal'
class: 'pull-right'
dataDismiss: 'modal'
Template.loginOrRegisterModal.events
"click #loginRadioOption": (event) ->
$("#login-email").addClass("hidden")
$("#login-verify-password").addClass("hidden")
$("#signinSubmit").val("Log In")
"click #signupRadioOption": (event) ->
$("#login-email").removeClass("hidden")
$("#login-verify-password").removeClass("hidden")
$("#signinSubmit").val("Sign Up")
"submit form": (event) ->
isLoginChecked = document.getElementById("loginRadioOption").checked
event.preventDefault()
if isLoginChecked
username = event.target.username.value
password = event.target.password.value
Meteor.loginWithPassword username, password, (err) ->
if not err then Modal.hide "loginOrRegisterModal"
else toast.warning "<i class=\"fa fa-warning\" /> Warning!",
"Username or Password is invalid."
else
username = event.target.username.value
email = event.target.email.value
password = event.target.password.value
verifyPassword = event.target.verifyPassword.value
Modal.allowMultiple = true
if password isnt verifyPassword
toast.danger "Passwords Don't Match",
"Please make sure your password fields match."
else
Accounts.createUser {
username: username,
email: email,
password: password
}, (err) ->
#TODO if err and err.reason is "Email already exists." then ...
if err? then toast.danger "Error!", err.reason
else
Modal.allowMultiple = true
Modal.hide "loginOrRegisterModal"
if email isnt ""
toast.success "Verification Email Sent",
"Please check your email to verify your registration.
Until you verify, you will not have the ability to create or participate in projects.",
10000
else
toast.warning "You Cannot Verify Without An Email Address",
"Please add an email address on your profile page in order to send the verification email.
Without verifying, you will not have the ability to create or participate in projects.",
10000
Template.signOutButton.events
"click": ->
Session.keys = {}
Meteor.logout()
| 180670 | Template.signInButton.events
"click": (event) ->
Modal.show "loginOrRegisterModal"
Template.loginOrRegisterModal.helpers
buttonClose: -> Render.buttonClose
id: 'closeLoginModal'
class: 'pull-right'
dataDismiss: 'modal'
Template.loginOrRegisterModal.events
"click #loginRadioOption": (event) ->
$("#login-email").addClass("hidden")
$("#login-verify-password").addClass("hidden")
$("#signinSubmit").val("Log In")
"click #signupRadioOption": (event) ->
$("#login-email").removeClass("hidden")
$("#login-verify-password").removeClass("hidden")
$("#signinSubmit").val("Sign Up")
"submit form": (event) ->
isLoginChecked = document.getElementById("loginRadioOption").checked
event.preventDefault()
if isLoginChecked
username = event.target.username.value
password = event.target.password.value
Meteor.loginWithPassword username, password, (err) ->
if not err then Modal.hide "loginOrRegisterModal"
else toast.warning "<i class=\"fa fa-warning\" /> Warning!",
"Username or Password is invalid."
else
username = event.target.username.value
email = event.target.email.value
password = event.target.password.value
verifyPassword = event.target.verifyPassword.value
Modal.allowMultiple = true
if password isnt verifyPassword
toast.danger "Passwords Don't Match",
"Please make sure your password fields match."
else
Accounts.createUser {
username: username,
email: email,
password: <PASSWORD>
}, (err) ->
#TODO if err and err.reason is "Email already exists." then ...
if err? then toast.danger "Error!", err.reason
else
Modal.allowMultiple = true
Modal.hide "loginOrRegisterModal"
if email isnt ""
toast.success "Verification Email Sent",
"Please check your email to verify your registration.
Until you verify, you will not have the ability to create or participate in projects.",
10000
else
toast.warning "You Cannot Verify Without An Email Address",
"Please add an email address on your profile page in order to send the verification email.
Without verifying, you will not have the ability to create or participate in projects.",
10000
Template.signOutButton.events
"click": ->
Session.keys = {}
Meteor.logout()
| true | Template.signInButton.events
"click": (event) ->
Modal.show "loginOrRegisterModal"
Template.loginOrRegisterModal.helpers
buttonClose: -> Render.buttonClose
id: 'closeLoginModal'
class: 'pull-right'
dataDismiss: 'modal'
Template.loginOrRegisterModal.events
"click #loginRadioOption": (event) ->
$("#login-email").addClass("hidden")
$("#login-verify-password").addClass("hidden")
$("#signinSubmit").val("Log In")
"click #signupRadioOption": (event) ->
$("#login-email").removeClass("hidden")
$("#login-verify-password").removeClass("hidden")
$("#signinSubmit").val("Sign Up")
"submit form": (event) ->
isLoginChecked = document.getElementById("loginRadioOption").checked
event.preventDefault()
if isLoginChecked
username = event.target.username.value
password = event.target.password.value
Meteor.loginWithPassword username, password, (err) ->
if not err then Modal.hide "loginOrRegisterModal"
else toast.warning "<i class=\"fa fa-warning\" /> Warning!",
"Username or Password is invalid."
else
username = event.target.username.value
email = event.target.email.value
password = event.target.password.value
verifyPassword = event.target.verifyPassword.value
Modal.allowMultiple = true
if password isnt verifyPassword
toast.danger "Passwords Don't Match",
"Please make sure your password fields match."
else
Accounts.createUser {
username: username,
email: email,
password: PI:PASSWORD:<PASSWORD>END_PI
}, (err) ->
#TODO if err and err.reason is "Email already exists." then ...
if err? then toast.danger "Error!", err.reason
else
Modal.allowMultiple = true
Modal.hide "loginOrRegisterModal"
if email isnt ""
toast.success "Verification Email Sent",
"Please check your email to verify your registration.
Until you verify, you will not have the ability to create or participate in projects.",
10000
else
toast.warning "You Cannot Verify Without An Email Address",
"Please add an email address on your profile page in order to send the verification email.
Without verifying, you will not have the ability to create or participate in projects.",
10000
Template.signOutButton.events
"click": ->
Session.keys = {}
Meteor.logout()
|
[
{
"context": "rror.status is 401)\n $scope.badPassword = yes\n $scope.userInfo.currentPassword = ''\n ",
"end": 2224,
"score": 0.9968593716621399,
"start": 2221,
"tag": "PASSWORD",
"value": "yes"
},
{
"context": " = yes\n $scope.userInfo.currentPassword = ''\n $scope.submitButton.state 'error'\n",
"end": 2268,
"score": 0.6600288152694702,
"start": 2268,
"tag": "PASSWORD",
"value": ""
}
] | app/views/settings/settings.coffee | jluchiji/tranzit | 0 | angular.module 'Tranzit.app.views.settings', []
.controller 'SettingsController', ($scope, AppSession) ->
undefined
.controller 'AccountSettingsController', ($scope, TranzitAuthSession, AppSession, AppData) ->
# Make a backup copy of the user info
original =
firstName: AppSession.user().name
password: ''
# Make a copy of the user info
$scope.userInfo =
firstName: AppSession.user().name
password: ''
# Multistate: save account settings
$scope.submitButton =
'loading':
class: 'loading disabled'
'success':
class: 'success disabled'
callback: -> setTimeout((=> @state 'default'), 3000)
'error':
class: 'error disabled'
callback: -> setTimeout((=> @state 'default'), 3000)
$scope.badPassword = no
# 'Private' functions
getChanges = ->
return _.diff original, $scope.userInfo, ['name', 'password']
# 'Public' functions
$scope.hasChanges = ->
diff = getChanges()
return diff and _.keys(diff).length isnt 0
$scope.needPassword = ->
diff = getChanges()
return diff.password and not $scope.userInfo.currentPassword
$scope.needVerify = ->
diff = getChanges()
return diff.password and $scope.userInfo.password isnt $scope.userInfo.passwordVerify
$scope.reset = ->
$scope.userInfo =
firstName: AppSession.user().name
password: ''
passwordVerofy: ''
currentPassword: ''
$scope.submit = ->
if not $scope.hasChanges()
$scope.submitButton.state 'success'
return
# Shorthand
u = $scope.userInfo
# Validity of first name & last name checked by HTML form
# Validity of password
if $scope.needPassword() and not u.currentPassword
$scope.submitButton.state 'error'
return
if $scope.needVerify() and u.password isnt u.passwordVerify
$scope.userInfo.passwordVerify = ''
$scope.submitButton.state 'error'
return
$scope.badPassword = no
$scope.submitButton.state 'loading'
AppData.updateUser(u.currentPassword, getChanges())
.success ->
$scope.submitButton.state 'success'
$scope.reset()
.error (error) ->
if (error.status is 401)
$scope.badPassword = yes
$scope.userInfo.currentPassword = ''
$scope.submitButton.state 'error'
| 65779 | angular.module 'Tranzit.app.views.settings', []
.controller 'SettingsController', ($scope, AppSession) ->
undefined
.controller 'AccountSettingsController', ($scope, TranzitAuthSession, AppSession, AppData) ->
# Make a backup copy of the user info
original =
firstName: AppSession.user().name
password: ''
# Make a copy of the user info
$scope.userInfo =
firstName: AppSession.user().name
password: ''
# Multistate: save account settings
$scope.submitButton =
'loading':
class: 'loading disabled'
'success':
class: 'success disabled'
callback: -> setTimeout((=> @state 'default'), 3000)
'error':
class: 'error disabled'
callback: -> setTimeout((=> @state 'default'), 3000)
$scope.badPassword = no
# 'Private' functions
getChanges = ->
return _.diff original, $scope.userInfo, ['name', 'password']
# 'Public' functions
$scope.hasChanges = ->
diff = getChanges()
return diff and _.keys(diff).length isnt 0
$scope.needPassword = ->
diff = getChanges()
return diff.password and not $scope.userInfo.currentPassword
$scope.needVerify = ->
diff = getChanges()
return diff.password and $scope.userInfo.password isnt $scope.userInfo.passwordVerify
$scope.reset = ->
$scope.userInfo =
firstName: AppSession.user().name
password: ''
passwordVerofy: ''
currentPassword: ''
$scope.submit = ->
if not $scope.hasChanges()
$scope.submitButton.state 'success'
return
# Shorthand
u = $scope.userInfo
# Validity of first name & last name checked by HTML form
# Validity of password
if $scope.needPassword() and not u.currentPassword
$scope.submitButton.state 'error'
return
if $scope.needVerify() and u.password isnt u.passwordVerify
$scope.userInfo.passwordVerify = ''
$scope.submitButton.state 'error'
return
$scope.badPassword = no
$scope.submitButton.state 'loading'
AppData.updateUser(u.currentPassword, getChanges())
.success ->
$scope.submitButton.state 'success'
$scope.reset()
.error (error) ->
if (error.status is 401)
$scope.badPassword = <PASSWORD>
$scope.userInfo.currentPassword =<PASSWORD> ''
$scope.submitButton.state 'error'
| true | angular.module 'Tranzit.app.views.settings', []
.controller 'SettingsController', ($scope, AppSession) ->
undefined
.controller 'AccountSettingsController', ($scope, TranzitAuthSession, AppSession, AppData) ->
# Make a backup copy of the user info
original =
firstName: AppSession.user().name
password: ''
# Make a copy of the user info
$scope.userInfo =
firstName: AppSession.user().name
password: ''
# Multistate: save account settings
$scope.submitButton =
'loading':
class: 'loading disabled'
'success':
class: 'success disabled'
callback: -> setTimeout((=> @state 'default'), 3000)
'error':
class: 'error disabled'
callback: -> setTimeout((=> @state 'default'), 3000)
$scope.badPassword = no
# 'Private' functions
getChanges = ->
return _.diff original, $scope.userInfo, ['name', 'password']
# 'Public' functions
$scope.hasChanges = ->
diff = getChanges()
return diff and _.keys(diff).length isnt 0
$scope.needPassword = ->
diff = getChanges()
return diff.password and not $scope.userInfo.currentPassword
$scope.needVerify = ->
diff = getChanges()
return diff.password and $scope.userInfo.password isnt $scope.userInfo.passwordVerify
$scope.reset = ->
$scope.userInfo =
firstName: AppSession.user().name
password: ''
passwordVerofy: ''
currentPassword: ''
$scope.submit = ->
if not $scope.hasChanges()
$scope.submitButton.state 'success'
return
# Shorthand
u = $scope.userInfo
# Validity of first name & last name checked by HTML form
# Validity of password
if $scope.needPassword() and not u.currentPassword
$scope.submitButton.state 'error'
return
if $scope.needVerify() and u.password isnt u.passwordVerify
$scope.userInfo.passwordVerify = ''
$scope.submitButton.state 'error'
return
$scope.badPassword = no
$scope.submitButton.state 'loading'
AppData.updateUser(u.currentPassword, getChanges())
.success ->
$scope.submitButton.state 'success'
$scope.reset()
.error (error) ->
if (error.status is 401)
$scope.badPassword = PI:PASSWORD:<PASSWORD>END_PI
$scope.userInfo.currentPassword =PI:PASSWORD:<PASSWORD>END_PI ''
$scope.submitButton.state 'error'
|
[
{
"context": "rror'\n process.env.HUBOT_TWITTER_CONSUMER_KEY='foobarbaz'\n process.env.HUBOT_TWITTER_CONSUMER_SECRET='f",
"end": 382,
"score": 0.7512000203132629,
"start": 373,
"tag": "KEY",
"value": "foobarbaz"
},
{
"context": "z'\n process.env.HUBOT_TWITTER_CONSUMER_SECRET='foobarbaz'\n process.env.HUBOT_TWITTER_ACCESS_TOKEN='foob",
"end": 440,
"score": 0.9907100200653076,
"start": 431,
"tag": "KEY",
"value": "foobarbaz"
},
{
"context": "rbaz'\n process.env.HUBOT_TWITTER_ACCESS_TOKEN='foobarbaz'\n process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRE",
"end": 495,
"score": 0.5539945960044861,
"start": 486,
"tag": "PASSWORD",
"value": "foobarbaz"
},
{
"context": " process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET='foobarbaz'\n nock.disableNetConnect()\n @room = helper.",
"end": 557,
"score": 0.9975526928901672,
"start": 548,
"tag": "KEY",
"value": "foobarbaz"
},
{
"context": "sv')\n\n selfRoom = @room\n selfRoom.user.say('alice', '@hubot preds')\n setTimeout(() ->\n try\n",
"end": 1720,
"score": 0.9987872242927551,
"start": 1715,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " selfRoom = @room\n selfRoom.user.say('alice', '@hubot preds')\n setTimeout(() ->\n try\n expect(s",
"end": 1736,
"score": 0.896515429019928,
"start": 1723,
"tag": "USERNAME",
"value": "'@hubot preds"
},
{
"context": " expect(selfRoom.messages).to.eql [\n ['alice', '@hubot preds']\n [\n 'hubot'",
"end": 1830,
"score": 0.9982894062995911,
"start": 1825,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "ct(selfRoom.messages).to.eql [\n ['alice', '@hubot preds']\n [\n 'hubot',\n ",
"end": 1840,
"score": 0.787369430065155,
"start": 1833,
"tag": "USERNAME",
"value": "'@hubot"
},
{
"context": "r/2019020052\",\n \"author_name\": \"NHL.com\",\n \"author_link\": \"https://nhl.c",
"end": 2162,
"score": 0.6469396948814392,
"start": 2156,
"tag": "EMAIL",
"value": "HL.com"
},
{
"context": " \"author_icon\": \"https://github.com/nhl.png\",\n \"color\": \"#FFB81C\",\n ",
"end": 2277,
"score": 0.9939742088317871,
"start": 2270,
"tag": "USERNAME",
"value": "nhl.png"
},
{
"context": "ley Cup: 4.2%\",\n \"author_name\": \"MoneyPuck.com\",\n \"author_link\": \"https://money",
"end": 2868,
"score": 0.9830716848373413,
"start": 2855,
"tag": "EMAIL",
"value": "MoneyPuck.com"
},
{
"context": "sv')\n\n selfRoom = @room\n selfRoom.user.say('alice', '@hubot preds')\n setTimeout(() ->\n try\n",
"end": 4515,
"score": 0.9583704471588135,
"start": 4510,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "selfRoom = @room\n selfRoom.user.say('alice', '@hubot preds')\n setTimeout(() ->\n try\n expect(s",
"end": 4531,
"score": 0.8150839805603027,
"start": 4520,
"tag": "USERNAME",
"value": "hubot preds"
},
{
"context": " expect(selfRoom.messages).to.eql [\n ['alice', '@hubot preds']\n [\n 'hubot'",
"end": 4625,
"score": 0.9707797765731812,
"start": 4620,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "selfRoom.messages).to.eql [\n ['alice', '@hubot preds']\n [\n 'hubot',\n ",
"end": 4635,
"score": 0.8981646299362183,
"start": 4630,
"tag": "USERNAME",
"value": "hubot"
},
{
"context": "ley Cup: 4.2%\",\n \"author_name\": \"MoneyPuck.com\",\n \"author_link\": \"https://money",
"end": 5672,
"score": 0.7795721292495728,
"start": 5659,
"tag": "EMAIL",
"value": "MoneyPuck.com"
},
{
"context": "sv')\n\n selfRoom = @room\n selfRoom.user.say('alice', '@hubot bolts')\n setTimeout(() ->\n try\n",
"end": 7330,
"score": 0.9697171449661255,
"start": 7325,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " expect(selfRoom.messages).to.eql [\n ['alice', '@hubot bolts']\n [\n 'hubot'",
"end": 7440,
"score": 0.9545609354972839,
"start": 7435,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " \"author_icon\": \"https://github.com/nhl.png\",\n \"color\": \"#002868\",\n ",
"end": 7912,
"score": 0.999618649482727,
"start": 7905,
"tag": "USERNAME",
"value": "nhl.png"
},
{
"context": "up: 5.4%\",\n \"author_name\": \"MoneyPuck.com\",\n \"author_link\": \"https://money",
"end": 8529,
"score": 0.7448829412460327,
"start": 8521,
"tag": "EMAIL",
"value": "Puck.com"
},
{
"context": "sv')\n\n selfRoom = @room\n selfRoom.user.say('alice', '@hubot preds')\n setTimeout(() ->\n try\n",
"end": 10148,
"score": 0.962119460105896,
"start": 10143,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " expect(selfRoom.messages).to.eql [\n ['alice', '@hubot preds']\n [\n 'hubot'",
"end": 10258,
"score": 0.9384450316429138,
"start": 10253,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " \"author_icon\": \"https://github.com/nhl.png\",\n \"color\": \"#FFB81C\",\n ",
"end": 10712,
"score": 0.9994749426841736,
"start": 10705,
"tag": "USERNAME",
"value": "nhl.png"
},
{
"context": "up: 4.2%\",\n \"author_name\": \"MoneyPuck.com\",\n \"author_link\": \"https://money",
"end": 11363,
"score": 0.6584202647209167,
"start": 11355,
"tag": "EMAIL",
"value": "Puck.com"
},
{
"context": "sv')\n\n selfRoom = @room\n selfRoom.user.say('alice', '@hubot preds')\n setTimeout(() ->\n try\n",
"end": 12981,
"score": 0.9558310508728027,
"start": 12976,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " expect(selfRoom.messages).to.eql [\n ['alice', '@hubot preds']\n [\n 'hubot'",
"end": 13091,
"score": 0.8906900882720947,
"start": 13086,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " \"author_icon\": \"https://github.com/nhl.png\",\n \"color\": \"#FFB81C\",\n ",
"end": 13540,
"score": 0.9979991912841797,
"start": 13533,
"tag": "USERNAME",
"value": "nhl.png"
},
{
"context": "ley Cup: 4.2%\",\n \"author_name\": \"MoneyPuck.com\",\n \"author_link\": \"https://mo",
"end": 14160,
"score": 0.5191453099250793,
"start": 14151,
"tag": "USERNAME",
"value": "MoneyPuck"
},
{
"context": ".2%\",\n \"author_name\": \"MoneyPuck.com\",\n \"author_link\": \"https://money",
"end": 14164,
"score": 0.46724197268486023,
"start": 14161,
"tag": "EMAIL",
"value": "com"
},
{
"context": "sv')\n\n selfRoom = @room\n selfRoom.user.say('alice', '@hubot preds')\n setTimeout(() ->\n try\n",
"end": 15792,
"score": 0.9752762913703918,
"start": 15787,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " selfRoom = @room\n selfRoom.user.say('alice', '@hubot preds')\n setTimeout(() ->\n try\n ex",
"end": 15802,
"score": 0.8632491230964661,
"start": 15795,
"tag": "USERNAME",
"value": "'@hubot"
},
{
"context": " expect(selfRoom.messages).to.eql [\n ['alice', '@hubot preds']\n [\n 'hubot'",
"end": 15902,
"score": 0.9627994298934937,
"start": 15897,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "selfRoom.messages).to.eql [\n ['alice', '@hubot preds']\n [\n 'hubot',\n ",
"end": 15912,
"score": 0.948357343673706,
"start": 15907,
"tag": "USERNAME",
"value": "hubot"
},
{
"context": "ley Cup: 1.6%\",\n \"author_name\": \"MoneyPuck.com\",\n \"author_link\": \"https://money",
"end": 16986,
"score": 0.9979174733161926,
"start": 16973,
"tag": "EMAIL",
"value": "MoneyPuck.com"
},
{
"context": "get('/1.1/statuses/user_timeline.json?screen_name=predsnhl')\n .replyWithFile(200, __dirname + '/fixture",
"end": 17832,
"score": 0.9993538856506348,
"start": 17824,
"tag": "USERNAME",
"value": "predsnhl"
},
{
"context": "on')\n\n selfRoom = @room\n selfRoom.user.say('alice', '@hubot preds twitter')\n setTimeout(() ->\n ",
"end": 17958,
"score": 0.9622185826301575,
"start": 17953,
"tag": "USERNAME",
"value": "alice"
},
{
"context": " selfRoom = @room\n selfRoom.user.say('alice', '@hubot preds twitter')\n setTimeout(() ->\n try\n ",
"end": 17968,
"score": 0.8881731033325195,
"start": 17961,
"tag": "USERNAME",
"value": "'@hubot"
},
{
"context": " expect(selfRoom.messages).to.eql [\n ['alice', '@hubot preds twitter']\n [\n ",
"end": 18076,
"score": 0.9310242533683777,
"start": 18071,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "ct(selfRoom.messages).to.eql [\n ['alice', '@hubot preds twitter']\n [\n 'hubot',\n",
"end": 18086,
"score": 0.9283673167228699,
"start": 18079,
"tag": "USERNAME",
"value": "'@hubot"
},
{
"context": " {\n \"text\": \"<https://twitter.com/twitterapi/status/850007368138018817>\",\n \"unfur",
"end": 18204,
"score": 0.8773432970046997,
"start": 18194,
"tag": "USERNAME",
"value": "twitterapi"
}
] | test/hockey-slack_test.coffee | stephenyeargin/hubot-hockey | 0 | Helper = require('hubot-test-helper')
chai = require 'chai'
nock = require 'nock'
expect = chai.expect
helper = new Helper [
'adapters/slack.coffee'
'../src/hockey.coffee'
]
# Alter time as test runs
originalDateNow = Date.now
describe 'hubot-hockey for slack', ->
beforeEach ->
process.env.HUBOT_LOG_LEVEL='error'
process.env.HUBOT_TWITTER_CONSUMER_KEY='foobarbaz'
process.env.HUBOT_TWITTER_CONSUMER_SECRET='foobarbaz'
process.env.HUBOT_TWITTER_ACCESS_TOKEN='foobarbaz'
process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET='foobarbaz'
nock.disableNetConnect()
@room = helper.createRoom()
afterEach ->
delete process.env.HUBOT_LOG_LEVEL
delete process.env.HUBOT_TWITTER_CONSUMER_KEY
delete process.env.HUBOT_TWITTER_CONSUMER_SECRET
delete process.env.HUBOT_TWITTER_ACCESS_TOKEN
delete process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET
Date.now = originalDateNow
nock.cleanAll()
@room.destroy()
it 'responds with a completed game and playoff odds', (done) ->
Date.now = () ->
return Date.parse('Thu Oct 10 23:59:00 CDT 2019')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 18,
startDate: '2019-10-10',
endDate: '2020-01-08',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-18-final.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds']
[
'hubot',
{
"attachments": [
{
"fallback": "10/10/2019 - Washington Capitals 5, Nashville Predators 6 (Final)",
"title_link": "https://www.nhl.com/gamecenter/2019020052",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#FFB81C",
"title": "10/10/2019 - Final",
"text": "```\n Washington Capitals (2-1-2) 5 \n Nashville Predators (3-1-0) 6 \n```",
"footer": "Bridgestone Arena",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Make Playoffs: 67.5% / Win Stanley Cup: 4.2%",
"author_name": "MoneyPuck.com",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#FFB81C",
"title": "Nashville Predators",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/NSH.png",
"fields": [
{
"title": "Make Playoffs",
"value": "67.5%",
"short": false
},
{
"title": "Win Stanley Cup",
"value": "4.2%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with a completed game that went to overtime and playoff odds', (done) ->
Date.now = () ->
return Date.parse('Thu Dec 19 09:42:00 CST 2019')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 18,
startDate: '2019-12-19',
endDate: '2020-03-18',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-18-final-ot.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds']
[
'hubot',
{
"attachments": [
{
"fallback": "12/19/2019 - Nashville Predators 4, Ottawa Senators 5 (Final/OT)",
"title_link": "https://www.nhl.com/gamecenter/2019020542",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#FFB81C",
"title": "12/19/2019 - Final/OT",
"text": "```\n Nashville Predators (16-12-6) 4 \n Ottawa Senators (15-18-3) 5 \n```",
"footer": "Canadian Tire Centre",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Make Playoffs: 67.5% / Win Stanley Cup: 4.2%",
"author_name": "MoneyPuck.com",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#FFB81C",
"title": "Nashville Predators",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/NSH.png",
"fields": [
{
"title": "Make Playoffs",
"value": "67.5%",
"short": false
},
{
"title": "Win Stanley Cup",
"value": "4.2%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with a completed game that went to multiple overtimes and playoff odds', (done) ->
Date.now = () ->
return Date.parse('Tue Aug 11 21:42:00 CDT 2020')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 14,
startDate: '2020-08-11',
endDate: '2020-11-09',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-14-final-5ot.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot bolts')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bolts']
[
'hubot',
{
"attachments": [
{
"fallback": "8/11/2020 - Columbus Blue Jackets 2, Tampa Bay Lightning 3 (Final/5OT - Lighting lead 1-0)",
"title_link": "https://www.nhl.com/gamecenter/2019030121",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#002868",
"title": "8/11/2020 - Final/5OT - Lighting lead 1-0",
"text": "```\n Columbus Blue Jackets (3-3-0) 2 \n Tampa Bay Lightning (3-1-0) 3 \n```",
"footer": "Scotiabank Arena",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Make Playoffs: 74.3% / Win Stanley Cup: 5.4%",
"author_name": "MoneyPuck.com",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#002868",
"title": "Tampa Bay Lightning",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/TBL.png",
"fields": [
{
"title": "Make Playoffs",
"value": "74.3%",
"short": false
},
{
"title": "Win Stanley Cup",
"value": "5.4%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with an in-progress game and playoff odds', (done) ->
Date.now = () ->
Date.parse('Tue Oct 15 17:40:00 CDT 2019')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 18,
startDate: '2019-10-15',
endDate: '2020-01-13',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-18-future.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds']
[
'hubot',
{
"attachments": [
{
"fallback": "10/15/2019 - Nashville Predators 0, Vegas Golden Knights 0 (9:00 pm CDT)",
"title_link": "https://www.nhl.com/gamecenter/2019020090",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#FFB81C",
"title": "10/15/2019 - 9:00 pm CDT",
"text": "```\n Nashville Predators (3-2-0) 0 \n Vegas Golden Knights (4-2-0) 0 \n```",
"footer": "T-Mobile Arena; TV: ESPN+ (national) | ATTSN-RM (home) | FS-TN (away)",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Make Playoffs: 67.5% / Win Stanley Cup: 4.2%",
"author_name": "MoneyPuck.com",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#FFB81C",
"title": "Nashville Predators",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/NSH.png",
"fields": [
{
"title": "Make Playoffs",
"value": "67.5%",
"short": false
},
{
"title": "Win Stanley Cup",
"value": "4.2%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with a future game and playoff odds', (done) ->
Date.now = () ->
Date.parse('Sat Oct 12 17:40:00 CDT 2019')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 18,
startDate: '2019-10-12',
endDate: '2020-01-10',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-18-in-progress.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds']
[
'hubot',
{
"attachments": [
{
"fallback": "10/12/2019 - Nashville Predators 1, Los Angeles Kings 2 (04:23 1st)",
"title_link": "https://www.nhl.com/gamecenter/2019020063",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#FFB81C",
"title": "10/12/2019 - 04:23 1st",
"text": "```\n Nashville Predators (3-1-0) 1 \n Los Angeles Kings (1-2-0) 2 \n```",
"footer": "STAPLES Center; TV: FS-W (home) | FS-TN (away)",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Make Playoffs: 67.5% / Win Stanley Cup: 4.2%",
"author_name": "MoneyPuck.com",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#FFB81C",
"title": "Nashville Predators",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/NSH.png",
"fields": [
{
"title": "Make Playoffs",
"value": "67.5%",
"short": false
},
{
"title": "Win Stanley Cup",
"value": "4.2%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with a scheduled preseason game and odds', (done) ->
Date.now = () ->
Date.parse('Wed Jul 22 17:40:00 CDT 2020')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 18,
startDate: '2020-07-22',
endDate: '2020-10-20',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-18-playoff.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent-playoffs.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds']
[
'hubot',
{
"attachments": [
{
"fallback": "7/30/2020 - Nashville Predators 0, Dallas Stars 0 (3:00 pm CDT - Preseason)",
"title_link": "https://www.nhl.com/gamecenter/2019011010",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#FFB81C",
"title": "7/30/2020 - 3:00 pm CDT - Preseason",
"text": "```\n Nashville Predators (0-0) 0 \n Dallas Stars (0-0) 0 \n```",
"footer": "Rogers Place; TV: NHLN (national) | FS-SW (home) | FS-TN (away)",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Win Stanley Cup: 1.6%",
"author_name": "MoneyPuck.com",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#FFB81C",
"title": "Nashville Predators",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/NSH.png",
"fields": [
{
"title": "Win Stanley Cup",
"value": "1.6%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with a team\'s latest tweet', (done) ->
nock('https://api.twitter.com')
.get('/1.1/statuses/user_timeline.json?screen_name=predsnhl')
.replyWithFile(200, __dirname + '/fixtures/twitter-predsnhl.json')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds twitter')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds twitter']
[
'hubot',
{
"text": "<https://twitter.com/twitterapi/status/850007368138018817>",
"unfurl_links": true
}
]
]
done()
catch err
done err
return
, 1000)
| 87171 | Helper = require('hubot-test-helper')
chai = require 'chai'
nock = require 'nock'
expect = chai.expect
helper = new Helper [
'adapters/slack.coffee'
'../src/hockey.coffee'
]
# Alter time as test runs
originalDateNow = Date.now
describe 'hubot-hockey for slack', ->
beforeEach ->
process.env.HUBOT_LOG_LEVEL='error'
process.env.HUBOT_TWITTER_CONSUMER_KEY='<KEY>'
process.env.HUBOT_TWITTER_CONSUMER_SECRET='<KEY>'
process.env.HUBOT_TWITTER_ACCESS_TOKEN='<KEY>'
process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET='<KEY>'
nock.disableNetConnect()
@room = helper.createRoom()
afterEach ->
delete process.env.HUBOT_LOG_LEVEL
delete process.env.HUBOT_TWITTER_CONSUMER_KEY
delete process.env.HUBOT_TWITTER_CONSUMER_SECRET
delete process.env.HUBOT_TWITTER_ACCESS_TOKEN
delete process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET
Date.now = originalDateNow
nock.cleanAll()
@room.destroy()
it 'responds with a completed game and playoff odds', (done) ->
Date.now = () ->
return Date.parse('Thu Oct 10 23:59:00 CDT 2019')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 18,
startDate: '2019-10-10',
endDate: '2020-01-08',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-18-final.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds']
[
'hubot',
{
"attachments": [
{
"fallback": "10/10/2019 - Washington Capitals 5, Nashville Predators 6 (Final)",
"title_link": "https://www.nhl.com/gamecenter/2019020052",
"author_name": "N<EMAIL>",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#FFB81C",
"title": "10/10/2019 - Final",
"text": "```\n Washington Capitals (2-1-2) 5 \n Nashville Predators (3-1-0) 6 \n```",
"footer": "Bridgestone Arena",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Make Playoffs: 67.5% / Win Stanley Cup: 4.2%",
"author_name": "<EMAIL>",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#FFB81C",
"title": "Nashville Predators",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/NSH.png",
"fields": [
{
"title": "Make Playoffs",
"value": "67.5%",
"short": false
},
{
"title": "Win Stanley Cup",
"value": "4.2%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with a completed game that went to overtime and playoff odds', (done) ->
Date.now = () ->
return Date.parse('Thu Dec 19 09:42:00 CST 2019')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 18,
startDate: '2019-12-19',
endDate: '2020-03-18',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-18-final-ot.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds']
[
'hubot',
{
"attachments": [
{
"fallback": "12/19/2019 - Nashville Predators 4, Ottawa Senators 5 (Final/OT)",
"title_link": "https://www.nhl.com/gamecenter/2019020542",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#FFB81C",
"title": "12/19/2019 - Final/OT",
"text": "```\n Nashville Predators (16-12-6) 4 \n Ottawa Senators (15-18-3) 5 \n```",
"footer": "Canadian Tire Centre",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Make Playoffs: 67.5% / Win Stanley Cup: 4.2%",
"author_name": "<EMAIL>",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#FFB81C",
"title": "Nashville Predators",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/NSH.png",
"fields": [
{
"title": "Make Playoffs",
"value": "67.5%",
"short": false
},
{
"title": "Win Stanley Cup",
"value": "4.2%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with a completed game that went to multiple overtimes and playoff odds', (done) ->
Date.now = () ->
return Date.parse('Tue Aug 11 21:42:00 CDT 2020')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 14,
startDate: '2020-08-11',
endDate: '2020-11-09',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-14-final-5ot.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot bolts')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bolts']
[
'hubot',
{
"attachments": [
{
"fallback": "8/11/2020 - Columbus Blue Jackets 2, Tampa Bay Lightning 3 (Final/5OT - Lighting lead 1-0)",
"title_link": "https://www.nhl.com/gamecenter/2019030121",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#002868",
"title": "8/11/2020 - Final/5OT - Lighting lead 1-0",
"text": "```\n Columbus Blue Jackets (3-3-0) 2 \n Tampa Bay Lightning (3-1-0) 3 \n```",
"footer": "Scotiabank Arena",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Make Playoffs: 74.3% / Win Stanley Cup: 5.4%",
"author_name": "Money<EMAIL>",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#002868",
"title": "Tampa Bay Lightning",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/TBL.png",
"fields": [
{
"title": "Make Playoffs",
"value": "74.3%",
"short": false
},
{
"title": "Win Stanley Cup",
"value": "5.4%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with an in-progress game and playoff odds', (done) ->
Date.now = () ->
Date.parse('Tue Oct 15 17:40:00 CDT 2019')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 18,
startDate: '2019-10-15',
endDate: '2020-01-13',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-18-future.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds']
[
'hubot',
{
"attachments": [
{
"fallback": "10/15/2019 - Nashville Predators 0, Vegas Golden Knights 0 (9:00 pm CDT)",
"title_link": "https://www.nhl.com/gamecenter/2019020090",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#FFB81C",
"title": "10/15/2019 - 9:00 pm CDT",
"text": "```\n Nashville Predators (3-2-0) 0 \n Vegas Golden Knights (4-2-0) 0 \n```",
"footer": "T-Mobile Arena; TV: ESPN+ (national) | ATTSN-RM (home) | FS-TN (away)",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Make Playoffs: 67.5% / Win Stanley Cup: 4.2%",
"author_name": "Money<EMAIL>",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#FFB81C",
"title": "Nashville Predators",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/NSH.png",
"fields": [
{
"title": "Make Playoffs",
"value": "67.5%",
"short": false
},
{
"title": "Win Stanley Cup",
"value": "4.2%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with a future game and playoff odds', (done) ->
Date.now = () ->
Date.parse('Sat Oct 12 17:40:00 CDT 2019')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 18,
startDate: '2019-10-12',
endDate: '2020-01-10',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-18-in-progress.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds']
[
'hubot',
{
"attachments": [
{
"fallback": "10/12/2019 - Nashville Predators 1, Los Angeles Kings 2 (04:23 1st)",
"title_link": "https://www.nhl.com/gamecenter/2019020063",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#FFB81C",
"title": "10/12/2019 - 04:23 1st",
"text": "```\n Nashville Predators (3-1-0) 1 \n Los Angeles Kings (1-2-0) 2 \n```",
"footer": "STAPLES Center; TV: FS-W (home) | FS-TN (away)",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Make Playoffs: 67.5% / Win Stanley Cup: 4.2%",
"author_name": "MoneyPuck.<EMAIL>",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#FFB81C",
"title": "Nashville Predators",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/NSH.png",
"fields": [
{
"title": "Make Playoffs",
"value": "67.5%",
"short": false
},
{
"title": "Win Stanley Cup",
"value": "4.2%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with a scheduled preseason game and odds', (done) ->
Date.now = () ->
Date.parse('Wed Jul 22 17:40:00 CDT 2020')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 18,
startDate: '2020-07-22',
endDate: '2020-10-20',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-18-playoff.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent-playoffs.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds']
[
'hubot',
{
"attachments": [
{
"fallback": "7/30/2020 - Nashville Predators 0, Dallas Stars 0 (3:00 pm CDT - Preseason)",
"title_link": "https://www.nhl.com/gamecenter/2019011010",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#FFB81C",
"title": "7/30/2020 - 3:00 pm CDT - Preseason",
"text": "```\n Nashville Predators (0-0) 0 \n Dallas Stars (0-0) 0 \n```",
"footer": "Rogers Place; TV: NHLN (national) | FS-SW (home) | FS-TN (away)",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Win Stanley Cup: 1.6%",
"author_name": "<EMAIL>",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#FFB81C",
"title": "Nashville Predators",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/NSH.png",
"fields": [
{
"title": "Win Stanley Cup",
"value": "1.6%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with a team\'s latest tweet', (done) ->
nock('https://api.twitter.com')
.get('/1.1/statuses/user_timeline.json?screen_name=predsnhl')
.replyWithFile(200, __dirname + '/fixtures/twitter-predsnhl.json')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds twitter')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds twitter']
[
'hubot',
{
"text": "<https://twitter.com/twitterapi/status/850007368138018817>",
"unfurl_links": true
}
]
]
done()
catch err
done err
return
, 1000)
| true | Helper = require('hubot-test-helper')
chai = require 'chai'
nock = require 'nock'
expect = chai.expect
helper = new Helper [
'adapters/slack.coffee'
'../src/hockey.coffee'
]
# Alter time as test runs
originalDateNow = Date.now
describe 'hubot-hockey for slack', ->
beforeEach ->
process.env.HUBOT_LOG_LEVEL='error'
process.env.HUBOT_TWITTER_CONSUMER_KEY='PI:KEY:<KEY>END_PI'
process.env.HUBOT_TWITTER_CONSUMER_SECRET='PI:KEY:<KEY>END_PI'
process.env.HUBOT_TWITTER_ACCESS_TOKEN='PI:PASSWORD:<KEY>END_PI'
process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET='PI:KEY:<KEY>END_PI'
nock.disableNetConnect()
@room = helper.createRoom()
afterEach ->
delete process.env.HUBOT_LOG_LEVEL
delete process.env.HUBOT_TWITTER_CONSUMER_KEY
delete process.env.HUBOT_TWITTER_CONSUMER_SECRET
delete process.env.HUBOT_TWITTER_ACCESS_TOKEN
delete process.env.HUBOT_TWITTER_ACCESS_TOKEN_SECRET
Date.now = originalDateNow
nock.cleanAll()
@room.destroy()
it 'responds with a completed game and playoff odds', (done) ->
Date.now = () ->
return Date.parse('Thu Oct 10 23:59:00 CDT 2019')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 18,
startDate: '2019-10-10',
endDate: '2020-01-08',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-18-final.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds']
[
'hubot',
{
"attachments": [
{
"fallback": "10/10/2019 - Washington Capitals 5, Nashville Predators 6 (Final)",
"title_link": "https://www.nhl.com/gamecenter/2019020052",
"author_name": "NPI:EMAIL:<EMAIL>END_PI",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#FFB81C",
"title": "10/10/2019 - Final",
"text": "```\n Washington Capitals (2-1-2) 5 \n Nashville Predators (3-1-0) 6 \n```",
"footer": "Bridgestone Arena",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Make Playoffs: 67.5% / Win Stanley Cup: 4.2%",
"author_name": "PI:EMAIL:<EMAIL>END_PI",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#FFB81C",
"title": "Nashville Predators",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/NSH.png",
"fields": [
{
"title": "Make Playoffs",
"value": "67.5%",
"short": false
},
{
"title": "Win Stanley Cup",
"value": "4.2%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with a completed game that went to overtime and playoff odds', (done) ->
Date.now = () ->
return Date.parse('Thu Dec 19 09:42:00 CST 2019')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 18,
startDate: '2019-12-19',
endDate: '2020-03-18',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-18-final-ot.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds']
[
'hubot',
{
"attachments": [
{
"fallback": "12/19/2019 - Nashville Predators 4, Ottawa Senators 5 (Final/OT)",
"title_link": "https://www.nhl.com/gamecenter/2019020542",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#FFB81C",
"title": "12/19/2019 - Final/OT",
"text": "```\n Nashville Predators (16-12-6) 4 \n Ottawa Senators (15-18-3) 5 \n```",
"footer": "Canadian Tire Centre",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Make Playoffs: 67.5% / Win Stanley Cup: 4.2%",
"author_name": "PI:EMAIL:<EMAIL>END_PI",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#FFB81C",
"title": "Nashville Predators",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/NSH.png",
"fields": [
{
"title": "Make Playoffs",
"value": "67.5%",
"short": false
},
{
"title": "Win Stanley Cup",
"value": "4.2%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with a completed game that went to multiple overtimes and playoff odds', (done) ->
Date.now = () ->
return Date.parse('Tue Aug 11 21:42:00 CDT 2020')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 14,
startDate: '2020-08-11',
endDate: '2020-11-09',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-14-final-5ot.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot bolts')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot bolts']
[
'hubot',
{
"attachments": [
{
"fallback": "8/11/2020 - Columbus Blue Jackets 2, Tampa Bay Lightning 3 (Final/5OT - Lighting lead 1-0)",
"title_link": "https://www.nhl.com/gamecenter/2019030121",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#002868",
"title": "8/11/2020 - Final/5OT - Lighting lead 1-0",
"text": "```\n Columbus Blue Jackets (3-3-0) 2 \n Tampa Bay Lightning (3-1-0) 3 \n```",
"footer": "Scotiabank Arena",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Make Playoffs: 74.3% / Win Stanley Cup: 5.4%",
"author_name": "MoneyPI:EMAIL:<EMAIL>END_PI",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#002868",
"title": "Tampa Bay Lightning",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/TBL.png",
"fields": [
{
"title": "Make Playoffs",
"value": "74.3%",
"short": false
},
{
"title": "Win Stanley Cup",
"value": "5.4%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with an in-progress game and playoff odds', (done) ->
Date.now = () ->
Date.parse('Tue Oct 15 17:40:00 CDT 2019')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 18,
startDate: '2019-10-15',
endDate: '2020-01-13',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-18-future.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds']
[
'hubot',
{
"attachments": [
{
"fallback": "10/15/2019 - Nashville Predators 0, Vegas Golden Knights 0 (9:00 pm CDT)",
"title_link": "https://www.nhl.com/gamecenter/2019020090",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#FFB81C",
"title": "10/15/2019 - 9:00 pm CDT",
"text": "```\n Nashville Predators (3-2-0) 0 \n Vegas Golden Knights (4-2-0) 0 \n```",
"footer": "T-Mobile Arena; TV: ESPN+ (national) | ATTSN-RM (home) | FS-TN (away)",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Make Playoffs: 67.5% / Win Stanley Cup: 4.2%",
"author_name": "MoneyPI:EMAIL:<EMAIL>END_PI",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#FFB81C",
"title": "Nashville Predators",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/NSH.png",
"fields": [
{
"title": "Make Playoffs",
"value": "67.5%",
"short": false
},
{
"title": "Win Stanley Cup",
"value": "4.2%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with a future game and playoff odds', (done) ->
Date.now = () ->
Date.parse('Sat Oct 12 17:40:00 CDT 2019')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 18,
startDate: '2019-10-12',
endDate: '2020-01-10',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-18-in-progress.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds']
[
'hubot',
{
"attachments": [
{
"fallback": "10/12/2019 - Nashville Predators 1, Los Angeles Kings 2 (04:23 1st)",
"title_link": "https://www.nhl.com/gamecenter/2019020063",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#FFB81C",
"title": "10/12/2019 - 04:23 1st",
"text": "```\n Nashville Predators (3-1-0) 1 \n Los Angeles Kings (1-2-0) 2 \n```",
"footer": "STAPLES Center; TV: FS-W (home) | FS-TN (away)",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Make Playoffs: 67.5% / Win Stanley Cup: 4.2%",
"author_name": "MoneyPuck.PI:EMAIL:<EMAIL>END_PI",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#FFB81C",
"title": "Nashville Predators",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/NSH.png",
"fields": [
{
"title": "Make Playoffs",
"value": "67.5%",
"short": false
},
{
"title": "Win Stanley Cup",
"value": "4.2%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with a scheduled preseason game and odds', (done) ->
Date.now = () ->
Date.parse('Wed Jul 22 17:40:00 CDT 2020')
nock('https://statsapi.web.nhl.com')
.get('/api/v1/schedule')
.query({
teamId: 18,
startDate: '2020-07-22',
endDate: '2020-10-20',
hydrate: 'linescore,broadcasts(all),game(seriesSummary)'
})
.delay({
head: 100,
body: 200,
})
.replyWithFile(200, __dirname + '/fixtures/nhl-statsapi-team-18-playoff.json')
nock('https://moneypuck.com')
.get('/moneypuck/simulations/simulations_recent.csv')
.replyWithFile(200, __dirname + '/fixtures/moneypuck-simulations_recent-playoffs.csv')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds']
[
'hubot',
{
"attachments": [
{
"fallback": "7/30/2020 - Nashville Predators 0, Dallas Stars 0 (3:00 pm CDT - Preseason)",
"title_link": "https://www.nhl.com/gamecenter/2019011010",
"author_name": "NHL.com",
"author_link": "https://nhl.com",
"author_icon": "https://github.com/nhl.png",
"color": "#FFB81C",
"title": "7/30/2020 - 3:00 pm CDT - Preseason",
"text": "```\n Nashville Predators (0-0) 0 \n Dallas Stars (0-0) 0 \n```",
"footer": "Rogers Place; TV: NHLN (national) | FS-SW (home) | FS-TN (away)",
"mrkdwn_in": ["text", "pretext"]
}
]
}
]
[
'hubot',
{
"attachments": [
{
"fallback": "Odds to Win Stanley Cup: 1.6%",
"author_name": "PI:EMAIL:<EMAIL>END_PI",
"author_link": "https://moneypuck.com",
"author_icon": "http://peter-tanner.com/moneypuck/logos/moneypucklogo.png",
"color": "#FFB81C",
"title": "Nashville Predators",
"thumb_url": "http://peter-tanner.com/moneypuck/logos/NSH.png",
"fields": [
{
"title": "Win Stanley Cup",
"value": "1.6%",
"short": false
}
]
}
]
}
]
]
done()
catch err
done err
return
, 1000)
it 'responds with a team\'s latest tweet', (done) ->
nock('https://api.twitter.com')
.get('/1.1/statuses/user_timeline.json?screen_name=predsnhl')
.replyWithFile(200, __dirname + '/fixtures/twitter-predsnhl.json')
selfRoom = @room
selfRoom.user.say('alice', '@hubot preds twitter')
setTimeout(() ->
try
expect(selfRoom.messages).to.eql [
['alice', '@hubot preds twitter']
[
'hubot',
{
"text": "<https://twitter.com/twitterapi/status/850007368138018817>",
"unfurl_links": true
}
]
]
done()
catch err
done err
return
, 1000)
|
[
{
"context": "gradients = [\n {\n \"name\": \"Apple\",\n \"css\": \"background-image: linear-gradient(-",
"end": 36,
"score": 0.999061644077301,
"start": 31,
"tag": "NAME",
"value": "Apple"
},
{
"context": "eg, #b3b3b3 0%, #999 100%);\"\n }\n {\n \"name\": \"Blogger\",\n \"css\": \"background-image: linear-gradient(-",
"end": 147,
"score": 0.9960312843322754,
"start": 140,
"tag": "NAME",
"value": "Blogger"
},
{
"context": " #ff8000 0%, #ff9933 100%);\"\n }\n {\n \"name\": \"Digg\",\n \"css\": \"background-image: linear-gradient(-",
"end": 258,
"score": 0.9969710111618042,
"start": 254,
"tag": "NAME",
"value": "Digg"
},
{
"context": " #262626 0%, #404040 100%);\"\n }\n {\n \"name\": \"Dailymotion\",\n \"css\": \"background-image: linear-gradient(-",
"end": 376,
"score": 0.9958608150482178,
"start": 365,
"tag": "NAME",
"value": "Dailymotion"
},
{
"context": " #0066dc 0%, #107fff 100%);\"\n }\n {\n \"name\": \"Facebook\",\n \"css\": \"background-image: linear-gradient(-",
"end": 491,
"score": 0.9955216646194458,
"start": 483,
"tag": "NAME",
"value": "Facebook"
},
{
"context": " #3b5998 0%, #4c70ba 100%);\"\n }\n {\n \"name\": \"Flipboard\",\n \"css\": \"background-image: linear-gradient(-",
"end": 607,
"score": 0.9972619414329529,
"start": 598,
"tag": "NAME",
"value": "Flipboard"
},
{
"context": " #e12828 0%, #e75555 100%);\"\n }\n {\n \"name\": \"Github\",\n \"css\": \"background-image: linear-gradient(-",
"end": 720,
"score": 0.7753063440322876,
"start": 714,
"tag": "NAME",
"value": "Github"
},
{
"context": " #dc4e41 0%, #e4766c 100%);\"\n }\n {\n \"name\": \"LinkedIn\",\n \"css\": \"background-image: linear-gradient(-",
"end": 952,
"score": 0.9658691883087158,
"start": 944,
"tag": "NAME",
"value": "LinkedIn"
},
{
"context": " #0077b5 0%, #0099e8 100%);\"\n }\n {\n \"name\": \"LiveJournal\",\n \"css\": \"background-image: linear-gradient(-",
"end": 1070,
"score": 0.8392019867897034,
"start": 1059,
"tag": "NAME",
"value": "LiveJournal"
},
{
"context": " #00b0ea 0%, #1ec7ff 100%);\"\n }\n {\n \"name\": \"Odnoklassniki\",\n \"css\": \"background-image: linear-gradient(-",
"end": 1190,
"score": 0.9941787719726562,
"start": 1177,
"tag": "NAME",
"value": "Odnoklassniki"
},
{
"context": " #25d366 0%, #4be083 100%);\"\n }\n {\n \"name\": \"Xing\",\n \"css\": \"background-image: linear-gradient(-",
"end": 2320,
"score": 0.9955110549926758,
"start": 2316,
"tag": "NAME",
"value": "Xing"
},
{
"context": " #1a7576 0%, #239ea0 100%);\"\n }\n {\n \"name\": \"Yahoo\",\n \"css\": \"background-image: linear-gradient(-",
"end": 2432,
"score": 0.9941409826278687,
"start": 2427,
"tag": "NAME",
"value": "Yahoo"
},
{
"context": " #720e9e 0%, #9412cd 100%);\"\n }\n {\n \"name\": \"Youtube\",\n \"css\": \"background-image: linear-gradient(-",
"end": 2546,
"score": 0.9835720658302307,
"start": 2539,
"tag": "NAME",
"value": "Youtube"
},
{
"context": " #cd201f 0%, #e23e3d 100%);\"\n }\n {\n \"name\": \"Warm Flame\",\n \"css\": \"background-image: linear-g",
"end": 2654,
"score": 0.5219935178756714,
"start": 2653,
"tag": "NAME",
"value": "W"
},
{
"context": "20Night%20Fade.png\"\n },\n {\n \"name\": \"Spring Warmth\",\n \"css\": \"background-image: linear-gradient(t",
"end": 3074,
"score": 0.5186119675636292,
"start": 3069,
"tag": "NAME",
"value": "armth"
},
{
"context": "/003%20Spring%20Warmth.png\"\n },\n {\n \"name\": \"Juicy Peach\",\n \"css\": \"background-image: linear-g",
"end": 3279,
"score": 0.5608300566673279,
"start": 3277,
"tag": "NAME",
"value": "Ju"
},
{
"context": "Spring%20Warmth.png\"\n },\n {\n \"name\": \"Juicy Peach\",\n \"css\": \"background-image: linear-gradient(t",
"end": 3288,
"score": 0.5612665414810181,
"start": 3284,
"tag": "NAME",
"value": "each"
},
{
"context": "ng/004%20Juicy%20Peach.png\"\n },\n {\n \"name\": \"Young Passion\",\n \"css\": \"background-image: linear-gradient(t",
"end": 3492,
"score": 0.9915330410003662,
"start": 3479,
"tag": "NAME",
"value": "Young Passion"
},
{
"context": "/005%20Young%20Passion.png\"\n },\n {\n \"name\": \"Lady Lips\",\n \"css\": \"background-image: linear-gradient(t",
"end": 3745,
"score": 0.9995100498199463,
"start": 3736,
"tag": "NAME",
"value": "Lady Lips"
},
{
"context": "_png/006%20Lady%20Lips.png\"\n },\n {\n \"name\": \"Sunny Morning\",\n \"css\": \"background-image: linear-gradient(1",
"end": 3958,
"score": 0.9980534315109253,
"start": 3945,
"tag": "NAME",
"value": "Sunny Morning"
},
{
"context": "/007%20Sunny%20Morning.png\"\n },\n {\n \"name\": \"Rainy Ashville\",\n \"css\": \"background-image: linear-gradient(t",
"end": 4163,
"score": 0.9997025728225708,
"start": 4149,
"tag": "NAME",
"value": "Rainy Ashville"
},
{
"context": "008%20Rainy%20Ashville.png\"\n },\n {\n \"name\": \"Frozen Dreams\",\n \"css\": \"background-image: linear-gradient(t",
"end": 4368,
"score": 0.9991264939308167,
"start": 4355,
"tag": "NAME",
"value": "Frozen Dreams"
},
{
"context": "/009%20Frozen%20Dreams.png\"\n },\n {\n \"name\": \"Winter Neva\",\n \"css\": \"background-image: linear-gradient(1",
"end": 4582,
"score": 0.9998685717582703,
"start": 4571,
"tag": "NAME",
"value": "Winter Neva"
},
{
"context": "ng/010%20Winter%20Neva.png\"\n },\n {\n \"name\": \"Dusty Grass\",\n \"css\": \"background-image: linear-gradient(1",
"end": 4782,
"score": 0.9993521571159363,
"start": 4771,
"tag": "NAME",
"value": "Dusty Grass"
},
{
"context": "ng/011%20Dusty%20Grass.png\"\n },\n {\n \"name\": \"Tempting Azure\",\n \"css\": \"background-image: linear-gradient(1",
"end": 4985,
"score": 0.9754345417022705,
"start": 4971,
"tag": "NAME",
"value": "Tempting Azure"
},
{
"context": "012%20Tempting%20Azure.png\"\n },\n {\n \"name\": \"Heavy Rain\",\n \"css\": \"background-image: linear-gradient(t",
"end": 5187,
"score": 0.9913962483406067,
"start": 5177,
"tag": "NAME",
"value": "Heavy Rain"
},
{
"context": "png/013%20Heavy%20Rain.png\"\n },\n {\n \"name\": \"Amy Crisp\",\n \"css\": \"background-image: linear-gradient(1",
"end": 5384,
"score": 0.9993923902511597,
"start": 5375,
"tag": "NAME",
"value": "Amy Crisp"
},
{
"context": "_png/014%20Amy%20Crisp.png\"\n },\n {\n \"name\": \"Mean Fruit\",\n \"css\": \"background-image: linear-gradient(1",
"end": 5581,
"score": 0.9954107403755188,
"start": 5571,
"tag": "NAME",
"value": "Mean Fruit"
},
{
"context": "png/015%20Mean%20Fruit.png\"\n },\n {\n \"name\": \"Deep Blue\",\n \"css\": \"background-image: linear-gradient(1",
"end": 5778,
"score": 0.9947649240493774,
"start": 5769,
"tag": "NAME",
"value": "Deep Blue"
},
{
"context": "_png/016%20Deep%20Blue.png\"\n },\n {\n \"name\": \"Ripe Malinka\",\n \"css\": \"background-image: linear-gradient(1",
"end": 5977,
"score": 0.9998793601989746,
"start": 5965,
"tag": "NAME",
"value": "Ripe Malinka"
},
{
"context": "g/017%20Ripe%20Malinka.png\"\n },\n {\n \"name\": \"Cloudy Knoxville\",\n \"css\": \"background-image: linear-gradient(1",
"end": 6183,
"score": 0.9984648823738098,
"start": 6167,
"tag": "NAME",
"value": "Cloudy Knoxville"
},
{
"context": "8%20Cloudy%20Knoxville.png\"\n },\n {\n \"name\": \"Malibu Beach\",\n \"css\": \"background-image: linear-gradient(t",
"end": 6389,
"score": 0.998405933380127,
"start": 6377,
"tag": "NAME",
"value": "Malibu Beach"
},
{
"context": "g/019%20Malibu%20Beach.png\"\n },\n {\n \"name\": \"New Life\",\n \"css\": \"background-image: linear-gradient(t",
"end": 6589,
"score": 0.9618625640869141,
"start": 6581,
"tag": "NAME",
"value": "New Life"
},
{
"context": "ng/021%20True%20Sunset.png\"\n },\n {\n \"name\": \"Morpheus Den\",\n \"css\": \"background-image: linear-gradient(t",
"end": 6991,
"score": 0.9758589863777161,
"start": 6979,
"tag": "NAME",
"value": "Morpheus Den"
},
{
"context": "g/022%20Morpheus%20Den.png\"\n },\n {\n \"name\": \"Rare Wind\",\n \"css\": \"background-image: linear-gradient(t",
"end": 7190,
"score": 0.915259063243866,
"start": 7181,
"tag": "NAME",
"value": "Rare Wind"
},
{
"context": "_png/024%20Near%20Moon.png\"\n },\n {\n \"name\": \"Wild Apple\",\n \"css\": \"background-image: linear-gradient(t",
"end": 7583,
"score": 0.9225496649742126,
"start": 7573,
"tag": "NAME",
"value": "Wild Apple"
},
{
"context": "png/025%20Wild%20Apple.png\"\n },\n {\n \"name\": \"Saint Petersburg\",\n \"css\": \"background-image: linear-gradient(1",
"end": 7787,
"score": 0.9944241642951965,
"start": 7771,
"tag": "NAME",
"value": "Saint Petersburg"
},
{
"context": "6%20Saint%20Petersburg.png\"\n },\n {\n \"name\": \"Arielle's Smile\",\n \"css\": \"background-image: radial-gradient(c",
"end": 7996,
"score": 0.9993782639503479,
"start": 7981,
"tag": "NAME",
"value": "Arielle's Smile"
},
{
"context": "27%20Arielle's%20Smile.png\"\n },\n {\n \"name\": \"Plum Plate\",\n \"css\": \"background-image: linear-gradient(1",
"end": 8228,
"score": 0.9917757511138916,
"start": 8218,
"tag": "NAME",
"value": "Plum Plate"
},
{
"context": "png/028%20Plum%20Plate.png\"\n },\n {\n \"name\": \"Everlasting Sky\",\n \"css\": \"background-image: linear-gradient(1",
"end": 8431,
"score": 0.990981936454773,
"start": 8416,
"tag": "NAME",
"value": "Everlasting Sky"
},
{
"context": "29%20Everlasting%20Sky.png\"\n },\n {\n \"name\": \"Happy Fisher\",\n \"css\": \"background-image: linear-gradient(1",
"end": 8636,
"score": 0.996260404586792,
"start": 8624,
"tag": "NAME",
"value": "Happy Fisher"
},
{
"context": "g/030%20Happy%20Fisher.png\"\n },\n {\n \"name\": \"Blessing\",\n \"css\": \"background-image: linear-gradient(t",
"end": 8834,
"score": 0.997974157333374,
"start": 8826,
"tag": "NAME",
"value": "Blessing"
},
{
"context": "nts_png/031%20Blessing.png\"\n },\n {\n \"name\": \"Sharpeye Eagle\",\n \"css\": \"background-image: linear-gradient(t",
"end": 9032,
"score": 0.9983860850334167,
"start": 9018,
"tag": "NAME",
"value": "Sharpeye Eagle"
},
{
"context": "032%20Sharpeye%20Eagle.png\"\n },\n {\n \"name\": \"Ladoga Bottom\",\n \"css\": \"background-image: linear-gradient(t",
"end": 9237,
"score": 0.9988894462585449,
"start": 9224,
"tag": "NAME",
"value": "Ladoga Bottom"
},
{
"context": "/033%20Ladoga%20Bottom.png\"\n },\n {\n \"name\": \"Lemon Gate\",\n \"css\": \"background-image: linear-gradient(t",
"end": 9438,
"score": 0.7195659279823303,
"start": 9428,
"tag": "NAME",
"value": "Lemon Gate"
},
{
"context": "035%20Itmeo%20Branding.png\"\n },\n {\n \"name\": \"Zeus Miracle\",\n \"css\": \"background-image: linear-gradient(t",
"end": 9844,
"score": 0.8791002631187439,
"start": 9832,
"tag": "NAME",
"value": "Zeus Miracle"
},
{
"context": "36%20Zeus%20Miracle.png\"\n },\n {\n \"name\": \"Old Hat\",\n \"css\": \"background-image: linear-gradient(t",
"end": 10041,
"score": 0.5682344436645508,
"start": 10038,
"tag": "NAME",
"value": "Hat"
},
{
"context": "ts_png/037%20Old%20Hat.png\"\n },\n {\n \"name\": \"Star Wine\",\n \"css\": \"background-image: linear-gradient(t",
"end": 10287,
"score": 0.8519322872161865,
"start": 10278,
"tag": "NAME",
"value": "Star Wine"
},
{
"context": "_png/038%20Star%20Wine.png\"\n },\n {\n \"name\": \"Deep Blue\",\n \"css\": \"background-image: linear-gradient(t",
"end": 10535,
"score": 0.9737733602523804,
"start": 10526,
"tag": "NAME",
"value": "Deep Blue"
},
{
"context": "_png/039%20Deep%20Blue.png\"\n },\n {\n \"name\": \"Coup de Grace\",\n \"css\": \"background-color: #DCD9D4; \\n backg",
"end": 10737,
"score": 0.9989964365959167,
"start": 10724,
"tag": "NAME",
"value": "Coup de Grace"
},
{
"context": "40%20Coup%20de%20Grace.png\"\n },\n {\n \"name\": \"Happy Acid\",\n \"css\": \"background-image: linear-gradient(t",
"end": 11119,
"score": 0.9984163641929626,
"start": 11109,
"tag": "NAME",
"value": "Happy Acid"
},
{
"context": "png/041%20Happy%20Acid.png\"\n },\n {\n \"name\": \"Awesome Pine\",\n \"css\": \"background-image: linear-gradient(t",
"end": 11319,
"score": 0.9985625147819519,
"start": 11307,
"tag": "NAME",
"value": "Awesome Pine"
},
{
"context": "s_png/043%20New%20York.png\"\n },\n {\n \"name\": \"Shy Rainbow\",\n \"css\": \"background-image: linear-gradient(t",
"end": 11714,
"score": 0.9955199956893921,
"start": 11703,
"tag": "NAME",
"value": "Shy Rainbow"
},
{
"context": "ng/044%20Shy%20Rainbow.png\"\n },\n {\n \"name\": \"Loon Crest\",\n \"css\": \"background: linear-gradient(to bott",
"end": 11954,
"score": 0.9960957765579224,
"start": 11944,
"tag": "NAME",
"value": "Loon Crest"
},
{
"context": "png/045%20Loon%20Crest.png\"\n },\n {\n \"name\": \"Mixed Hopes\",\n \"css\": \"background-image: linear-gradient(t",
"end": 12309,
"score": 0.9611279964447021,
"start": 12298,
"tag": "NAME",
"value": "Mixed Hopes"
},
{
"context": "ng/046%20Mixed%20Hopes.png\"\n },\n {\n \"name\": \"Fly High\",\n \"css\": \"background-image: linear-gradient(t",
"end": 12506,
"score": 0.9203280210494995,
"start": 12498,
"tag": "NAME",
"value": "Fly High"
},
{
"context": "s_png/047%20Fly%20High.png\"\n },\n {\n \"name\": \"Strong Bliss\",\n \"css\": \"background-image: linear-gradient(t",
"end": 12704,
"score": 0.905648410320282,
"start": 12692,
"tag": "NAME",
"value": "Strong Bliss"
},
{
"context": "g/048%20Strong%20Bliss.png\"\n },\n {\n \"name\": \"Fresh Milk\",\n \"css\": \"background-image: linear-gradient(t",
"end": 12932,
"score": 0.6997798085212708,
"start": 12922,
"tag": "NAME",
"value": "Fresh Milk"
},
{
"context": "png/049%20Fresh%20Milk.png\"\n },\n {\n \"name\": \"Snow Again\",\n \"css\": \"background-image: linear-gradient(t",
"end": 13130,
"score": 0.9529775381088257,
"start": 13120,
"tag": "NAME",
"value": "Snow Again"
},
{
"context": "png/050%20Snow%20Again.png\"\n },\n {\n \"name\": \"February Ink\",\n \"css\": \"background-image: linear-gradient(t",
"end": 13330,
"score": 0.9870119094848633,
"start": 13318,
"tag": "NAME",
"value": "February Ink"
},
{
"context": "g/051%20February%20Ink.png\"\n },\n {\n \"name\": \"Kind Steel\",\n \"css\": \"background-image: linear-gradient(-",
"end": 13530,
"score": 0.9853197932243347,
"start": 13520,
"tag": "NAME",
"value": "Kind Steel"
},
{
"context": "png/052%20Kind%20Steel.png\"\n },\n {\n \"name\": \"Soft Grass\",\n \"css\": \"background-image: linear-gradient(t",
"end": 13728,
"score": 0.6520134806632996,
"start": 13718,
"tag": "NAME",
"value": "Soft Grass"
},
{
"context": "png/053%20Soft%20Grass.png\"\n },\n {\n \"name\": \"Grown Early\",\n \"css\": \"background-image: linear-gradient(t",
"end": 13927,
"score": 0.5656664371490479,
"start": 13916,
"tag": "NAME",
"value": "Grown Early"
},
{
"context": "4%20Grown%20Early.png\"\n },\n {\n \"name\": \"Sharp Blues\",\n \"css\": \"background-image: linear-gradien",
"end": 14124,
"score": 0.5145111680030823,
"start": 14122,
"tag": "NAME",
"value": "Bl"
},
{
"context": "066%20Night%20Party.png\"\n },\n {\n \"name\": \"Sky Glider\",\n \"css\": \"background-image: linear-gradient(t",
"end": 16864,
"score": 0.5259478092193604,
"start": 16858,
"tag": "NAME",
"value": "Glider"
},
{
"context": "69%20Purple%20Division.png\"\n },\n {\n \"name\": \"Aqua Splash\",\n \"css\": \"background-image: linear-gradient(1",
"end": 17473,
"score": 0.7459935545921326,
"start": 17462,
"tag": "NAME",
"value": "Aqua Splash"
},
{
"context": "ng/070%20Aqua%20Splash.png\"\n },\n {\n \"name\": \"Above Clouds\",\n \"css\": \"background-image: linear-gradient(t",
"end": 17673,
"score": 0.8576822876930237,
"start": 17661,
"tag": "NAME",
"value": "Above Clouds"
},
{
"context": "00%),%20radial-gradien.png\"\n },\n {\n \"name\": \"Spiky Naga\",\n \"css\": \"background-image: linear-gradient(t",
"end": 18166,
"score": 0.9996596574783325,
"start": 18156,
"tag": "NAME",
"value": "Spiky Naga"
},
{
"context": "png/072%20Spiky%20Naga.png\"\n },\n {\n \"name\": \"Love Kiss\",\n \"css\": \"background-image: linear-gradient(t",
"end": 18454,
"score": 0.9998746514320374,
"start": 18445,
"tag": "NAME",
"value": "Love Kiss"
},
{
"context": "_png/073%20Love%20Kiss.png\"\n },\n {\n \"name\": \"Sharp Glass\",\n \"css\": \"background: #C9CCD3;\\n background-i",
"end": 18652,
"score": 0.9323380589485168,
"start": 18641,
"tag": "NAME",
"value": "Sharp Glass"
},
{
"context": "ng/074%20Sharp%20Glass.png\"\n },\n {\n \"name\": \"Clean Mirror\",\n \"css\": \"background-image: linear-gradient(4",
"end": 18935,
"score": 0.9118340611457825,
"start": 18923,
"tag": "NAME",
"value": "Clean Mirror"
},
{
"context": "g/076%20Premium%20Dark.png\"\n },\n {\n \"name\": \"Cold Evening\",\n \"css\": \"background-image: linear-gradient(t",
"end": 19338,
"score": 0.9951018691062927,
"start": 19326,
"tag": "NAME",
"value": "Cold Evening"
},
{
"context": "g/077%20Cold%20Evening.png\"\n },\n {\n \"name\": \"Cochiti Lake\",\n \"css\": \"background-image: linear-gradi",
"end": 19563,
"score": 0.6928191184997559,
"start": 19556,
"tag": "NAME",
"value": "Cochiti"
},
{
"context": "g/079%20Summer%20Games.png\"\n },\n {\n \"name\": \"Passionate Bed\",\n \"css\": \"background-image: linear-gradient(t",
"end": 19975,
"score": 0.7866194248199463,
"start": 19961,
"tag": "NAME",
"value": "Passionate Bed"
},
{
"context": "080%20Passionate%20Bed.png\"\n },\n {\n \"name\": \"Mountain Rock\",\n \"css\": \"background-image: linear-gradient(t",
"end": 20182,
"score": 0.7361562848091125,
"start": 20169,
"tag": "NAME",
"value": "Mountain Rock"
},
{
"context": "/081%20Mountain%20Rock.png\"\n },\n {\n \"name\": \"Desert Hump\",\n \"css\": \"background-image: linear-gradient(t",
"end": 20386,
"score": 0.9977099299430847,
"start": 20375,
"tag": "NAME",
"value": "Desert Hump"
},
{
"context": "ng/082%20Desert%20Hump.png\"\n },\n {\n \"name\": \"Jungle Day\",\n \"css\": \"background-image: linear-gradient(4",
"end": 20585,
"score": 0.783308207988739,
"start": 20575,
"tag": "NAME",
"value": "Jungle Day"
},
{
"context": "png/083%20Jungle%20Day.png\"\n },\n {\n \"name\": \"Phoenix Start\",\n \"css\": \"background-image: linear-gradient(t",
"end": 20785,
"score": 0.9793289303779602,
"start": 20772,
"tag": "NAME",
"value": "Phoenix Start"
},
{
"context": "/084%20Phoenix%20Start.png\"\n },\n {\n \"name\": \"October Silence\",\n \"css\": \"background-image: linear-gradient(-",
"end": 20993,
"score": 0.9844328761100769,
"start": 20978,
"tag": "NAME",
"value": "October Silence"
},
{
"context": "85%20October%20Silence.png\"\n },\n {\n \"name\": \"Faraway River\",\n \"css\": \"background-image: linear-gradient(-",
"end": 21199,
"score": 0.9953962564468384,
"start": 21186,
"tag": "NAME",
"value": "Faraway River"
},
{
"context": "/086%20Faraway%20River.png\"\n },\n {\n \"name\": \"Alchemist Lab\",\n \"css\": \"background-image: linear-gradient(-",
"end": 21403,
"score": 0.9792205095291138,
"start": 21390,
"tag": "NAME",
"value": "Alchemist Lab"
},
{
"context": "/087%20Alchemist%20Lab.png\"\n },\n {\n \"name\": \"Over Sun\",\n \"css\": \"background-image: linear-gradient(6",
"end": 21602,
"score": 0.9615411758422852,
"start": 21594,
"tag": "NAME",
"value": "Over Sun"
},
{
"context": "s_png/088%20Over%20Sun.png\"\n },\n {\n \"name\": \"Premium White\",\n \"css\": \"background-image: linear-gradient(t",
"end": 21800,
"score": 0.995821475982666,
"start": 21787,
"tag": "NAME",
"value": "Premium White"
},
{
"context": "g/094%20Cloudy%20Apple.png\"\n },\n {\n \"name\": \"Big Mango\",\n \"css\": \"background-image: linear-gradient(t",
"end": 23079,
"score": 0.7327472567558289,
"start": 23070,
"tag": "NAME",
"value": "Big Mango"
},
{
"context": "100%20Vicious%20Stance.png\"\n },\n {\n \"name\": \"Palo Alto\",\n \"css\": \"background-image: linear-gradient(-",
"end": 24306,
"score": 0.9993562698364258,
"start": 24297,
"tag": "NAME",
"value": "Palo Alto"
},
{
"context": "_png/101%20Palo%20Alto.png\"\n },\n {\n \"name\": \"Happy Memories\",\n \"css\": \"background-image: linear-gradient(-",
"end": 24507,
"score": 0.9173410534858704,
"start": 24493,
"tag": "NAME",
"value": "Happy Memories"
},
{
"context": "102%20Happy%20Memories.png\"\n },\n {\n \"name\": \"Midnight Bloom\",\n \"css\": \"background-image: linear-gradient(-",
"end": 24713,
"score": 0.9987766742706299,
"start": 24699,
"tag": "NAME",
"value": "Midnight Bloom"
},
{
"context": "103%20Midnight%20Bloom.png\"\n },\n {\n \"name\": \"Crystalline\",\n \"css\": \"background-image: linear-gradient(-",
"end": 24916,
"score": 0.9995789527893066,
"start": 24905,
"tag": "NAME",
"value": "Crystalline"
},
{
"context": "_png/104%20Crystalline.png\"\n },\n {\n \"name\": \"Raccoon Back\",\n \"css\": \"background: linear-gradient(-180deg",
"end": 25115,
"score": 0.9997949600219727,
"start": 25103,
"tag": "NAME",
"value": "Raccoon Back"
},
{
"context": "g/105%20Raccoon%20Back.png\"\n },\n {\n \"name\": \"Party Bliss\",\n \"css\": \"background-image: linear-gradient(t",
"end": 25423,
"score": 0.9679222106933594,
"start": 25412,
"tag": "NAME",
"value": "Party Bliss"
},
{
"context": "ng/106%20Party%20Bliss.png\"\n },\n {\n \"name\": \"Confident Cloud\",\n \"css\": \"background-image: linear-gradient(t",
"end": 25627,
"score": 0.9760691523551941,
"start": 25612,
"tag": "NAME",
"value": "Confident Cloud"
},
{
"context": "07%20Confident%20Cloud.png\"\n },\n {\n \"name\": \"Le Cocktail\",\n \"css\": \"background-image: linear-gradient(4",
"end": 25843,
"score": 0.9969343543052673,
"start": 25832,
"tag": "NAME",
"value": "Le Cocktail"
},
{
"context": "ng/108%20Le%20Cocktail.png\"\n },\n {\n \"name\": \"River City\",\n \"css\": \"background-image: linear-gradient(t",
"end": 26041,
"score": 0.9326830506324768,
"start": 26031,
"tag": "NAME",
"value": "River City"
},
{
"context": "png/109%20River%20City.png\"\n },\n {\n \"name\": \"Frozen Berry\",\n \"css\": \"background-image: linear-gradient(t",
"end": 26241,
"score": 0.999268114566803,
"start": 26229,
"tag": "NAME",
"value": "Frozen Berry"
},
{
"context": "g/110%20Frozen%20Berry.png\"\n },\n {\n \"name\": \"Elegance\",\n \"css\": \"background-image: radial-gradient(7",
"end": 26439,
"score": 0.9861945509910583,
"start": 26431,
"tag": "NAME",
"value": "Elegance"
},
{
"context": "nts_png/111%20Elegance.png\"\n },\n {\n \"name\": \"Child Care\",\n \"css\": \"background-image: linear-gradient(-",
"end": 26747,
"score": 0.874693751335144,
"start": 26737,
"tag": "NAME",
"value": "Child Care"
},
{
"context": "png/112%20Child%20Care.png\"\n },\n {\n \"name\": \"Flying Lemon\",\n \"css\": \"background-image: linear-gradient(6",
"end": 26947,
"score": 0.9866936206817627,
"start": 26935,
"tag": "NAME",
"value": "Flying Lemon"
},
{
"context": "g/113%20Flying%20Lemon.png\"\n },\n {\n \"name\": \"New Retrowave\",\n \"css\": \"background-image: linear-gradient(t",
"end": 27149,
"score": 0.98964524269104,
"start": 27136,
"tag": "NAME",
"value": "New Retrowave"
},
{
"context": "/114%20New%20Retrowave.png\"\n },\n {\n \"name\": \"Hidden Jaguar\",\n \"css\": \"background-image: linear-gradient(t",
"end": 27366,
"score": 0.9880519509315491,
"start": 27353,
"tag": "NAME",
"value": "Hidden Jaguar"
},
{
"context": "16%20Above%20The%20Sky.png\"\n },\n {\n \"name\": \"Nega\",\n \"css\": \"background-image: linear-gradient(4",
"end": 27822,
"score": 0.930539071559906,
"start": 27818,
"tag": "NAME",
"value": "Nega"
},
{
"context": "adients_png/117%20Nega.png\"\n },\n {\n \"name\": \"Dense Water\",\n \"css\": \"background-image: linear-gradient(t",
"end": 28012,
"score": 0.9665623307228088,
"start": 28001,
"tag": "NAME",
"value": "Dense Water"
},
{
"context": "ng/118%20Dense%20Water.png\"\n },\n {\n \"name\": \"Chemic Aqua\",\n \"css\": \"background-color: #CDDCDC;\\n backgr",
"end": 28227,
"score": 0.9978961944580078,
"start": 28216,
"tag": "NAME",
"value": "Chemic Aqua"
},
{
"context": "ng/119%20Chemic%20Aqua.png\"\n },\n {\n \"name\": \"Seashore\",\n \"css\": \"background-image: linear-gradient(t",
"end": 28602,
"score": 0.9964180588722229,
"start": 28594,
"tag": "NAME",
"value": "Seashore"
},
{
"context": "nts_png/120%20Seashore.png\"\n },\n {\n \"name\": \"Marble Wall\",\n \"css\": \"background-image: linear-gradient(t",
"end": 28797,
"score": 0.9997909665107727,
"start": 28786,
"tag": "NAME",
"value": "Marble Wall"
},
{
"context": "ng/121%20Marble%20Wall.png\"\n },\n {\n \"name\": \"Cheerful Caramel\",\n \"css\": \"background-image: linear-gradient(t",
"end": 29014,
"score": 0.9998613595962524,
"start": 28998,
"tag": "NAME",
"value": "Cheerful Caramel"
},
{
"context": "2%20Cheerful%20Caramel.png\"\n },\n {\n \"name\": \"Night Sky\",\n \"css\": \"background-image: linear-gradient(t",
"end": 29217,
"score": 0.9975325465202332,
"start": 29208,
"tag": "NAME",
"value": "Night Sky"
},
{
"context": "_png/123%20Night%20Sky.png\"\n },\n {\n \"name\": \"Magic Lake\",\n \"css\": \"background-image: linear-gradient(t",
"end": 29426,
"score": 0.9990013241767883,
"start": 29416,
"tag": "NAME",
"value": "Magic Lake"
},
{
"context": "png/124%20Magic%20Lake.png\"\n },\n {\n \"name\": \"Young Grass\",\n \"css\": \"background-image: linear-gradient(t",
"end": 29637,
"score": 0.9994354844093323,
"start": 29626,
"tag": "NAME",
"value": "Young Grass"
},
{
"context": "ng/125%20Young%20Grass.png\"\n },\n {\n \"name\": \"Colorful Peach\",\n \"css\": \"background-image: linear-gradient(t",
"end": 29840,
"score": 0.9989991188049316,
"start": 29826,
"tag": "NAME",
"value": "Colorful Peach"
},
{
"context": "126%20Colorful%20Peach.png\"\n },\n {\n \"name\": \"Gentle Care\",\n \"css\": \"background-image: linear-gradient(t",
"end": 30045,
"score": 0.9977576732635498,
"start": 30034,
"tag": "NAME",
"value": "Gentle Care"
},
{
"context": "ng/127%20Gentle%20Care.png\"\n },\n {\n \"name\": \"Plum Bath\",\n \"css\": \"background-image: linear-gradient(t",
"end": 30245,
"score": 0.9905068278312683,
"start": 30236,
"tag": "NAME",
"value": "Plum Bath"
},
{
"context": "_png/128%20Plum%20Bath.png\"\n },\n {\n \"name\": \"Happy Unicorn\",\n \"css\": \"background-image: linear-gradient(t",
"end": 30445,
"score": 0.6354379653930664,
"start": 30432,
"tag": "NAME",
"value": "Happy Unicorn"
},
{
"context": "/129%20Happy%20Unicorn.png\"\n },\n {\n \"name\": \"Full Metal\",\n \"css\": \"background: linear-gradient(to bott",
"end": 30646,
"score": 0.987026035785675,
"start": 30636,
"tag": "NAME",
"value": "Full Metal"
},
{
"context": "/130%20Full%20Metal.png\"\n },\n {\n \"name\": \"African Field\",\n \"css\": \"background-image: linear-gradient(t",
"end": 31075,
"score": 0.6362314224243164,
"start": 31065,
"tag": "NAME",
"value": "ican Field"
},
{
"context": "ng/134%20Glass%20Water.png\"\n },\n {\n \"name\": \"Slick Carbon\",\n \"css\": \"background: linear-gradient(",
"end": 31912,
"score": 0.6494088172912598,
"start": 31907,
"tag": "NAME",
"value": "Slick"
},
{
"context": "/136%20North%20Miracle.png\"\n },\n {\n \"name\": \"Fruit Blend\",\n \"css\": \"background-image: linear-gradient(t",
"end": 32446,
"score": 0.9479429721832275,
"start": 32435,
"tag": "NAME",
"value": "Fruit Blend"
},
{
"context": "ng/137%20Fruit%20Blend.png\"\n },\n {\n \"name\": \"Millennium Pine\",\n \"css\": \"background-image: linear-gradient(t",
"end": 32652,
"score": 0.9977009892463684,
"start": 32637,
"tag": "NAME",
"value": "Millennium Pine"
},
{
"context": "38%20Millennium%20Pine.png\"\n },\n {\n \"name\": \"High Flight\",\n \"css\": \"background-image: linear-gradient(t",
"end": 32856,
"score": 0.989539384841919,
"start": 32845,
"tag": "NAME",
"value": "High Flight"
},
{
"context": "ng/139%20High%20Flight.png\"\n },\n {\n \"name\": \"Mole Hall\",\n \"css\": \"background-image: linear-gradient(-",
"end": 33056,
"score": 0.9997179508209229,
"start": 33047,
"tag": "NAME",
"value": "Mole Hall"
},
{
"context": "_png/140%20Mole%20Hall.png\"\n },\n {\n \"name\": \"Earl Gray\",\n \"css\": \"background-color: #E4E4E1;\\n backgr",
"end": 33252,
"score": 0.9998430609703064,
"start": 33243,
"tag": "NAME",
"value": "Earl Gray"
},
{
"context": "_png/141%20Earl%20Gray.png\"\n },\n {\n \"name\": \"Space Shift\",\n \"css\": \"background-image: linear-gradient(6",
"end": 33635,
"score": 0.9720981121063232,
"start": 33624,
"tag": "NAME",
"value": "Space Shift"
},
{
"context": "ng/142%20Space%20Shift.png\"\n },\n {\n \"name\": \"Forest Inei\",\n \"css\": \"background-image: linear-gradient(t",
"end": 33860,
"score": 0.9814975261688232,
"start": 33849,
"tag": "NAME",
"value": "Forest Inei"
},
{
"context": "ng/143%20Forest%20Inei.png\"\n },\n {\n \"name\": \"Royal Garden\",\n \"css\": \"background-image: linear-gradient(t",
"end": 34061,
"score": 0.989614725112915,
"start": 34049,
"tag": "NAME",
"value": "Royal Garden"
},
{
"context": "g/144%20Royal%20Garden.png\"\n },\n {\n \"name\": \"Rich Metal\",\n \"css\": \"background-image: linear-gradient(t",
"end": 34263,
"score": 0.9968609809875488,
"start": 34253,
"tag": "NAME",
"value": "Rich Metal"
},
{
"context": "png/145%20Rich%20Metal.png\"\n },\n {\n \"name\": \"Juicy Cake\",\n \"css\": \"background-image: linear-gradient(t",
"end": 34463,
"score": 0.9945288300514221,
"start": 34453,
"tag": "NAME",
"value": "Juicy Cake"
},
{
"context": "7%20Smart%20Indigo.png\"\n },\n {\n \"name\": \"Sand Strike\",\n \"css\": \"background-image: linear-gradient(t",
"end": 34864,
"score": 0.6630921363830566,
"start": 34858,
"tag": "NAME",
"value": "Strike"
},
{
"context": "/150%20Aqua%20Guidance.png\"\n },\n {\n \"name\": \"Sun Veggie\",\n \"css\": \"background-image: linear-gradient(-",
"end": 35485,
"score": 0.593600869178772,
"start": 35475,
"tag": "NAME",
"value": "Sun Veggie"
},
{
"context": "_png/153%20Black%20Sea.png\"\n },\n {\n \"name\": \"Grass Shampoo\",\n \"css\": \"background-image: linear",
"end": 36094,
"score": 0.6844266653060913,
"start": 36092,
"tag": "NAME",
"value": "Gr"
},
{
"context": "5%20Landing%20Aircraft.png\"\n },\n {\n \"name\": \"Witch Dance\",\n \"css\": \"background-image: linear-gradient(-",
"end": 36545,
"score": 0.9161889553070068,
"start": 36534,
"tag": "NAME",
"value": "Witch Dance"
},
{
"context": "57%20Sleepless%20Night.png\"\n },\n {\n \"name\": \"Angel Care\",\n \"css\": \"background-image: linear-gradi",
"end": 36962,
"score": 0.9873796701431274,
"start": 36957,
"tag": "NAME",
"value": "Angel"
},
{
"context": "png/158%20Angel%20Care.png\"\n },\n {\n \"name\": \"Crystal River\",\n \"css\": \"background-image: linear-gradient(-",
"end": 37182,
"score": 0.6954061388969421,
"start": 37169,
"tag": "NAME",
"value": "Crystal River"
},
{
"context": "%20Crystal%20River.png\"\n },\n {\n \"name\": \"Soft Lipstick\",\n \"css\": \"background-image: linear-gradient(-",
"end": 37400,
"score": 0.5855475068092346,
"start": 37392,
"tag": "NAME",
"value": "Lipstick"
},
{
"context": "ng/169%20Supreme%20Sky.png\"\n },\n {\n \"name\": \"Light Blue\",\n \"css\": \"background-image: linear-gradient(-",
"end": 39479,
"score": 0.9436932802200317,
"start": 39469,
"tag": "NAME",
"value": "Light Blue"
},
{
"context": "png/170%20Light%20Blue.png\"\n },\n {\n \"name\": \"Mind Crawl\",\n \"css\": \"background-image: linear-gradient(-",
"end": 39691,
"score": 0.9937777519226074,
"start": 39681,
"tag": "NAME",
"value": "Mind Crawl"
},
{
"context": "png/171%20Mind%20Crawl.png\"\n },\n {\n \"name\": \"Lily Meadow\",\n \"css\": \"background-image: linear-gradient(-",
"end": 39904,
"score": 0.9973408579826355,
"start": 39893,
"tag": "NAME",
"value": "Lily Meadow"
},
{
"context": "ng/172%20Lily%20Meadow.png\"\n },\n {\n \"name\": \"Sugar Lollipop\",\n \"css\": \"background-image: linear-gradient(-",
"end": 40121,
"score": 0.9943485856056213,
"start": 40107,
"tag": "NAME",
"value": "Sugar Lollipop"
},
{
"context": "173%20Sugar%20Lollipop.png\"\n },\n {\n \"name\": \"Sweet Dessert\",\n \"css\": \"background-image: linear-gradient(-",
"end": 40340,
"score": 0.9965051412582397,
"start": 40327,
"tag": "NAME",
"value": "Sweet Dessert"
},
{
"context": "/174%20Sweet%20Dessert.png\"\n },\n {\n \"name\": \"Magic Ray\",\n \"css\": \"background-image: linear-gradient(-",
"end": 40554,
"score": 0.7885194420814514,
"start": 40545,
"tag": "NAME",
"value": "Magic Ray"
},
{
"context": "_png/175%20Magic%20Ray.png\"\n },\n {\n \"name\": \"Teen Party\",\n \"css\": \"background-image: linear-gradient(-",
"end": 40765,
"score": 0.5802436470985413,
"start": 40755,
"tag": "NAME",
"value": "Teen Party"
},
{
"context": "png/176%20Teen%20Party.png\"\n },\n {\n \"name\": \"Frozen Heat\",\n \"css\": \"background-image: linear-gradient(-",
"end": 40978,
"score": 0.7126020789146423,
"start": 40967,
"tag": "NAME",
"value": "Frozen Heat"
},
{
"context": "ng/177%20Frozen%20Heat.png\"\n },\n {\n \"name\": \"Gagarin View\",\n \"css\": \"background-image: linear-gradient(-",
"end": 41193,
"score": 0.7889927625656128,
"start": 41181,
"tag": "NAME",
"value": "Gagarin View"
},
{
"context": "/179%20Fabled%20Sunset.png\"\n },\n {\n \"name\": \"Perfect Blue\",\n \"css\": \"background-image: linear-gradient(-",
"end": 41640,
"score": 0.6050131320953369,
"start": 41628,
"tag": "NAME",
"value": "Perfect Blue"
}
] | src/gradients.coffee | allenbrowntech/lemon-gradients | 0 | gradients = [
{
"name": "Apple",
"css": "background-image: linear-gradient(-225deg, #b3b3b3 0%, #999 100%);"
}
{
"name": "Blogger",
"css": "background-image: linear-gradient(-225deg, #ff8000 0%, #ff9933 100%);"
}
{
"name": "Digg",
"css": "background-image: linear-gradient(-225deg, #262626 0%, #404040 100%);"
}
{
"name": "Dailymotion",
"css": "background-image: linear-gradient(-225deg, #0066dc 0%, #107fff 100%);"
}
{
"name": "Facebook",
"css": "background-image: linear-gradient(-225deg, #3b5998 0%, #4c70ba 100%);"
}
{
"name": "Flipboard",
"css": "background-image: linear-gradient(-225deg, #e12828 0%, #e75555 100%);"
}
{
"name": "Github",
"css": "background-image: linear-gradient(-225deg, #24292e 0%, #3a434b 100%);"
}
{
"name": "GooglePlus",
"css": "background-image: linear-gradient(-225deg, #dc4e41 0%, #e4766c 100%);"
}
{
"name": "LinkedIn",
"css": "background-image: linear-gradient(-225deg, #0077b5 0%, #0099e8 100%);"
}
{
"name": "LiveJournal",
"css": "background-image: linear-gradient(-225deg, #00b0ea 0%, #1ec7ff 100%);"
}
{
"name": "Odnoklassniki",
"css": "background-image: linear-gradient(-225deg, #d7772d 0%, #df9358 100%);"
}
{
"name": "Outlook",
"css": "background-image: linear-gradient(-225deg, #008ff9 0%, #0072c6 100%);"
}
{
"name": "Pinterest",
"css": "background-image: linear-gradient(-225deg, #cb2027 0%, #e03e44 100%);"
}
{
"name": "Reddit",
"css": "background-image: linear-gradient(-225deg, #ff4500 0%, #ff6a33 100%);"
}
{
"name": "Tumblr",
"css": "background-image: linear-gradient(-225deg, #32506d 0%, #426a90 100%);"
}
{
"name": "Twitch",
"css": "background-image: linear-gradient(-225deg, #6441a5 0%, #7e5bbe 100%);"
}
{
"name": "Twitter",
"css": "background-image: linear-gradient(-225deg, #55acee 0%, #83c3f3 100%);"
}
{
"name": "VK",
"css": "background-image: linear-gradient(-225deg, #4c6c91 0%, #6385ad 100%);"
}
{
"name": "Weibo",
"css": "background-image: linear-gradient(-225deg, #ff9933 0%, #ffb366 100%);"
}
{
"name": "Whatsapp",
"css": "background-image: linear-gradient(-225deg, #25d366 0%, #4be083 100%);"
}
{
"name": "Xing",
"css": "background-image: linear-gradient(-225deg, #1a7576 0%, #239ea0 100%);"
}
{
"name": "Yahoo",
"css": "background-image: linear-gradient(-225deg, #720e9e 0%, #9412cd 100%);"
}
{
"name": "Youtube",
"css": "background-image: linear-gradient(-225deg, #cd201f 0%, #e23e3d 100%);"
}
{
"name": "Warm Flame",
"css": "background-image: linear-gradient(45deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%);",
"image": "https://itmeo.com/public/webgradients_png/001%20Warm%20Flame.png"
},
{
"name": "Night Fade",
"css": "background-image: linear-gradient(to top, #a18cd1 0%, #fbc2eb 100%);",
"image": "https://itmeo.com/public/webgradients_png/002%20Night%20Fade.png"
},
{
"name": "Spring Warmth",
"css": "background-image: linear-gradient(to top, #fad0c4 0%, #fad0c4 1%, #ffd1ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/003%20Spring%20Warmth.png"
},
{
"name": "Juicy Peach",
"css": "background-image: linear-gradient(to right, #ffecd2 0%, #fcb69f 100%);",
"image": "https://itmeo.com/public/webgradients_png/004%20Juicy%20Peach.png"
},
{
"name": "Young Passion",
"css": "background-image: linear-gradient(to right, #ff8177 0%, #ff867a 0%, #ff8c7f 21%, #f99185 52%, #cf556c 78%, #b12a5b 100%);",
"image": "https://itmeo.com/public/webgradients_png/005%20Young%20Passion.png"
},
{
"name": "Lady Lips",
"css": "background-image: linear-gradient(to top, #ff9a9e 0%, #fecfef 99%, #fecfef 100%);",
"image": "https://itmeo.com/public/webgradients_png/006%20Lady%20Lips.png"
},
{
"name": "Sunny Morning",
"css": "background-image: linear-gradient(120deg, #f6d365 0%, #fda085 100%);",
"image": "https://itmeo.com/public/webgradients_png/007%20Sunny%20Morning.png"
},
{
"name": "Rainy Ashville",
"css": "background-image: linear-gradient(to top, #fbc2eb 0%, #a6c1ee 100%);",
"image": "https://itmeo.com/public/webgradients_png/008%20Rainy%20Ashville.png"
},
{
"name": "Frozen Dreams",
"css": "background-image: linear-gradient(to top, #fdcbf1 0%, #fdcbf1 1%, #e6dee9 100%);",
"image": "https://itmeo.com/public/webgradients_png/009%20Frozen%20Dreams.png"
},
{
"name": "Winter Neva",
"css": "background-image: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);",
"image": "https://itmeo.com/public/webgradients_png/010%20Winter%20Neva.png"
},
{
"name": "Dusty Grass",
"css": "background-image: linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%);",
"image": "https://itmeo.com/public/webgradients_png/011%20Dusty%20Grass.png"
},
{
"name": "Tempting Azure",
"css": "background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);",
"image": "https://itmeo.com/public/webgradients_png/012%20Tempting%20Azure.png"
},
{
"name": "Heavy Rain",
"css": "background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);",
"image": "https://itmeo.com/public/webgradients_png/013%20Heavy%20Rain.png"
},
{
"name": "Amy Crisp",
"css": "background-image: linear-gradient(120deg, #a6c0fe 0%, #f68084 100%);",
"image": "https://itmeo.com/public/webgradients_png/014%20Amy%20Crisp.png"
},
{
"name": "Mean Fruit",
"css": "background-image: linear-gradient(120deg, #fccb90 0%, #d57eeb 100%);",
"image": "https://itmeo.com/public/webgradients_png/015%20Mean%20Fruit.png"
},
{
"name": "Deep Blue",
"css": "background-image: linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%);",
"image": "https://itmeo.com/public/webgradients_png/016%20Deep%20Blue.png"
},
{
"name": "Ripe Malinka",
"css": "background-image: linear-gradient(120deg, #f093fb 0%, #f5576c 100%);",
"image": "https://itmeo.com/public/webgradients_png/017%20Ripe%20Malinka.png"
},
{
"name": "Cloudy Knoxville",
"css": "background-image: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);",
"image": "https://itmeo.com/public/webgradients_png/018%20Cloudy%20Knoxville.png"
},
{
"name": "Malibu Beach",
"css": "background-image: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);",
"image": "https://itmeo.com/public/webgradients_png/019%20Malibu%20Beach.png"
},
{
"name": "New Life",
"css": "background-image: linear-gradient(to right, #43e97b 0%, #38f9d7 100%);",
"image": "https://itmeo.com/public/webgradients_png/020%20New%20Life.png"
},
{
"name": "True Sunset",
"css": "background-image: linear-gradient(to right, #fa709a 0%, #fee140 100%);",
"image": "https://itmeo.com/public/webgradients_png/021%20True%20Sunset.png"
},
{
"name": "Morpheus Den",
"css": "background-image: linear-gradient(to top, #30cfd0 0%, #330867 100%);",
"image": "https://itmeo.com/public/webgradients_png/022%20Morpheus%20Den.png"
},
{
"name": "Rare Wind",
"css": "background-image: linear-gradient(to top, #a8edea 0%, #fed6e3 100%);",
"image": "https://itmeo.com/public/webgradients_png/023%20Rare%20Wind.png"
},
{
"name": "Near Moon",
"css": "background-image: linear-gradient(to top, #5ee7df 0%, #b490ca 100%);",
"image": "https://itmeo.com/public/webgradients_png/024%20Near%20Moon.png"
},
{
"name": "Wild Apple",
"css": "background-image: linear-gradient(to top, #d299c2 0%, #fef9d7 100%);",
"image": "https://itmeo.com/public/webgradients_png/025%20Wild%20Apple.png"
},
{
"name": "Saint Petersburg",
"css": "background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);",
"image": "https://itmeo.com/public/webgradients_png/026%20Saint%20Petersburg.png"
},
{
"name": "Arielle's Smile",
"css": "background-image: radial-gradient(circle 248px at center, #16d9e3 0%, #30c7ec 47%, #46aef7 100%);",
"image": "https://itmeo.com/public/webgradients_png/027%20Arielle's%20Smile.png"
},
{
"name": "Plum Plate",
"css": "background-image: linear-gradient(135deg, #667eea 0%, #764ba2 100%);",
"image": "https://itmeo.com/public/webgradients_png/028%20Plum%20Plate.png"
},
{
"name": "Everlasting Sky",
"css": "background-image: linear-gradient(135deg, #fdfcfb 0%, #e2d1c3 100%);",
"image": "https://itmeo.com/public/webgradients_png/029%20Everlasting%20Sky.png"
},
{
"name": "Happy Fisher",
"css": "background-image: linear-gradient(120deg, #89f7fe 0%, #66a6ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/030%20Happy%20Fisher.png"
},
{
"name": "Blessing",
"css": "background-image: linear-gradient(to top, #fddb92 0%, #d1fdff 100%);",
"image": "https://itmeo.com/public/webgradients_png/031%20Blessing.png"
},
{
"name": "Sharpeye Eagle",
"css": "background-image: linear-gradient(to top, #9890e3 0%, #b1f4cf 100%);",
"image": "https://itmeo.com/public/webgradients_png/032%20Sharpeye%20Eagle.png"
},
{
"name": "Ladoga Bottom",
"css": "background-image: linear-gradient(to top, #ebc0fd 0%, #d9ded8 100%);",
"image": "https://itmeo.com/public/webgradients_png/033%20Ladoga%20Bottom.png"
},
{
"name": "Lemon Gate",
"css": "background-image: linear-gradient(to top, #96fbc4 0%, #f9f586 100%);",
"image": "https://itmeo.com/public/webgradients_png/034%20Lemon%20Gate.png"
},
{
"name": "Itmeo Branding",
"css": "background-image: linear-gradient(180deg, #2af598 0%, #009efd 100%);",
"image": "https://itmeo.com/public/webgradients_png/035%20Itmeo%20Branding.png"
},
{
"name": "Zeus Miracle",
"css": "background-image: linear-gradient(to top, #cd9cf2 0%, #f6f3ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/036%20Zeus%20Miracle.png"
},
{
"name": "Old Hat",
"css": "background-image: linear-gradient(to right, #e4afcb 0%, #b8cbb8 0%, #b8cbb8 0%, #e2c58b 30%, #c2ce9c 64%, #7edbdc 100%);",
"image": "https://itmeo.com/public/webgradients_png/037%20Old%20Hat.png"
},
{
"name": "Star Wine",
"css": "background-image: linear-gradient(to right, #b8cbb8 0%, #b8cbb8 0%, #b465da 0%, #cf6cc9 33%, #ee609c 66%, #ee609c 100%);",
"image": "https://itmeo.com/public/webgradients_png/038%20Star%20Wine.png"
},
{
"name": "Deep Blue",
"css": "background-image: linear-gradient(to right, #6a11cb 0%, #2575fc 100%);",
"image": "https://itmeo.com/public/webgradients_png/039%20Deep%20Blue.png"
},
{
"name": "Coup de Grace",
"css": "background-color: #DCD9D4; \n background-image: linear-gradient(to bottom, rgba(255,255,255,0.50) 0%, rgba(0,0,0,0.50) 100%), radial-gradient(at 50% 0%, rgba(255,255,255,0.10) 0%, rgba(0,0,0,0.50) 50%); \n background-blend-mode: soft-light,screen;",
"image": "https://itmeo.com/public/webgradients_png/040%20Coup%20de%20Grace.png"
},
{
"name": "Happy Acid",
"css": "background-image: linear-gradient(to top, #37ecba 0%, #72afd3 100%);",
"image": "https://itmeo.com/public/webgradients_png/041%20Happy%20Acid.png"
},
{
"name": "Awesome Pine",
"css": "background-image: linear-gradient(to top, #ebbba7 0%, #cfc7f8 100%);",
"image": "https://itmeo.com/public/webgradients_png/042%20Awesome%20Pine.png"
},
{
"name": "New York",
"css": "background-image: linear-gradient(to top, #fff1eb 0%, #ace0f9 100%);",
"image": "https://itmeo.com/public/webgradients_png/043%20New%20York.png"
},
{
"name": "Shy Rainbow",
"css": "background-image: linear-gradient(to right, #eea2a2 0%, #bbc1bf 19%, #57c6e1 42%, #b49fda 79%, #7ac5d8 100%);",
"image": "https://itmeo.com/public/webgradients_png/044%20Shy%20Rainbow.png"
},
{
"name": "Loon Crest",
"css": "background: linear-gradient(to bottom, rgba(255,255,255,0.15) 0%, rgba(0,0,0,0.15) 100%), radial-gradient(at top center, rgba(255,255,255,0.40) 0%, rgba(0,0,0,0.40) 120%) #989898; \n background-blend-mode: multiply,multiply;",
"image": "https://itmeo.com/public/webgradients_png/045%20Loon%20Crest.png"
},
{
"name": "Mixed Hopes",
"css": "background-image: linear-gradient(to top, #c471f5 0%, #fa71cd 100%);",
"image": "https://itmeo.com/public/webgradients_png/046%20Mixed%20Hopes.png"
},
{
"name": "Fly High",
"css": "background-image: linear-gradient(to top, #48c6ef 0%, #6f86d6 100%);",
"image": "https://itmeo.com/public/webgradients_png/047%20Fly%20High.png"
},
{
"name": "Strong Bliss",
"css": "background-image: linear-gradient(to right, #f78ca0 0%, #f9748f 19%, #fd868c 60%, #fe9a8b 100%);",
"image": "https://itmeo.com/public/webgradients_png/048%20Strong%20Bliss.png"
},
{
"name": "Fresh Milk",
"css": "background-image: linear-gradient(to top, #feada6 0%, #f5efef 100%);",
"image": "https://itmeo.com/public/webgradients_png/049%20Fresh%20Milk.png"
},
{
"name": "Snow Again",
"css": "background-image: linear-gradient(to top, #e6e9f0 0%, #eef1f5 100%);",
"image": "https://itmeo.com/public/webgradients_png/050%20Snow%20Again.png"
},
{
"name": "February Ink",
"css": "background-image: linear-gradient(to top, #accbee 0%, #e7f0fd 100%);",
"image": "https://itmeo.com/public/webgradients_png/051%20February%20Ink.png"
},
{
"name": "Kind Steel",
"css": "background-image: linear-gradient(-20deg, #e9defa 0%, #fbfcdb 100%);",
"image": "https://itmeo.com/public/webgradients_png/052%20Kind%20Steel.png"
},
{
"name": "Soft Grass",
"css": "background-image: linear-gradient(to top, #c1dfc4 0%, #deecdd 100%);",
"image": "https://itmeo.com/public/webgradients_png/053%20Soft%20Grass.png"
},
{
"name": "Grown Early",
"css": "background-image: linear-gradient(to top, #0ba360 0%, #3cba92 100%);",
"image": "https://itmeo.com/public/webgradients_png/054%20Grown%20Early.png"
},
{
"name": "Sharp Blues",
"css": "background-image: linear-gradient(to top, #00c6fb 0%, #005bea 100%);",
"image": "https://itmeo.com/public/webgradients_png/055%20Sharp%20Blues.png"
},
{
"name": "Shady Water",
"css": "background-image: linear-gradient(to right, #74ebd5 0%, #9face6 100%);",
"image": "https://itmeo.com/public/webgradients_png/056%20Shady%20Water.png"
},
{
"name": "Dirty Beauty",
"css": "background-image: linear-gradient(to top, #6a85b6 0%, #bac8e0 100%);",
"image": "https://itmeo.com/public/webgradients_png/057%20Dirty%20Beauty.png"
},
{
"name": "Great Whale",
"css": "background-image: linear-gradient(to top, #a3bded 0%, #6991c7 100%);",
"image": "https://itmeo.com/public/webgradients_png/058%20Great%20Whale.png"
},
{
"name": "Teen Notebook",
"css": "background-image: linear-gradient(to top, #9795f0 0%, #fbc8d4 100%);",
"image": "https://itmeo.com/public/webgradients_png/059%20Teen%20Notebook.png"
},
{
"name": "Polite Rumors",
"css": "background-image: linear-gradient(to top, #a7a6cb 0%, #8989ba 52%, #8989ba 100%);",
"image": "https://itmeo.com/public/webgradients_png/060%20Polite%20Rumors.png"
},
{
"name": "Sweet Period",
"css": "background-image: linear-gradient(to top, #3f51b1 0%, #5a55ae 13%, #7b5fac 25%, #8f6aae 38%, #a86aa4 50%, #cc6b8e 62%, #f18271 75%, #f3a469 87%, #f7c978 100%);",
"image": "https://itmeo.com/public/webgradients_png/061%20Sweet%20Period.png"
},
{
"name": "Wide Matrix",
"css": "background-image: linear-gradient(to top, #fcc5e4 0%, #fda34b 15%, #ff7882 35%, #c8699e 52%, #7046aa 71%, #0c1db8 87%, #020f75 100%);",
"image": "https://itmeo.com/public/webgradients_png/062%20Wide%20Matrix.png"
},
{
"name": "Soft Cherish",
"css": "background-image: linear-gradient(to top, #dbdcd7 0%, #dddcd7 24%, #e2c9cc 30%, #e7627d 46%, #b8235a 59%, #801357 71%, #3d1635 84%, #1c1a27 100%);",
"image": "https://itmeo.com/public/webgradients_png/063%20Soft%20Cherish.png"
},
{
"name": "Red Salvation",
"css": "background-image: linear-gradient(to top, #f43b47 0%, #453a94 100%);",
"image": "https://itmeo.com/public/webgradients_png/064%20Red%20Salvation.png"
},
{
"name": "Burning Spring",
"css": "background-image: linear-gradient(to top, #4fb576 0%, #44c489 30%, #28a9ae 46%, #28a2b7 59%, #4c7788 71%, #6c4f63 86%, #432c39 100%);",
"image": "https://itmeo.com/public/webgradients_png/065%20Burning%20Spring.png"
},
{
"name": "Night Party",
"css": "background-image: linear-gradient(to top, #0250c5 0%, #d43f8d 100%);",
"image": "https://itmeo.com/public/webgradients_png/066%20Night%20Party.png"
},
{
"name": "Sky Glider",
"css": "background-image: linear-gradient(to top, #88d3ce 0%, #6e45e2 100%);",
"image": "https://itmeo.com/public/webgradients_png/067%20Sky%20Glider.png"
},
{
"name": "Heaven Peach",
"css": "background-image: linear-gradient(to top, #d9afd9 0%, #97d9e1 100%);",
"image": "https://itmeo.com/public/webgradients_png/068%20Heaven%20Peach.png"
},
{
"name": "Purple Division",
"css": "background-image: linear-gradient(to top, #7028e4 0%, #e5b2ca 100%);",
"image": "https://itmeo.com/public/webgradients_png/069%20Purple%20Division.png"
},
{
"name": "Aqua Splash",
"css": "background-image: linear-gradient(15deg, #13547a 0%, #80d0c7 100%);",
"image": "https://itmeo.com/public/webgradients_png/070%20Aqua%20Splash.png"
},
{
"name": "Above Clouds",
"css": "background-image: linear-gradient(to left, #BDBBBE 0%, #9D9EA3 100%), radial-gradient(88% 271%, rgba(255, 255, 255, 0.25) 0%, rgba(254, 254, 254, 0.25) 1%, rgba(0, 0, 0, 0.25) 100%), radial-gradient(50% 100%, rgba(255, 255, 255, 0.30) 0%, rgba(0, 0, 0, 0.30) 100%);\n background-blend-mode: normal, lighten, soft-light;",
"image": "https://itmeo.com/public/webgradients_png/5)%201%,%20rgba(0,%200,%200,%200.25)%20100%),%20radial-gradien.png"
},
{
"name": "Spiky Naga",
"css": "background-image: linear-gradient(to top, #505285 0%, #585e92 12%, #65689f 25%, #7474b0 37%, #7e7ebb 50%, #8389c7 62%, #9795d4 75%, #a2a1dc 87%, #b5aee4 100%);",
"image": "https://itmeo.com/public/webgradients_png/072%20Spiky%20Naga.png"
},
{
"name": "Love Kiss",
"css": "background-image: linear-gradient(to top, #ff0844 0%, #ffb199 100%);",
"image": "https://itmeo.com/public/webgradients_png/073%20Love%20Kiss.png"
},
{
"name": "Sharp Glass",
"css": "background: #C9CCD3;\n background-image: linear-gradient(-180deg, rgba(255,255,255,0.50) 0%, rgba(0,0,0,0.50) 100%);\n background-blend-mode: lighten;",
"image": "https://itmeo.com/public/webgradients_png/074%20Sharp%20Glass.png"
},
{
"name": "Clean Mirror",
"css": "background-image: linear-gradient(45deg, #93a5cf 0%, #e4efe9 100%);",
"image": "https://itmeo.com/public/webgradients_png/075%20Clean%20Mirror.png"
},
{
"name": "Premium Dark",
"css": "background-image: linear-gradient(to right, #434343 0%, black 100%);",
"image": "https://itmeo.com/public/webgradients_png/076%20Premium%20Dark.png"
},
{
"name": "Cold Evening",
"css": "background-image: linear-gradient(to top, #0c3483 0%, #a2b6df 100%, #6b8cce 100%, #a2b6df 100%);",
"image": "https://itmeo.com/public/webgradients_png/077%20Cold%20Evening.png"
},
{
"name": "Cochiti Lake",
"css": "background-image: linear-gradient(45deg, #93a5cf 0%, #e4efe9 100%);",
"image": "https://itmeo.com/public/webgradients_png/078%20Cochiti%20Lake.png"
},
{
"name": "Summer Games",
"css": "background-image: linear-gradient(to right, #92fe9d 0%, #00c9ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/079%20Summer%20Games.png"
},
{
"name": "Passionate Bed",
"css": "background-image: linear-gradient(to right, #ff758c 0%, #ff7eb3 100%);",
"image": "https://itmeo.com/public/webgradients_png/080%20Passionate%20Bed.png"
},
{
"name": "Mountain Rock",
"css": "background-image: linear-gradient(to right, #868f96 0%, #596164 100%);",
"image": "https://itmeo.com/public/webgradients_png/081%20Mountain%20Rock.png"
},
{
"name": "Desert Hump",
"css": "background-image: linear-gradient(to top, #c79081 0%, #dfa579 100%);",
"image": "https://itmeo.com/public/webgradients_png/082%20Desert%20Hump.png"
},
{
"name": "Jungle Day",
"css": "background-image: linear-gradient(45deg, #8baaaa 0%, #ae8b9c 100%);",
"image": "https://itmeo.com/public/webgradients_png/083%20Jungle%20Day.png"
},
{
"name": "Phoenix Start",
"css": "background-image: linear-gradient(to right, #f83600 0%, #f9d423 100%);",
"image": "https://itmeo.com/public/webgradients_png/084%20Phoenix%20Start.png"
},
{
"name": "October Silence",
"css": "background-image: linear-gradient(-20deg, #b721ff 0%, #21d4fd 100%);",
"image": "https://itmeo.com/public/webgradients_png/085%20October%20Silence.png"
},
{
"name": "Faraway River",
"css": "background-image: linear-gradient(-20deg, #6e45e2 0%, #88d3ce 100%);",
"image": "https://itmeo.com/public/webgradients_png/086%20Faraway%20River.png"
},
{
"name": "Alchemist Lab",
"css": "background-image: linear-gradient(-20deg, #d558c8 0%, #24d292 100%);",
"image": "https://itmeo.com/public/webgradients_png/087%20Alchemist%20Lab.png"
},
{
"name": "Over Sun",
"css": "background-image: linear-gradient(60deg, #abecd6 0%, #fbed96 100%);",
"image": "https://itmeo.com/public/webgradients_png/088%20Over%20Sun.png"
},
{
"name": "Premium White",
"css": "background-image: linear-gradient(to top, #d5d4d0 0%, #d5d4d0 1%, #eeeeec 31%, #efeeec 75%, #e9e9e7 100%);",
"image": "https://itmeo.com/public/webgradients_png/089%20Premium%20White.png"
},
{
"name": "Mars Party",
"css": "background-image: linear-gradient(to top, #5f72bd 0%, #9b23ea 100%);",
"image": "https://itmeo.com/public/webgradients_png/090%20Mars%20Party.png"
},
{
"name": "Eternal Constance",
"css": "background-image: linear-gradient(to top, #09203f 0%, #537895 100%);",
"image": "https://itmeo.com/public/webgradients_png/091%20Eternal%20Constance.png"
},
{
"name": "Japan Blush",
"css": "background-image: linear-gradient(-20deg, #ddd6f3 0%, #faaca8 100%, #faaca8 100%);",
"image": "https://itmeo.com/public/webgradients_png/092%20Japan%20Blush.png"
},
{
"name": "Smiling Rain",
"css": "background-image: linear-gradient(-20deg, #dcb0ed 0%, #99c99c 100%);",
"image": "https://itmeo.com/public/webgradients_png/093%20Smiling%20Rain.png"
},
{
"name": "Cloudy Apple",
"css": "background-image: linear-gradient(to top, #f3e7e9 0%, #e3eeff 99%, #e3eeff 100%);",
"image": "https://itmeo.com/public/webgradients_png/094%20Cloudy%20Apple.png"
},
{
"name": "Big Mango",
"css": "background-image: linear-gradient(to top, #c71d6f 0%, #d09693 100%);",
"image": "https://itmeo.com/public/webgradients_png/095%20Big%20Mango.png"
},
{
"name": "Healthy Water",
"css": "background-image: linear-gradient(60deg, #96deda 0%, #50c9c3 100%);",
"image": "https://itmeo.com/public/webgradients_png/096%20Healthy%20Water.png"
},
{
"name": "Amour Amour",
"css": "background-image: linear-gradient(to top, #f77062 0%, #fe5196 100%);",
"image": "https://itmeo.com/public/webgradients_png/097%20Amour%20Amour.png"
},
{
"name": "Risky Concrete",
"css": "background-image: linear-gradient(to top, #c4c5c7 0%, #dcdddf 52%, #ebebeb 100%);",
"image": "https://itmeo.com/public/webgradients_png/098%20Risky%20Concrete.png"
},
{
"name": "Strong Stick",
"css": "background-image: linear-gradient(to right, #a8caba 0%, #5d4157 100%);",
"image": "https://itmeo.com/public/webgradients_png/099%20Strong%20Stick.png"
},
{
"name": "Vicious Stance",
"css": "background-image: linear-gradient(60deg, #29323c 0%, #485563 100%);",
"image": "https://itmeo.com/public/webgradients_png/100%20Vicious%20Stance.png"
},
{
"name": "Palo Alto",
"css": "background-image: linear-gradient(-60deg, #16a085 0%, #f4d03f 100%);",
"image": "https://itmeo.com/public/webgradients_png/101%20Palo%20Alto.png"
},
{
"name": "Happy Memories",
"css": "background-image: linear-gradient(-60deg, #ff5858 0%, #f09819 100%);",
"image": "https://itmeo.com/public/webgradients_png/102%20Happy%20Memories.png"
},
{
"name": "Midnight Bloom",
"css": "background-image: linear-gradient(-20deg, #2b5876 0%, #4e4376 100%);",
"image": "https://itmeo.com/public/webgradients_png/103%20Midnight%20Bloom.png"
},
{
"name": "Crystalline",
"css": "background-image: linear-gradient(-20deg, #00cdac 0%, #8ddad5 100%);",
"image": "https://itmeo.com/public/webgradients_png/104%20Crystalline.png"
},
{
"name": "Raccoon Back",
"css": "background: linear-gradient(-180deg, #BCC5CE 0%, #929EAD 98%), radial-gradient(at top left, rgba(255,255,255,0.30) 0%, rgba(0,0,0,0.30) 100%);\n background-blend-mode: screen;",
"image": "https://itmeo.com/public/webgradients_png/105%20Raccoon%20Back.png"
},
{
"name": "Party Bliss",
"css": "background-image: linear-gradient(to top, #4481eb 0%, #04befe 100%);",
"image": "https://itmeo.com/public/webgradients_png/106%20Party%20Bliss.png"
},
{
"name": "Confident Cloud",
"css": "background-image: linear-gradient(to top, #dad4ec 0%, #dad4ec 1%, #f3e7e9 100%);",
"image": "https://itmeo.com/public/webgradients_png/107%20Confident%20Cloud.png"
},
{
"name": "Le Cocktail",
"css": "background-image: linear-gradient(45deg, #874da2 0%, #c43a30 100%);",
"image": "https://itmeo.com/public/webgradients_png/108%20Le%20Cocktail.png"
},
{
"name": "River City",
"css": "background-image: linear-gradient(to top, #4481eb 0%, #04befe 100%);",
"image": "https://itmeo.com/public/webgradients_png/109%20River%20City.png"
},
{
"name": "Frozen Berry",
"css": "background-image: linear-gradient(to top, #e8198b 0%, #c7eafd 100%);",
"image": "https://itmeo.com/public/webgradients_png/110%20Frozen%20Berry.png"
},
{
"name": "Elegance",
"css": "background-image: radial-gradient(73% 147%, #EADFDF 59%, #ECE2DF 100%), radial-gradient(91% 146%, rgba(255,255,255,0.50) 47%, rgba(0,0,0,0.50) 100%);\n background-blend-mode: screen;",
"image": "https://itmeo.com/public/webgradients_png/111%20Elegance.png"
},
{
"name": "Child Care",
"css": "background-image: linear-gradient(-20deg, #f794a4 0%, #fdd6bd 100%);",
"image": "https://itmeo.com/public/webgradients_png/112%20Child%20Care.png"
},
{
"name": "Flying Lemon",
"css": "background-image: linear-gradient(60deg, #64b3f4 0%, #c2e59c 100%);",
"image": "https://itmeo.com/public/webgradients_png/113%20Flying%20Lemon.png"
},
{
"name": "New Retrowave",
"css": "background-image: linear-gradient(to top, #3b41c5 0%, #a981bb 49%, #ffc8a9 100%);",
"image": "https://itmeo.com/public/webgradients_png/114%20New%20Retrowave.png"
},
{
"name": "Hidden Jaguar",
"css": "background-image: linear-gradient(to top, #0fd850 0%, #f9f047 100%);",
"image": "https://itmeo.com/public/webgradients_png/115%20Hidden%20Jaguar.png"
},
{
"name": "Above The Sky",
"css": "background-image: linear-gradient(to top, lightgrey 0%, lightgrey 1%, #e0e0e0 26%, #efefef 48%, #d9d9d9 75%, #bcbcbc 100%);",
"image": "https://itmeo.com/public/webgradients_png/116%20Above%20The%20Sky.png"
},
{
"name": "Nega",
"css": "background-image: linear-gradient(45deg, #ee9ca7 0%, #ffdde1 100%);",
"image": "https://itmeo.com/public/webgradients_png/117%20Nega.png"
},
{
"name": "Dense Water",
"css": "background-image: linear-gradient(to right, #3ab5b0 0%, #3d99be 31%, #56317a 100%);",
"image": "https://itmeo.com/public/webgradients_png/118%20Dense%20Water.png"
},
{
"name": "Chemic Aqua",
"css": "background-color: #CDDCDC;\n background-image: radial-gradient(at 50% 100%, rgba(255,255,255,0.50) 0%, rgba(0,0,0,0.50) 100%), linear-gradient(to bottom, rgba(255,255,255,0.25) 0%, rgba(0,0,0,0.25) 100%);\n background-blend-mode: screen, overlay;",
"image": "https://itmeo.com/public/webgradients_png/119%20Chemic%20Aqua.png"
},
{
"name": "Seashore",
"css": "background-image: linear-gradient(to top, #209cff 0%, #68e0cf 100%);",
"image": "https://itmeo.com/public/webgradients_png/120%20Seashore.png"
},
{
"name": "Marble Wall",
"css": "background-image: linear-gradient(to top, #bdc2e8 0%, #bdc2e8 1%, #e6dee9 100%);",
"image": "https://itmeo.com/public/webgradients_png/121%20Marble%20Wall.png"
},
{
"name": "Cheerful Caramel",
"css": "background-image: linear-gradient(to top, #e6b980 0%, #eacda3 100%);",
"image": "https://itmeo.com/public/webgradients_png/122%20Cheerful%20Caramel.png"
},
{
"name": "Night Sky",
"css": "background-image: linear-gradient(to top, #1e3c72 0%, #1e3c72 1%, #2a5298 100%);",
"image": "https://itmeo.com/public/webgradients_png/123%20Night%20Sky.png"
},
{
"name": "Magic Lake",
"css": "background-image: linear-gradient(to top, #d5dee7 0%, #ffafbd 0%, #c9ffbf 100%);",
"image": "https://itmeo.com/public/webgradients_png/124%20Magic%20Lake.png"
},
{
"name": "Young Grass",
"css": "background-image: linear-gradient(to top, #9be15d 0%, #00e3ae 100%);",
"image": "https://itmeo.com/public/webgradients_png/125%20Young%20Grass.png"
},
{
"name": "Colorful Peach",
"css": "background-image: linear-gradient(to right, #ed6ea0 0%, #ec8c69 100%);",
"image": "https://itmeo.com/public/webgradients_png/126%20Colorful%20Peach.png"
},
{
"name": "Gentle Care",
"css": "background-image: linear-gradient(to right, #ffc3a0 0%, #ffafbd 100%);",
"image": "https://itmeo.com/public/webgradients_png/127%20Gentle%20Care.png"
},
{
"name": "Plum Bath",
"css": "background-image: linear-gradient(to top, #cc208e 0%, #6713d2 100%);",
"image": "https://itmeo.com/public/webgradients_png/128%20Plum%20Bath.png"
},
{
"name": "Happy Unicorn",
"css": "background-image: linear-gradient(to top, #b3ffab 0%, #12fff7 100%);",
"image": "https://itmeo.com/public/webgradients_png/129%20Happy%20Unicorn.png"
},
{
"name": "Full Metal",
"css": "background: linear-gradient(to bottom, #D5DEE7 0%, #E8EBF2 50%, #E2E7ED 100%), linear-gradient(to bottom, rgba(0,0,0,0.02) 50%, rgba(255,255,255,0.02) 61%, rgba(0,0,0,0.02) 73%), linear-gradient(33deg, rgba(255,255,255,0.20) 0%, rgba(0,0,0,0.20) 100%);\n background-blend-mode: normal,color-burn;",
"image": "https://itmeo.com/public/webgradients_png/130%20Full%20Metal.png"
},
{
"name": "African Field",
"css": "background-image: linear-gradient(to top, #65bd60 0%, #5ac1a8 25%, #3ec6ed 50%, #b7ddb7 75%, #fef381 100%);",
"image": "https://itmeo.com/public/webgradients_png/131%20African%20Field.png"
},
{
"name": "Solid Stone",
"css": "background-image: linear-gradient(to right, #243949 0%, #517fa4 100%);",
"image": "https://itmeo.com/public/webgradients_png/132%20Solid%20Stone.png"
},
{
"name": "Orange Juice",
"css": "background-image: linear-gradient(-20deg, #fc6076 0%, #ff9a44 100%);",
"image": "https://itmeo.com/public/webgradients_png/133%20Orange%20Juice.png"
},
{
"name": "Glass Water",
"css": "background-image: linear-gradient(to top, #dfe9f3 0%, white 100%);",
"image": "https://itmeo.com/public/webgradients_png/134%20Glass%20Water.png"
},
{
"name": "Slick Carbon",
"css": "background: linear-gradient(to bottom, #323232 0%, #3F3F3F 40%, #1C1C1C 150%), linear-gradient(to top, rgba(255,255,255,0.40) 0%, rgba(0,0,0,0.25) 200%);\n background-blend-mode: multiply;",
"image": "https://itmeo.com/public/webgradients_png/135%20Slick%20Carbon.png"
},
{
"name": "North Miracle",
"css": "background-image: linear-gradient(to right, #00dbde 0%, #fc00ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/136%20North%20Miracle.png"
},
{
"name": "Fruit Blend",
"css": "background-image: linear-gradient(to right, #f9d423 0%, #ff4e50 100%);",
"image": "https://itmeo.com/public/webgradients_png/137%20Fruit%20Blend.png"
},
{
"name": "Millennium Pine",
"css": "background-image: linear-gradient(to top, #50cc7f 0%, #f5d100 100%);",
"image": "https://itmeo.com/public/webgradients_png/138%20Millennium%20Pine.png"
},
{
"name": "High Flight",
"css": "background-image: linear-gradient(to right, #0acffe 0%, #495aff 100%);",
"image": "https://itmeo.com/public/webgradients_png/139%20High%20Flight.png"
},
{
"name": "Mole Hall",
"css": "background-image: linear-gradient(-20deg, #616161 0%, #9bc5c3 100%);",
"image": "https://itmeo.com/public/webgradients_png/140%20Mole%20Hall.png"
},
{
"name": "Earl Gray",
"css": "background-color: #E4E4E1;\n background-image: radial-gradient(at top center, rgba(255,255,255,0.03) 0%, rgba(0,0,0,0.03) 100%), linear-gradient(to top, rgba(255,255,255,0.1) 0%, rgba(143,152,157,0.60) 100%);\n \tbackground-blend-mode: normal, multiply;",
"image": "https://itmeo.com/public/webgradients_png/141%20Earl%20Gray.png"
},
{
"name": "Space Shift",
"css": "background-image: linear-gradient(60deg, #3d3393 0%, #2b76b9 37%, #2cacd1 65%, #35eb93 100%);",
"image": "https://itmeo.com/public/webgradients_png/142%20Space%20Shift.png"
},
{
"name": "Forest Inei",
"css": "background-image: linear-gradient(to top, #df89b5 0%, #bfd9fe 100%);",
"image": "https://itmeo.com/public/webgradients_png/143%20Forest%20Inei.png"
},
{
"name": "Royal Garden",
"css": "background-image: linear-gradient(to right, #ed6ea0 0%, #ec8c69 100%);",
"image": "https://itmeo.com/public/webgradients_png/144%20Royal%20Garden.png"
},
{
"name": "Rich Metal",
"css": "background-image: linear-gradient(to right, #d7d2cc 0%, #304352 100%);",
"image": "https://itmeo.com/public/webgradients_png/145%20Rich%20Metal.png"
},
{
"name": "Juicy Cake",
"css": "background-image: linear-gradient(to top, #e14fad 0%, #f9d423 100%);",
"image": "https://itmeo.com/public/webgradients_png/146%20Juicy%20Cake.png"
},
{
"name": "Smart Indigo",
"css": "background-image: linear-gradient(to top, #b224ef 0%, #7579ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/147%20Smart%20Indigo.png"
},
{
"name": "Sand Strike",
"css": "background-image: linear-gradient(to right, #c1c161 0%, #c1c161 0%, #d4d4b1 100%);",
"image": "https://itmeo.com/public/webgradients_png/148%20Sand%20Strike.png"
},
{
"name": "Norse Beauty",
"css": "background-image: linear-gradient(to right, #ec77ab 0%, #7873f5 100%);",
"image": "https://itmeo.com/public/webgradients_png/149%20Norse%20Beauty.png"
},
{
"name": "Aqua Guidance",
"css": "background-image: linear-gradient(to top, #007adf 0%, #00ecbc 100%);",
"image": "https://itmeo.com/public/webgradients_png/150%20Aqua%20Guidance.png"
},
{
"name": "Sun Veggie",
"css": "background-image: linear-gradient(-225deg, #20E2D7 0%, #F9FEA5 100%);",
"image": "https://itmeo.com/public/webgradients_png/151%20Sun%20Veggie.png"
},
{
"name": "Sea Lord",
"css": "background-image: linear-gradient(-225deg, #2CD8D5 0%, #C5C1FF 56%, #FFBAC3 100%);",
"image": "https://itmeo.com/public/webgradients_png/152%20Sea%20Lord.png"
},
{
"name": "Black Sea",
"css": "background-image: linear-gradient(-225deg, #2CD8D5 0%, #6B8DD6 48%, #8E37D7 100%);",
"image": "https://itmeo.com/public/webgradients_png/153%20Black%20Sea.png"
},
{
"name": "Grass Shampoo",
"css": "background-image: linear-gradient(-225deg, #DFFFCD 0%, #90F9C4 48%, #39F3BB 100%);",
"image": "https://itmeo.com/public/webgradients_png/154%20Grass%20Shampoo.png"
},
{
"name": "Landing Aircraft",
"css": "background-image: linear-gradient(-225deg, #5D9FFF 0%, #B8DCFF 48%, #6BBBFF 100%);",
"image": "https://itmeo.com/public/webgradients_png/155%20Landing%20Aircraft.png"
},
{
"name": "Witch Dance",
"css": "background-image: linear-gradient(-225deg, #A8BFFF 0%, #884D80 100%);",
"image": "https://itmeo.com/public/webgradients_png/156%20Witch%20Dance.png"
},
{
"name": "Sleepless Night",
"css": "background-image: linear-gradient(-225deg, #5271C4 0%, #B19FFF 48%, #ECA1FE 100%);",
"image": "https://itmeo.com/public/webgradients_png/157%20Sleepless%20Night.png"
},
{
"name": "Angel Care",
"css": "background-image: linear-gradient(-225deg, #FFE29F 0%, #FFA99F 48%, #FF719A 100%);",
"image": "https://itmeo.com/public/webgradients_png/158%20Angel%20Care.png"
},
{
"name": "Crystal River",
"css": "background-image: linear-gradient(-225deg, #22E1FF 0%, #1D8FE1 48%, #625EB1 100%);",
"image": "https://itmeo.com/public/webgradients_png/159%20Crystal%20River.png"
},
{
"name": "Soft Lipstick",
"css": "background-image: linear-gradient(-225deg, #B6CEE8 0%, #F578DC 100%);",
"image": "https://itmeo.com/public/webgradients_png/160%20Soft%20Lipstick.png"
},
{
"name": "Salt Mountain",
"css": "background-image: linear-gradient(-225deg, #FFFEFF 0%, #D7FFFE 100%);",
"image": "https://itmeo.com/public/webgradients_png/161%20Salt%20Mountain.png"
},
{
"name": "Perfect White",
"css": "background-image: linear-gradient(-225deg, #E3FDF5 0%, #FFE6FA 100%);",
"image": "https://itmeo.com/public/webgradients_png/162%20Perfect%20White.png"
},
{
"name": "Fresh Oasis",
"css": "background-image: linear-gradient(-225deg, #7DE2FC 0%, #B9B6E5 100%);",
"image": "https://itmeo.com/public/webgradients_png/163%20Fresh%20Oasis.png"
},
{
"name": "Strict November",
"css": "background-image: linear-gradient(-225deg, #CBBACC 0%, #2580B3 100%);",
"image": "https://itmeo.com/public/webgradients_png/164%20Strict%20November.png"
},
{
"name": "Morning Salad",
"css": "background-image: linear-gradient(-225deg, #B7F8DB 0%, #50A7C2 100%);",
"image": "https://itmeo.com/public/webgradients_png/165%20Morning%20Salad.png"
},
{
"name": "Deep Relief",
"css": "background-image: linear-gradient(-225deg, #7085B6 0%, #87A7D9 50%, #DEF3F8 100%);",
"image": "https://itmeo.com/public/webgradients_png/166%20Deep%20Relief.png"
},
{
"name": "Sea Strike",
"css": "background-image: linear-gradient(-225deg, #77FFD2 0%, #6297DB 48%, #1EECFF 100%);",
"image": "https://itmeo.com/public/webgradients_png/167%20Sea%20Strike.png"
},
{
"name": "Night Call",
"css": "background-image: linear-gradient(-225deg, #AC32E4 0%, #7918F2 48%, #4801FF 100%);",
"image": "https://itmeo.com/public/webgradients_png/168%20Night%20Call.png"
},
{
"name": "Supreme Sky",
"css": "background-image: linear-gradient(-225deg, #D4FFEC 0%, #57F2CC 48%, #4596FB 100%);",
"image": "https://itmeo.com/public/webgradients_png/169%20Supreme%20Sky.png"
},
{
"name": "Light Blue",
"css": "background-image: linear-gradient(-225deg, #9EFBD3 0%, #57E9F2 48%, #45D4FB 100%);",
"image": "https://itmeo.com/public/webgradients_png/170%20Light%20Blue.png"
},
{
"name": "Mind Crawl",
"css": "background-image: linear-gradient(-225deg, #473B7B 0%, #3584A7 51%, #30D2BE 100%);",
"image": "https://itmeo.com/public/webgradients_png/171%20Mind%20Crawl.png"
},
{
"name": "Lily Meadow",
"css": "background-image: linear-gradient(-225deg, #65379B 0%, #886AEA 53%, #6457C6 100%);",
"image": "https://itmeo.com/public/webgradients_png/172%20Lily%20Meadow.png"
},
{
"name": "Sugar Lollipop",
"css": "background-image: linear-gradient(-225deg, #A445B2 0%, #D41872 52%, #FF0066 100%);",
"image": "https://itmeo.com/public/webgradients_png/173%20Sugar%20Lollipop.png"
},
{
"name": "Sweet Dessert",
"css": "background-image: linear-gradient(-225deg, #7742B2 0%, #F180FF 52%, #FD8BD9 100%);",
"image": "https://itmeo.com/public/webgradients_png/174%20Sweet%20Dessert.png"
},
{
"name": "Magic Ray",
"css": "background-image: linear-gradient(-225deg, #FF3CAC 0%, #562B7C 52%, #2B86C5 100%);",
"image": "https://itmeo.com/public/webgradients_png/175%20Magic%20Ray.png"
},
{
"name": "Teen Party",
"css": "background-image: linear-gradient(-225deg, #FF057C 0%, #8D0B93 50%, #321575 100%);",
"image": "https://itmeo.com/public/webgradients_png/176%20Teen%20Party.png"
},
{
"name": "Frozen Heat",
"css": "background-image: linear-gradient(-225deg, #FF057C 0%, #7C64D5 48%, #4CC3FF 100%);",
"image": "https://itmeo.com/public/webgradients_png/177%20Frozen%20Heat.png"
},
{
"name": "Gagarin View",
"css": "background-image: linear-gradient(-225deg, #69EACB 0%, #EACCF8 48%, #6654F1 100%);",
"image": "https://itmeo.com/public/webgradients_png/178%20Gagarin%20View.png"
},
{
"name": "Fabled Sunset",
"css": "background-image: linear-gradient(-225deg, #231557 0%, #44107A 29%, #FF1361 67%, #FFF800 100%);",
"image": "https://itmeo.com/public/webgradients_png/179%20Fabled%20Sunset.png"
},
{
"name": "Perfect Blue",
"css": "background-image: linear-gradient(-225deg, #3D4E81 0%, #5753C9 48%, #6E7FF3 100%);",
"image": "https://itmeo.com/public/webgradients_png/180%20Perfect%20Blue.png"
}
]
module.exports = {
gradients: gradients
getCSS: (name) ->
gradients.find((item) -> item.name is name)?.css
getImage: (name) ->
gradients.find((item) -> item.name is name)?.image
}
| 41034 | gradients = [
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #b3b3b3 0%, #999 100%);"
}
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #ff8000 0%, #ff9933 100%);"
}
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #262626 0%, #404040 100%);"
}
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #0066dc 0%, #107fff 100%);"
}
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #3b5998 0%, #4c70ba 100%);"
}
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #e12828 0%, #e75555 100%);"
}
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #24292e 0%, #3a434b 100%);"
}
{
"name": "GooglePlus",
"css": "background-image: linear-gradient(-225deg, #dc4e41 0%, #e4766c 100%);"
}
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #0077b5 0%, #0099e8 100%);"
}
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #00b0ea 0%, #1ec7ff 100%);"
}
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #d7772d 0%, #df9358 100%);"
}
{
"name": "Outlook",
"css": "background-image: linear-gradient(-225deg, #008ff9 0%, #0072c6 100%);"
}
{
"name": "Pinterest",
"css": "background-image: linear-gradient(-225deg, #cb2027 0%, #e03e44 100%);"
}
{
"name": "Reddit",
"css": "background-image: linear-gradient(-225deg, #ff4500 0%, #ff6a33 100%);"
}
{
"name": "Tumblr",
"css": "background-image: linear-gradient(-225deg, #32506d 0%, #426a90 100%);"
}
{
"name": "Twitch",
"css": "background-image: linear-gradient(-225deg, #6441a5 0%, #7e5bbe 100%);"
}
{
"name": "Twitter",
"css": "background-image: linear-gradient(-225deg, #55acee 0%, #83c3f3 100%);"
}
{
"name": "VK",
"css": "background-image: linear-gradient(-225deg, #4c6c91 0%, #6385ad 100%);"
}
{
"name": "Weibo",
"css": "background-image: linear-gradient(-225deg, #ff9933 0%, #ffb366 100%);"
}
{
"name": "Whatsapp",
"css": "background-image: linear-gradient(-225deg, #25d366 0%, #4be083 100%);"
}
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #1a7576 0%, #239ea0 100%);"
}
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #720e9e 0%, #9412cd 100%);"
}
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #cd201f 0%, #e23e3d 100%);"
}
{
"name": "<NAME>arm Flame",
"css": "background-image: linear-gradient(45deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%);",
"image": "https://itmeo.com/public/webgradients_png/001%20Warm%20Flame.png"
},
{
"name": "Night Fade",
"css": "background-image: linear-gradient(to top, #a18cd1 0%, #fbc2eb 100%);",
"image": "https://itmeo.com/public/webgradients_png/002%20Night%20Fade.png"
},
{
"name": "Spring W<NAME>",
"css": "background-image: linear-gradient(to top, #fad0c4 0%, #fad0c4 1%, #ffd1ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/003%20Spring%20Warmth.png"
},
{
"name": "<NAME>icy P<NAME>",
"css": "background-image: linear-gradient(to right, #ffecd2 0%, #fcb69f 100%);",
"image": "https://itmeo.com/public/webgradients_png/004%20Juicy%20Peach.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #ff8177 0%, #ff867a 0%, #ff8c7f 21%, #f99185 52%, #cf556c 78%, #b12a5b 100%);",
"image": "https://itmeo.com/public/webgradients_png/005%20Young%20Passion.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #ff9a9e 0%, #fecfef 99%, #fecfef 100%);",
"image": "https://itmeo.com/public/webgradients_png/006%20Lady%20Lips.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(120deg, #f6d365 0%, #fda085 100%);",
"image": "https://itmeo.com/public/webgradients_png/007%20Sunny%20Morning.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #fbc2eb 0%, #a6c1ee 100%);",
"image": "https://itmeo.com/public/webgradients_png/008%20Rainy%20Ashville.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #fdcbf1 0%, #fdcbf1 1%, #e6dee9 100%);",
"image": "https://itmeo.com/public/webgradients_png/009%20Frozen%20Dreams.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);",
"image": "https://itmeo.com/public/webgradients_png/010%20Winter%20Neva.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%);",
"image": "https://itmeo.com/public/webgradients_png/011%20Dusty%20Grass.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);",
"image": "https://itmeo.com/public/webgradients_png/012%20Tempting%20Azure.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);",
"image": "https://itmeo.com/public/webgradients_png/013%20Heavy%20Rain.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(120deg, #a6c0fe 0%, #f68084 100%);",
"image": "https://itmeo.com/public/webgradients_png/014%20Amy%20Crisp.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(120deg, #fccb90 0%, #d57eeb 100%);",
"image": "https://itmeo.com/public/webgradients_png/015%20Mean%20Fruit.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%);",
"image": "https://itmeo.com/public/webgradients_png/016%20Deep%20Blue.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(120deg, #f093fb 0%, #f5576c 100%);",
"image": "https://itmeo.com/public/webgradients_png/017%20Ripe%20Malinka.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);",
"image": "https://itmeo.com/public/webgradients_png/018%20Cloudy%20Knoxville.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);",
"image": "https://itmeo.com/public/webgradients_png/019%20Malibu%20Beach.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #43e97b 0%, #38f9d7 100%);",
"image": "https://itmeo.com/public/webgradients_png/020%20New%20Life.png"
},
{
"name": "True Sunset",
"css": "background-image: linear-gradient(to right, #fa709a 0%, #fee140 100%);",
"image": "https://itmeo.com/public/webgradients_png/021%20True%20Sunset.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #30cfd0 0%, #330867 100%);",
"image": "https://itmeo.com/public/webgradients_png/022%20Morpheus%20Den.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #a8edea 0%, #fed6e3 100%);",
"image": "https://itmeo.com/public/webgradients_png/023%20Rare%20Wind.png"
},
{
"name": "Near Moon",
"css": "background-image: linear-gradient(to top, #5ee7df 0%, #b490ca 100%);",
"image": "https://itmeo.com/public/webgradients_png/024%20Near%20Moon.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #d299c2 0%, #fef9d7 100%);",
"image": "https://itmeo.com/public/webgradients_png/025%20Wild%20Apple.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);",
"image": "https://itmeo.com/public/webgradients_png/026%20Saint%20Petersburg.png"
},
{
"name": "<NAME>",
"css": "background-image: radial-gradient(circle 248px at center, #16d9e3 0%, #30c7ec 47%, #46aef7 100%);",
"image": "https://itmeo.com/public/webgradients_png/027%20Arielle's%20Smile.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(135deg, #667eea 0%, #764ba2 100%);",
"image": "https://itmeo.com/public/webgradients_png/028%20Plum%20Plate.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(135deg, #fdfcfb 0%, #e2d1c3 100%);",
"image": "https://itmeo.com/public/webgradients_png/029%20Everlasting%20Sky.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(120deg, #89f7fe 0%, #66a6ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/030%20Happy%20Fisher.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #fddb92 0%, #d1fdff 100%);",
"image": "https://itmeo.com/public/webgradients_png/031%20Blessing.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #9890e3 0%, #b1f4cf 100%);",
"image": "https://itmeo.com/public/webgradients_png/032%20Sharpeye%20Eagle.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #ebc0fd 0%, #d9ded8 100%);",
"image": "https://itmeo.com/public/webgradients_png/033%20Ladoga%20Bottom.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #96fbc4 0%, #f9f586 100%);",
"image": "https://itmeo.com/public/webgradients_png/034%20Lemon%20Gate.png"
},
{
"name": "Itmeo Branding",
"css": "background-image: linear-gradient(180deg, #2af598 0%, #009efd 100%);",
"image": "https://itmeo.com/public/webgradients_png/035%20Itmeo%20Branding.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #cd9cf2 0%, #f6f3ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/036%20Zeus%20Miracle.png"
},
{
"name": "Old <NAME>",
"css": "background-image: linear-gradient(to right, #e4afcb 0%, #b8cbb8 0%, #b8cbb8 0%, #e2c58b 30%, #c2ce9c 64%, #7edbdc 100%);",
"image": "https://itmeo.com/public/webgradients_png/037%20Old%20Hat.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #b8cbb8 0%, #b8cbb8 0%, #b465da 0%, #cf6cc9 33%, #ee609c 66%, #ee609c 100%);",
"image": "https://itmeo.com/public/webgradients_png/038%20Star%20Wine.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #6a11cb 0%, #2575fc 100%);",
"image": "https://itmeo.com/public/webgradients_png/039%20Deep%20Blue.png"
},
{
"name": "<NAME>",
"css": "background-color: #DCD9D4; \n background-image: linear-gradient(to bottom, rgba(255,255,255,0.50) 0%, rgba(0,0,0,0.50) 100%), radial-gradient(at 50% 0%, rgba(255,255,255,0.10) 0%, rgba(0,0,0,0.50) 50%); \n background-blend-mode: soft-light,screen;",
"image": "https://itmeo.com/public/webgradients_png/040%20Coup%20de%20Grace.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #37ecba 0%, #72afd3 100%);",
"image": "https://itmeo.com/public/webgradients_png/041%20Happy%20Acid.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #ebbba7 0%, #cfc7f8 100%);",
"image": "https://itmeo.com/public/webgradients_png/042%20Awesome%20Pine.png"
},
{
"name": "New York",
"css": "background-image: linear-gradient(to top, #fff1eb 0%, #ace0f9 100%);",
"image": "https://itmeo.com/public/webgradients_png/043%20New%20York.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #eea2a2 0%, #bbc1bf 19%, #57c6e1 42%, #b49fda 79%, #7ac5d8 100%);",
"image": "https://itmeo.com/public/webgradients_png/044%20Shy%20Rainbow.png"
},
{
"name": "<NAME>",
"css": "background: linear-gradient(to bottom, rgba(255,255,255,0.15) 0%, rgba(0,0,0,0.15) 100%), radial-gradient(at top center, rgba(255,255,255,0.40) 0%, rgba(0,0,0,0.40) 120%) #989898; \n background-blend-mode: multiply,multiply;",
"image": "https://itmeo.com/public/webgradients_png/045%20Loon%20Crest.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #c471f5 0%, #fa71cd 100%);",
"image": "https://itmeo.com/public/webgradients_png/046%20Mixed%20Hopes.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #48c6ef 0%, #6f86d6 100%);",
"image": "https://itmeo.com/public/webgradients_png/047%20Fly%20High.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #f78ca0 0%, #f9748f 19%, #fd868c 60%, #fe9a8b 100%);",
"image": "https://itmeo.com/public/webgradients_png/048%20Strong%20Bliss.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #feada6 0%, #f5efef 100%);",
"image": "https://itmeo.com/public/webgradients_png/049%20Fresh%20Milk.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #e6e9f0 0%, #eef1f5 100%);",
"image": "https://itmeo.com/public/webgradients_png/050%20Snow%20Again.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #accbee 0%, #e7f0fd 100%);",
"image": "https://itmeo.com/public/webgradients_png/051%20February%20Ink.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-20deg, #e9defa 0%, #fbfcdb 100%);",
"image": "https://itmeo.com/public/webgradients_png/052%20Kind%20Steel.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #c1dfc4 0%, #deecdd 100%);",
"image": "https://itmeo.com/public/webgradients_png/053%20Soft%20Grass.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #0ba360 0%, #3cba92 100%);",
"image": "https://itmeo.com/public/webgradients_png/054%20Grown%20Early.png"
},
{
"name": "Sharp <NAME>ues",
"css": "background-image: linear-gradient(to top, #00c6fb 0%, #005bea 100%);",
"image": "https://itmeo.com/public/webgradients_png/055%20Sharp%20Blues.png"
},
{
"name": "Shady Water",
"css": "background-image: linear-gradient(to right, #74ebd5 0%, #9face6 100%);",
"image": "https://itmeo.com/public/webgradients_png/056%20Shady%20Water.png"
},
{
"name": "Dirty Beauty",
"css": "background-image: linear-gradient(to top, #6a85b6 0%, #bac8e0 100%);",
"image": "https://itmeo.com/public/webgradients_png/057%20Dirty%20Beauty.png"
},
{
"name": "Great Whale",
"css": "background-image: linear-gradient(to top, #a3bded 0%, #6991c7 100%);",
"image": "https://itmeo.com/public/webgradients_png/058%20Great%20Whale.png"
},
{
"name": "Teen Notebook",
"css": "background-image: linear-gradient(to top, #9795f0 0%, #fbc8d4 100%);",
"image": "https://itmeo.com/public/webgradients_png/059%20Teen%20Notebook.png"
},
{
"name": "Polite Rumors",
"css": "background-image: linear-gradient(to top, #a7a6cb 0%, #8989ba 52%, #8989ba 100%);",
"image": "https://itmeo.com/public/webgradients_png/060%20Polite%20Rumors.png"
},
{
"name": "Sweet Period",
"css": "background-image: linear-gradient(to top, #3f51b1 0%, #5a55ae 13%, #7b5fac 25%, #8f6aae 38%, #a86aa4 50%, #cc6b8e 62%, #f18271 75%, #f3a469 87%, #f7c978 100%);",
"image": "https://itmeo.com/public/webgradients_png/061%20Sweet%20Period.png"
},
{
"name": "Wide Matrix",
"css": "background-image: linear-gradient(to top, #fcc5e4 0%, #fda34b 15%, #ff7882 35%, #c8699e 52%, #7046aa 71%, #0c1db8 87%, #020f75 100%);",
"image": "https://itmeo.com/public/webgradients_png/062%20Wide%20Matrix.png"
},
{
"name": "Soft Cherish",
"css": "background-image: linear-gradient(to top, #dbdcd7 0%, #dddcd7 24%, #e2c9cc 30%, #e7627d 46%, #b8235a 59%, #801357 71%, #3d1635 84%, #1c1a27 100%);",
"image": "https://itmeo.com/public/webgradients_png/063%20Soft%20Cherish.png"
},
{
"name": "Red Salvation",
"css": "background-image: linear-gradient(to top, #f43b47 0%, #453a94 100%);",
"image": "https://itmeo.com/public/webgradients_png/064%20Red%20Salvation.png"
},
{
"name": "Burning Spring",
"css": "background-image: linear-gradient(to top, #4fb576 0%, #44c489 30%, #28a9ae 46%, #28a2b7 59%, #4c7788 71%, #6c4f63 86%, #432c39 100%);",
"image": "https://itmeo.com/public/webgradients_png/065%20Burning%20Spring.png"
},
{
"name": "Night Party",
"css": "background-image: linear-gradient(to top, #0250c5 0%, #d43f8d 100%);",
"image": "https://itmeo.com/public/webgradients_png/066%20Night%20Party.png"
},
{
"name": "Sky <NAME>",
"css": "background-image: linear-gradient(to top, #88d3ce 0%, #6e45e2 100%);",
"image": "https://itmeo.com/public/webgradients_png/067%20Sky%20Glider.png"
},
{
"name": "Heaven Peach",
"css": "background-image: linear-gradient(to top, #d9afd9 0%, #97d9e1 100%);",
"image": "https://itmeo.com/public/webgradients_png/068%20Heaven%20Peach.png"
},
{
"name": "Purple Division",
"css": "background-image: linear-gradient(to top, #7028e4 0%, #e5b2ca 100%);",
"image": "https://itmeo.com/public/webgradients_png/069%20Purple%20Division.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(15deg, #13547a 0%, #80d0c7 100%);",
"image": "https://itmeo.com/public/webgradients_png/070%20Aqua%20Splash.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to left, #BDBBBE 0%, #9D9EA3 100%), radial-gradient(88% 271%, rgba(255, 255, 255, 0.25) 0%, rgba(254, 254, 254, 0.25) 1%, rgba(0, 0, 0, 0.25) 100%), radial-gradient(50% 100%, rgba(255, 255, 255, 0.30) 0%, rgba(0, 0, 0, 0.30) 100%);\n background-blend-mode: normal, lighten, soft-light;",
"image": "https://itmeo.com/public/webgradients_png/5)%201%,%20rgba(0,%200,%200,%200.25)%20100%),%20radial-gradien.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #505285 0%, #585e92 12%, #65689f 25%, #7474b0 37%, #7e7ebb 50%, #8389c7 62%, #9795d4 75%, #a2a1dc 87%, #b5aee4 100%);",
"image": "https://itmeo.com/public/webgradients_png/072%20Spiky%20Naga.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #ff0844 0%, #ffb199 100%);",
"image": "https://itmeo.com/public/webgradients_png/073%20Love%20Kiss.png"
},
{
"name": "<NAME>",
"css": "background: #C9CCD3;\n background-image: linear-gradient(-180deg, rgba(255,255,255,0.50) 0%, rgba(0,0,0,0.50) 100%);\n background-blend-mode: lighten;",
"image": "https://itmeo.com/public/webgradients_png/074%20Sharp%20Glass.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(45deg, #93a5cf 0%, #e4efe9 100%);",
"image": "https://itmeo.com/public/webgradients_png/075%20Clean%20Mirror.png"
},
{
"name": "Premium Dark",
"css": "background-image: linear-gradient(to right, #434343 0%, black 100%);",
"image": "https://itmeo.com/public/webgradients_png/076%20Premium%20Dark.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #0c3483 0%, #a2b6df 100%, #6b8cce 100%, #a2b6df 100%);",
"image": "https://itmeo.com/public/webgradients_png/077%20Cold%20Evening.png"
},
{
"name": "<NAME> Lake",
"css": "background-image: linear-gradient(45deg, #93a5cf 0%, #e4efe9 100%);",
"image": "https://itmeo.com/public/webgradients_png/078%20Cochiti%20Lake.png"
},
{
"name": "Summer Games",
"css": "background-image: linear-gradient(to right, #92fe9d 0%, #00c9ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/079%20Summer%20Games.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #ff758c 0%, #ff7eb3 100%);",
"image": "https://itmeo.com/public/webgradients_png/080%20Passionate%20Bed.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #868f96 0%, #596164 100%);",
"image": "https://itmeo.com/public/webgradients_png/081%20Mountain%20Rock.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #c79081 0%, #dfa579 100%);",
"image": "https://itmeo.com/public/webgradients_png/082%20Desert%20Hump.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(45deg, #8baaaa 0%, #ae8b9c 100%);",
"image": "https://itmeo.com/public/webgradients_png/083%20Jungle%20Day.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #f83600 0%, #f9d423 100%);",
"image": "https://itmeo.com/public/webgradients_png/084%20Phoenix%20Start.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-20deg, #b721ff 0%, #21d4fd 100%);",
"image": "https://itmeo.com/public/webgradients_png/085%20October%20Silence.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-20deg, #6e45e2 0%, #88d3ce 100%);",
"image": "https://itmeo.com/public/webgradients_png/086%20Faraway%20River.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-20deg, #d558c8 0%, #24d292 100%);",
"image": "https://itmeo.com/public/webgradients_png/087%20Alchemist%20Lab.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(60deg, #abecd6 0%, #fbed96 100%);",
"image": "https://itmeo.com/public/webgradients_png/088%20Over%20Sun.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #d5d4d0 0%, #d5d4d0 1%, #eeeeec 31%, #efeeec 75%, #e9e9e7 100%);",
"image": "https://itmeo.com/public/webgradients_png/089%20Premium%20White.png"
},
{
"name": "Mars Party",
"css": "background-image: linear-gradient(to top, #5f72bd 0%, #9b23ea 100%);",
"image": "https://itmeo.com/public/webgradients_png/090%20Mars%20Party.png"
},
{
"name": "Eternal Constance",
"css": "background-image: linear-gradient(to top, #09203f 0%, #537895 100%);",
"image": "https://itmeo.com/public/webgradients_png/091%20Eternal%20Constance.png"
},
{
"name": "Japan Blush",
"css": "background-image: linear-gradient(-20deg, #ddd6f3 0%, #faaca8 100%, #faaca8 100%);",
"image": "https://itmeo.com/public/webgradients_png/092%20Japan%20Blush.png"
},
{
"name": "Smiling Rain",
"css": "background-image: linear-gradient(-20deg, #dcb0ed 0%, #99c99c 100%);",
"image": "https://itmeo.com/public/webgradients_png/093%20Smiling%20Rain.png"
},
{
"name": "Cloudy Apple",
"css": "background-image: linear-gradient(to top, #f3e7e9 0%, #e3eeff 99%, #e3eeff 100%);",
"image": "https://itmeo.com/public/webgradients_png/094%20Cloudy%20Apple.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #c71d6f 0%, #d09693 100%);",
"image": "https://itmeo.com/public/webgradients_png/095%20Big%20Mango.png"
},
{
"name": "Healthy Water",
"css": "background-image: linear-gradient(60deg, #96deda 0%, #50c9c3 100%);",
"image": "https://itmeo.com/public/webgradients_png/096%20Healthy%20Water.png"
},
{
"name": "Amour Amour",
"css": "background-image: linear-gradient(to top, #f77062 0%, #fe5196 100%);",
"image": "https://itmeo.com/public/webgradients_png/097%20Amour%20Amour.png"
},
{
"name": "Risky Concrete",
"css": "background-image: linear-gradient(to top, #c4c5c7 0%, #dcdddf 52%, #ebebeb 100%);",
"image": "https://itmeo.com/public/webgradients_png/098%20Risky%20Concrete.png"
},
{
"name": "Strong Stick",
"css": "background-image: linear-gradient(to right, #a8caba 0%, #5d4157 100%);",
"image": "https://itmeo.com/public/webgradients_png/099%20Strong%20Stick.png"
},
{
"name": "Vicious Stance",
"css": "background-image: linear-gradient(60deg, #29323c 0%, #485563 100%);",
"image": "https://itmeo.com/public/webgradients_png/100%20Vicious%20Stance.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-60deg, #16a085 0%, #f4d03f 100%);",
"image": "https://itmeo.com/public/webgradients_png/101%20Palo%20Alto.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-60deg, #ff5858 0%, #f09819 100%);",
"image": "https://itmeo.com/public/webgradients_png/102%20Happy%20Memories.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-20deg, #2b5876 0%, #4e4376 100%);",
"image": "https://itmeo.com/public/webgradients_png/103%20Midnight%20Bloom.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-20deg, #00cdac 0%, #8ddad5 100%);",
"image": "https://itmeo.com/public/webgradients_png/104%20Crystalline.png"
},
{
"name": "<NAME>",
"css": "background: linear-gradient(-180deg, #BCC5CE 0%, #929EAD 98%), radial-gradient(at top left, rgba(255,255,255,0.30) 0%, rgba(0,0,0,0.30) 100%);\n background-blend-mode: screen;",
"image": "https://itmeo.com/public/webgradients_png/105%20Raccoon%20Back.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #4481eb 0%, #04befe 100%);",
"image": "https://itmeo.com/public/webgradients_png/106%20Party%20Bliss.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #dad4ec 0%, #dad4ec 1%, #f3e7e9 100%);",
"image": "https://itmeo.com/public/webgradients_png/107%20Confident%20Cloud.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(45deg, #874da2 0%, #c43a30 100%);",
"image": "https://itmeo.com/public/webgradients_png/108%20Le%20Cocktail.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #4481eb 0%, #04befe 100%);",
"image": "https://itmeo.com/public/webgradients_png/109%20River%20City.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #e8198b 0%, #c7eafd 100%);",
"image": "https://itmeo.com/public/webgradients_png/110%20Frozen%20Berry.png"
},
{
"name": "<NAME>",
"css": "background-image: radial-gradient(73% 147%, #EADFDF 59%, #ECE2DF 100%), radial-gradient(91% 146%, rgba(255,255,255,0.50) 47%, rgba(0,0,0,0.50) 100%);\n background-blend-mode: screen;",
"image": "https://itmeo.com/public/webgradients_png/111%20Elegance.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-20deg, #f794a4 0%, #fdd6bd 100%);",
"image": "https://itmeo.com/public/webgradients_png/112%20Child%20Care.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(60deg, #64b3f4 0%, #c2e59c 100%);",
"image": "https://itmeo.com/public/webgradients_png/113%20Flying%20Lemon.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #3b41c5 0%, #a981bb 49%, #ffc8a9 100%);",
"image": "https://itmeo.com/public/webgradients_png/114%20New%20Retrowave.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #0fd850 0%, #f9f047 100%);",
"image": "https://itmeo.com/public/webgradients_png/115%20Hidden%20Jaguar.png"
},
{
"name": "Above The Sky",
"css": "background-image: linear-gradient(to top, lightgrey 0%, lightgrey 1%, #e0e0e0 26%, #efefef 48%, #d9d9d9 75%, #bcbcbc 100%);",
"image": "https://itmeo.com/public/webgradients_png/116%20Above%20The%20Sky.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(45deg, #ee9ca7 0%, #ffdde1 100%);",
"image": "https://itmeo.com/public/webgradients_png/117%20Nega.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #3ab5b0 0%, #3d99be 31%, #56317a 100%);",
"image": "https://itmeo.com/public/webgradients_png/118%20Dense%20Water.png"
},
{
"name": "<NAME>",
"css": "background-color: #CDDCDC;\n background-image: radial-gradient(at 50% 100%, rgba(255,255,255,0.50) 0%, rgba(0,0,0,0.50) 100%), linear-gradient(to bottom, rgba(255,255,255,0.25) 0%, rgba(0,0,0,0.25) 100%);\n background-blend-mode: screen, overlay;",
"image": "https://itmeo.com/public/webgradients_png/119%20Chemic%20Aqua.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #209cff 0%, #68e0cf 100%);",
"image": "https://itmeo.com/public/webgradients_png/120%20Seashore.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #bdc2e8 0%, #bdc2e8 1%, #e6dee9 100%);",
"image": "https://itmeo.com/public/webgradients_png/121%20Marble%20Wall.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #e6b980 0%, #eacda3 100%);",
"image": "https://itmeo.com/public/webgradients_png/122%20Cheerful%20Caramel.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #1e3c72 0%, #1e3c72 1%, #2a5298 100%);",
"image": "https://itmeo.com/public/webgradients_png/123%20Night%20Sky.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #d5dee7 0%, #ffafbd 0%, #c9ffbf 100%);",
"image": "https://itmeo.com/public/webgradients_png/124%20Magic%20Lake.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #9be15d 0%, #00e3ae 100%);",
"image": "https://itmeo.com/public/webgradients_png/125%20Young%20Grass.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #ed6ea0 0%, #ec8c69 100%);",
"image": "https://itmeo.com/public/webgradients_png/126%20Colorful%20Peach.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #ffc3a0 0%, #ffafbd 100%);",
"image": "https://itmeo.com/public/webgradients_png/127%20Gentle%20Care.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #cc208e 0%, #6713d2 100%);",
"image": "https://itmeo.com/public/webgradients_png/128%20Plum%20Bath.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #b3ffab 0%, #12fff7 100%);",
"image": "https://itmeo.com/public/webgradients_png/129%20Happy%20Unicorn.png"
},
{
"name": "<NAME>",
"css": "background: linear-gradient(to bottom, #D5DEE7 0%, #E8EBF2 50%, #E2E7ED 100%), linear-gradient(to bottom, rgba(0,0,0,0.02) 50%, rgba(255,255,255,0.02) 61%, rgba(0,0,0,0.02) 73%), linear-gradient(33deg, rgba(255,255,255,0.20) 0%, rgba(0,0,0,0.20) 100%);\n background-blend-mode: normal,color-burn;",
"image": "https://itmeo.com/public/webgradients_png/130%20Full%20Metal.png"
},
{
"name": "Afr<NAME>",
"css": "background-image: linear-gradient(to top, #65bd60 0%, #5ac1a8 25%, #3ec6ed 50%, #b7ddb7 75%, #fef381 100%);",
"image": "https://itmeo.com/public/webgradients_png/131%20African%20Field.png"
},
{
"name": "Solid Stone",
"css": "background-image: linear-gradient(to right, #243949 0%, #517fa4 100%);",
"image": "https://itmeo.com/public/webgradients_png/132%20Solid%20Stone.png"
},
{
"name": "Orange Juice",
"css": "background-image: linear-gradient(-20deg, #fc6076 0%, #ff9a44 100%);",
"image": "https://itmeo.com/public/webgradients_png/133%20Orange%20Juice.png"
},
{
"name": "Glass Water",
"css": "background-image: linear-gradient(to top, #dfe9f3 0%, white 100%);",
"image": "https://itmeo.com/public/webgradients_png/134%20Glass%20Water.png"
},
{
"name": "<NAME> Carbon",
"css": "background: linear-gradient(to bottom, #323232 0%, #3F3F3F 40%, #1C1C1C 150%), linear-gradient(to top, rgba(255,255,255,0.40) 0%, rgba(0,0,0,0.25) 200%);\n background-blend-mode: multiply;",
"image": "https://itmeo.com/public/webgradients_png/135%20Slick%20Carbon.png"
},
{
"name": "North Miracle",
"css": "background-image: linear-gradient(to right, #00dbde 0%, #fc00ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/136%20North%20Miracle.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #f9d423 0%, #ff4e50 100%);",
"image": "https://itmeo.com/public/webgradients_png/137%20Fruit%20Blend.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #50cc7f 0%, #f5d100 100%);",
"image": "https://itmeo.com/public/webgradients_png/138%20Millennium%20Pine.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #0acffe 0%, #495aff 100%);",
"image": "https://itmeo.com/public/webgradients_png/139%20High%20Flight.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-20deg, #616161 0%, #9bc5c3 100%);",
"image": "https://itmeo.com/public/webgradients_png/140%20Mole%20Hall.png"
},
{
"name": "<NAME>",
"css": "background-color: #E4E4E1;\n background-image: radial-gradient(at top center, rgba(255,255,255,0.03) 0%, rgba(0,0,0,0.03) 100%), linear-gradient(to top, rgba(255,255,255,0.1) 0%, rgba(143,152,157,0.60) 100%);\n \tbackground-blend-mode: normal, multiply;",
"image": "https://itmeo.com/public/webgradients_png/141%20Earl%20Gray.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(60deg, #3d3393 0%, #2b76b9 37%, #2cacd1 65%, #35eb93 100%);",
"image": "https://itmeo.com/public/webgradients_png/142%20Space%20Shift.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #df89b5 0%, #bfd9fe 100%);",
"image": "https://itmeo.com/public/webgradients_png/143%20Forest%20Inei.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #ed6ea0 0%, #ec8c69 100%);",
"image": "https://itmeo.com/public/webgradients_png/144%20Royal%20Garden.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to right, #d7d2cc 0%, #304352 100%);",
"image": "https://itmeo.com/public/webgradients_png/145%20Rich%20Metal.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(to top, #e14fad 0%, #f9d423 100%);",
"image": "https://itmeo.com/public/webgradients_png/146%20Juicy%20Cake.png"
},
{
"name": "Smart Indigo",
"css": "background-image: linear-gradient(to top, #b224ef 0%, #7579ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/147%20Smart%20Indigo.png"
},
{
"name": "Sand <NAME>",
"css": "background-image: linear-gradient(to right, #c1c161 0%, #c1c161 0%, #d4d4b1 100%);",
"image": "https://itmeo.com/public/webgradients_png/148%20Sand%20Strike.png"
},
{
"name": "Norse Beauty",
"css": "background-image: linear-gradient(to right, #ec77ab 0%, #7873f5 100%);",
"image": "https://itmeo.com/public/webgradients_png/149%20Norse%20Beauty.png"
},
{
"name": "Aqua Guidance",
"css": "background-image: linear-gradient(to top, #007adf 0%, #00ecbc 100%);",
"image": "https://itmeo.com/public/webgradients_png/150%20Aqua%20Guidance.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #20E2D7 0%, #F9FEA5 100%);",
"image": "https://itmeo.com/public/webgradients_png/151%20Sun%20Veggie.png"
},
{
"name": "Sea Lord",
"css": "background-image: linear-gradient(-225deg, #2CD8D5 0%, #C5C1FF 56%, #FFBAC3 100%);",
"image": "https://itmeo.com/public/webgradients_png/152%20Sea%20Lord.png"
},
{
"name": "Black Sea",
"css": "background-image: linear-gradient(-225deg, #2CD8D5 0%, #6B8DD6 48%, #8E37D7 100%);",
"image": "https://itmeo.com/public/webgradients_png/153%20Black%20Sea.png"
},
{
"name": "<NAME>ass Shampoo",
"css": "background-image: linear-gradient(-225deg, #DFFFCD 0%, #90F9C4 48%, #39F3BB 100%);",
"image": "https://itmeo.com/public/webgradients_png/154%20Grass%20Shampoo.png"
},
{
"name": "Landing Aircraft",
"css": "background-image: linear-gradient(-225deg, #5D9FFF 0%, #B8DCFF 48%, #6BBBFF 100%);",
"image": "https://itmeo.com/public/webgradients_png/155%20Landing%20Aircraft.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #A8BFFF 0%, #884D80 100%);",
"image": "https://itmeo.com/public/webgradients_png/156%20Witch%20Dance.png"
},
{
"name": "Sleepless Night",
"css": "background-image: linear-gradient(-225deg, #5271C4 0%, #B19FFF 48%, #ECA1FE 100%);",
"image": "https://itmeo.com/public/webgradients_png/157%20Sleepless%20Night.png"
},
{
"name": "<NAME> Care",
"css": "background-image: linear-gradient(-225deg, #FFE29F 0%, #FFA99F 48%, #FF719A 100%);",
"image": "https://itmeo.com/public/webgradients_png/158%20Angel%20Care.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #22E1FF 0%, #1D8FE1 48%, #625EB1 100%);",
"image": "https://itmeo.com/public/webgradients_png/159%20Crystal%20River.png"
},
{
"name": "Soft <NAME>",
"css": "background-image: linear-gradient(-225deg, #B6CEE8 0%, #F578DC 100%);",
"image": "https://itmeo.com/public/webgradients_png/160%20Soft%20Lipstick.png"
},
{
"name": "Salt Mountain",
"css": "background-image: linear-gradient(-225deg, #FFFEFF 0%, #D7FFFE 100%);",
"image": "https://itmeo.com/public/webgradients_png/161%20Salt%20Mountain.png"
},
{
"name": "Perfect White",
"css": "background-image: linear-gradient(-225deg, #E3FDF5 0%, #FFE6FA 100%);",
"image": "https://itmeo.com/public/webgradients_png/162%20Perfect%20White.png"
},
{
"name": "Fresh Oasis",
"css": "background-image: linear-gradient(-225deg, #7DE2FC 0%, #B9B6E5 100%);",
"image": "https://itmeo.com/public/webgradients_png/163%20Fresh%20Oasis.png"
},
{
"name": "Strict November",
"css": "background-image: linear-gradient(-225deg, #CBBACC 0%, #2580B3 100%);",
"image": "https://itmeo.com/public/webgradients_png/164%20Strict%20November.png"
},
{
"name": "Morning Salad",
"css": "background-image: linear-gradient(-225deg, #B7F8DB 0%, #50A7C2 100%);",
"image": "https://itmeo.com/public/webgradients_png/165%20Morning%20Salad.png"
},
{
"name": "Deep Relief",
"css": "background-image: linear-gradient(-225deg, #7085B6 0%, #87A7D9 50%, #DEF3F8 100%);",
"image": "https://itmeo.com/public/webgradients_png/166%20Deep%20Relief.png"
},
{
"name": "Sea Strike",
"css": "background-image: linear-gradient(-225deg, #77FFD2 0%, #6297DB 48%, #1EECFF 100%);",
"image": "https://itmeo.com/public/webgradients_png/167%20Sea%20Strike.png"
},
{
"name": "Night Call",
"css": "background-image: linear-gradient(-225deg, #AC32E4 0%, #7918F2 48%, #4801FF 100%);",
"image": "https://itmeo.com/public/webgradients_png/168%20Night%20Call.png"
},
{
"name": "Supreme Sky",
"css": "background-image: linear-gradient(-225deg, #D4FFEC 0%, #57F2CC 48%, #4596FB 100%);",
"image": "https://itmeo.com/public/webgradients_png/169%20Supreme%20Sky.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #9EFBD3 0%, #57E9F2 48%, #45D4FB 100%);",
"image": "https://itmeo.com/public/webgradients_png/170%20Light%20Blue.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #473B7B 0%, #3584A7 51%, #30D2BE 100%);",
"image": "https://itmeo.com/public/webgradients_png/171%20Mind%20Crawl.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #65379B 0%, #886AEA 53%, #6457C6 100%);",
"image": "https://itmeo.com/public/webgradients_png/172%20Lily%20Meadow.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #A445B2 0%, #D41872 52%, #FF0066 100%);",
"image": "https://itmeo.com/public/webgradients_png/173%20Sugar%20Lollipop.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #7742B2 0%, #F180FF 52%, #FD8BD9 100%);",
"image": "https://itmeo.com/public/webgradients_png/174%20Sweet%20Dessert.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #FF3CAC 0%, #562B7C 52%, #2B86C5 100%);",
"image": "https://itmeo.com/public/webgradients_png/175%20Magic%20Ray.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #FF057C 0%, #8D0B93 50%, #321575 100%);",
"image": "https://itmeo.com/public/webgradients_png/176%20Teen%20Party.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #FF057C 0%, #7C64D5 48%, #4CC3FF 100%);",
"image": "https://itmeo.com/public/webgradients_png/177%20Frozen%20Heat.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #69EACB 0%, #EACCF8 48%, #6654F1 100%);",
"image": "https://itmeo.com/public/webgradients_png/178%20Gagarin%20View.png"
},
{
"name": "Fabled Sunset",
"css": "background-image: linear-gradient(-225deg, #231557 0%, #44107A 29%, #FF1361 67%, #FFF800 100%);",
"image": "https://itmeo.com/public/webgradients_png/179%20Fabled%20Sunset.png"
},
{
"name": "<NAME>",
"css": "background-image: linear-gradient(-225deg, #3D4E81 0%, #5753C9 48%, #6E7FF3 100%);",
"image": "https://itmeo.com/public/webgradients_png/180%20Perfect%20Blue.png"
}
]
module.exports = {
gradients: gradients
getCSS: (name) ->
gradients.find((item) -> item.name is name)?.css
getImage: (name) ->
gradients.find((item) -> item.name is name)?.image
}
| true | gradients = [
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #b3b3b3 0%, #999 100%);"
}
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #ff8000 0%, #ff9933 100%);"
}
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #262626 0%, #404040 100%);"
}
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #0066dc 0%, #107fff 100%);"
}
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #3b5998 0%, #4c70ba 100%);"
}
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #e12828 0%, #e75555 100%);"
}
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #24292e 0%, #3a434b 100%);"
}
{
"name": "GooglePlus",
"css": "background-image: linear-gradient(-225deg, #dc4e41 0%, #e4766c 100%);"
}
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #0077b5 0%, #0099e8 100%);"
}
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #00b0ea 0%, #1ec7ff 100%);"
}
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #d7772d 0%, #df9358 100%);"
}
{
"name": "Outlook",
"css": "background-image: linear-gradient(-225deg, #008ff9 0%, #0072c6 100%);"
}
{
"name": "Pinterest",
"css": "background-image: linear-gradient(-225deg, #cb2027 0%, #e03e44 100%);"
}
{
"name": "Reddit",
"css": "background-image: linear-gradient(-225deg, #ff4500 0%, #ff6a33 100%);"
}
{
"name": "Tumblr",
"css": "background-image: linear-gradient(-225deg, #32506d 0%, #426a90 100%);"
}
{
"name": "Twitch",
"css": "background-image: linear-gradient(-225deg, #6441a5 0%, #7e5bbe 100%);"
}
{
"name": "Twitter",
"css": "background-image: linear-gradient(-225deg, #55acee 0%, #83c3f3 100%);"
}
{
"name": "VK",
"css": "background-image: linear-gradient(-225deg, #4c6c91 0%, #6385ad 100%);"
}
{
"name": "Weibo",
"css": "background-image: linear-gradient(-225deg, #ff9933 0%, #ffb366 100%);"
}
{
"name": "Whatsapp",
"css": "background-image: linear-gradient(-225deg, #25d366 0%, #4be083 100%);"
}
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #1a7576 0%, #239ea0 100%);"
}
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #720e9e 0%, #9412cd 100%);"
}
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #cd201f 0%, #e23e3d 100%);"
}
{
"name": "PI:NAME:<NAME>END_PIarm Flame",
"css": "background-image: linear-gradient(45deg, #ff9a9e 0%, #fad0c4 99%, #fad0c4 100%);",
"image": "https://itmeo.com/public/webgradients_png/001%20Warm%20Flame.png"
},
{
"name": "Night Fade",
"css": "background-image: linear-gradient(to top, #a18cd1 0%, #fbc2eb 100%);",
"image": "https://itmeo.com/public/webgradients_png/002%20Night%20Fade.png"
},
{
"name": "Spring WPI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #fad0c4 0%, #fad0c4 1%, #ffd1ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/003%20Spring%20Warmth.png"
},
{
"name": "PI:NAME:<NAME>END_PIicy PPI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #ffecd2 0%, #fcb69f 100%);",
"image": "https://itmeo.com/public/webgradients_png/004%20Juicy%20Peach.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #ff8177 0%, #ff867a 0%, #ff8c7f 21%, #f99185 52%, #cf556c 78%, #b12a5b 100%);",
"image": "https://itmeo.com/public/webgradients_png/005%20Young%20Passion.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #ff9a9e 0%, #fecfef 99%, #fecfef 100%);",
"image": "https://itmeo.com/public/webgradients_png/006%20Lady%20Lips.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(120deg, #f6d365 0%, #fda085 100%);",
"image": "https://itmeo.com/public/webgradients_png/007%20Sunny%20Morning.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #fbc2eb 0%, #a6c1ee 100%);",
"image": "https://itmeo.com/public/webgradients_png/008%20Rainy%20Ashville.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #fdcbf1 0%, #fdcbf1 1%, #e6dee9 100%);",
"image": "https://itmeo.com/public/webgradients_png/009%20Frozen%20Dreams.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);",
"image": "https://itmeo.com/public/webgradients_png/010%20Winter%20Neva.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%);",
"image": "https://itmeo.com/public/webgradients_png/011%20Dusty%20Grass.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);",
"image": "https://itmeo.com/public/webgradients_png/012%20Tempting%20Azure.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);",
"image": "https://itmeo.com/public/webgradients_png/013%20Heavy%20Rain.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(120deg, #a6c0fe 0%, #f68084 100%);",
"image": "https://itmeo.com/public/webgradients_png/014%20Amy%20Crisp.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(120deg, #fccb90 0%, #d57eeb 100%);",
"image": "https://itmeo.com/public/webgradients_png/015%20Mean%20Fruit.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%);",
"image": "https://itmeo.com/public/webgradients_png/016%20Deep%20Blue.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(120deg, #f093fb 0%, #f5576c 100%);",
"image": "https://itmeo.com/public/webgradients_png/017%20Ripe%20Malinka.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);",
"image": "https://itmeo.com/public/webgradients_png/018%20Cloudy%20Knoxville.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #4facfe 0%, #00f2fe 100%);",
"image": "https://itmeo.com/public/webgradients_png/019%20Malibu%20Beach.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #43e97b 0%, #38f9d7 100%);",
"image": "https://itmeo.com/public/webgradients_png/020%20New%20Life.png"
},
{
"name": "True Sunset",
"css": "background-image: linear-gradient(to right, #fa709a 0%, #fee140 100%);",
"image": "https://itmeo.com/public/webgradients_png/021%20True%20Sunset.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #30cfd0 0%, #330867 100%);",
"image": "https://itmeo.com/public/webgradients_png/022%20Morpheus%20Den.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #a8edea 0%, #fed6e3 100%);",
"image": "https://itmeo.com/public/webgradients_png/023%20Rare%20Wind.png"
},
{
"name": "Near Moon",
"css": "background-image: linear-gradient(to top, #5ee7df 0%, #b490ca 100%);",
"image": "https://itmeo.com/public/webgradients_png/024%20Near%20Moon.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #d299c2 0%, #fef9d7 100%);",
"image": "https://itmeo.com/public/webgradients_png/025%20Wild%20Apple.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);",
"image": "https://itmeo.com/public/webgradients_png/026%20Saint%20Petersburg.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: radial-gradient(circle 248px at center, #16d9e3 0%, #30c7ec 47%, #46aef7 100%);",
"image": "https://itmeo.com/public/webgradients_png/027%20Arielle's%20Smile.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(135deg, #667eea 0%, #764ba2 100%);",
"image": "https://itmeo.com/public/webgradients_png/028%20Plum%20Plate.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(135deg, #fdfcfb 0%, #e2d1c3 100%);",
"image": "https://itmeo.com/public/webgradients_png/029%20Everlasting%20Sky.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(120deg, #89f7fe 0%, #66a6ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/030%20Happy%20Fisher.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #fddb92 0%, #d1fdff 100%);",
"image": "https://itmeo.com/public/webgradients_png/031%20Blessing.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #9890e3 0%, #b1f4cf 100%);",
"image": "https://itmeo.com/public/webgradients_png/032%20Sharpeye%20Eagle.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #ebc0fd 0%, #d9ded8 100%);",
"image": "https://itmeo.com/public/webgradients_png/033%20Ladoga%20Bottom.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #96fbc4 0%, #f9f586 100%);",
"image": "https://itmeo.com/public/webgradients_png/034%20Lemon%20Gate.png"
},
{
"name": "Itmeo Branding",
"css": "background-image: linear-gradient(180deg, #2af598 0%, #009efd 100%);",
"image": "https://itmeo.com/public/webgradients_png/035%20Itmeo%20Branding.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #cd9cf2 0%, #f6f3ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/036%20Zeus%20Miracle.png"
},
{
"name": "Old PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #e4afcb 0%, #b8cbb8 0%, #b8cbb8 0%, #e2c58b 30%, #c2ce9c 64%, #7edbdc 100%);",
"image": "https://itmeo.com/public/webgradients_png/037%20Old%20Hat.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #b8cbb8 0%, #b8cbb8 0%, #b465da 0%, #cf6cc9 33%, #ee609c 66%, #ee609c 100%);",
"image": "https://itmeo.com/public/webgradients_png/038%20Star%20Wine.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #6a11cb 0%, #2575fc 100%);",
"image": "https://itmeo.com/public/webgradients_png/039%20Deep%20Blue.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-color: #DCD9D4; \n background-image: linear-gradient(to bottom, rgba(255,255,255,0.50) 0%, rgba(0,0,0,0.50) 100%), radial-gradient(at 50% 0%, rgba(255,255,255,0.10) 0%, rgba(0,0,0,0.50) 50%); \n background-blend-mode: soft-light,screen;",
"image": "https://itmeo.com/public/webgradients_png/040%20Coup%20de%20Grace.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #37ecba 0%, #72afd3 100%);",
"image": "https://itmeo.com/public/webgradients_png/041%20Happy%20Acid.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #ebbba7 0%, #cfc7f8 100%);",
"image": "https://itmeo.com/public/webgradients_png/042%20Awesome%20Pine.png"
},
{
"name": "New York",
"css": "background-image: linear-gradient(to top, #fff1eb 0%, #ace0f9 100%);",
"image": "https://itmeo.com/public/webgradients_png/043%20New%20York.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #eea2a2 0%, #bbc1bf 19%, #57c6e1 42%, #b49fda 79%, #7ac5d8 100%);",
"image": "https://itmeo.com/public/webgradients_png/044%20Shy%20Rainbow.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background: linear-gradient(to bottom, rgba(255,255,255,0.15) 0%, rgba(0,0,0,0.15) 100%), radial-gradient(at top center, rgba(255,255,255,0.40) 0%, rgba(0,0,0,0.40) 120%) #989898; \n background-blend-mode: multiply,multiply;",
"image": "https://itmeo.com/public/webgradients_png/045%20Loon%20Crest.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #c471f5 0%, #fa71cd 100%);",
"image": "https://itmeo.com/public/webgradients_png/046%20Mixed%20Hopes.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #48c6ef 0%, #6f86d6 100%);",
"image": "https://itmeo.com/public/webgradients_png/047%20Fly%20High.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #f78ca0 0%, #f9748f 19%, #fd868c 60%, #fe9a8b 100%);",
"image": "https://itmeo.com/public/webgradients_png/048%20Strong%20Bliss.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #feada6 0%, #f5efef 100%);",
"image": "https://itmeo.com/public/webgradients_png/049%20Fresh%20Milk.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #e6e9f0 0%, #eef1f5 100%);",
"image": "https://itmeo.com/public/webgradients_png/050%20Snow%20Again.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #accbee 0%, #e7f0fd 100%);",
"image": "https://itmeo.com/public/webgradients_png/051%20February%20Ink.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-20deg, #e9defa 0%, #fbfcdb 100%);",
"image": "https://itmeo.com/public/webgradients_png/052%20Kind%20Steel.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #c1dfc4 0%, #deecdd 100%);",
"image": "https://itmeo.com/public/webgradients_png/053%20Soft%20Grass.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #0ba360 0%, #3cba92 100%);",
"image": "https://itmeo.com/public/webgradients_png/054%20Grown%20Early.png"
},
{
"name": "Sharp PI:NAME:<NAME>END_PIues",
"css": "background-image: linear-gradient(to top, #00c6fb 0%, #005bea 100%);",
"image": "https://itmeo.com/public/webgradients_png/055%20Sharp%20Blues.png"
},
{
"name": "Shady Water",
"css": "background-image: linear-gradient(to right, #74ebd5 0%, #9face6 100%);",
"image": "https://itmeo.com/public/webgradients_png/056%20Shady%20Water.png"
},
{
"name": "Dirty Beauty",
"css": "background-image: linear-gradient(to top, #6a85b6 0%, #bac8e0 100%);",
"image": "https://itmeo.com/public/webgradients_png/057%20Dirty%20Beauty.png"
},
{
"name": "Great Whale",
"css": "background-image: linear-gradient(to top, #a3bded 0%, #6991c7 100%);",
"image": "https://itmeo.com/public/webgradients_png/058%20Great%20Whale.png"
},
{
"name": "Teen Notebook",
"css": "background-image: linear-gradient(to top, #9795f0 0%, #fbc8d4 100%);",
"image": "https://itmeo.com/public/webgradients_png/059%20Teen%20Notebook.png"
},
{
"name": "Polite Rumors",
"css": "background-image: linear-gradient(to top, #a7a6cb 0%, #8989ba 52%, #8989ba 100%);",
"image": "https://itmeo.com/public/webgradients_png/060%20Polite%20Rumors.png"
},
{
"name": "Sweet Period",
"css": "background-image: linear-gradient(to top, #3f51b1 0%, #5a55ae 13%, #7b5fac 25%, #8f6aae 38%, #a86aa4 50%, #cc6b8e 62%, #f18271 75%, #f3a469 87%, #f7c978 100%);",
"image": "https://itmeo.com/public/webgradients_png/061%20Sweet%20Period.png"
},
{
"name": "Wide Matrix",
"css": "background-image: linear-gradient(to top, #fcc5e4 0%, #fda34b 15%, #ff7882 35%, #c8699e 52%, #7046aa 71%, #0c1db8 87%, #020f75 100%);",
"image": "https://itmeo.com/public/webgradients_png/062%20Wide%20Matrix.png"
},
{
"name": "Soft Cherish",
"css": "background-image: linear-gradient(to top, #dbdcd7 0%, #dddcd7 24%, #e2c9cc 30%, #e7627d 46%, #b8235a 59%, #801357 71%, #3d1635 84%, #1c1a27 100%);",
"image": "https://itmeo.com/public/webgradients_png/063%20Soft%20Cherish.png"
},
{
"name": "Red Salvation",
"css": "background-image: linear-gradient(to top, #f43b47 0%, #453a94 100%);",
"image": "https://itmeo.com/public/webgradients_png/064%20Red%20Salvation.png"
},
{
"name": "Burning Spring",
"css": "background-image: linear-gradient(to top, #4fb576 0%, #44c489 30%, #28a9ae 46%, #28a2b7 59%, #4c7788 71%, #6c4f63 86%, #432c39 100%);",
"image": "https://itmeo.com/public/webgradients_png/065%20Burning%20Spring.png"
},
{
"name": "Night Party",
"css": "background-image: linear-gradient(to top, #0250c5 0%, #d43f8d 100%);",
"image": "https://itmeo.com/public/webgradients_png/066%20Night%20Party.png"
},
{
"name": "Sky PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #88d3ce 0%, #6e45e2 100%);",
"image": "https://itmeo.com/public/webgradients_png/067%20Sky%20Glider.png"
},
{
"name": "Heaven Peach",
"css": "background-image: linear-gradient(to top, #d9afd9 0%, #97d9e1 100%);",
"image": "https://itmeo.com/public/webgradients_png/068%20Heaven%20Peach.png"
},
{
"name": "Purple Division",
"css": "background-image: linear-gradient(to top, #7028e4 0%, #e5b2ca 100%);",
"image": "https://itmeo.com/public/webgradients_png/069%20Purple%20Division.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(15deg, #13547a 0%, #80d0c7 100%);",
"image": "https://itmeo.com/public/webgradients_png/070%20Aqua%20Splash.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to left, #BDBBBE 0%, #9D9EA3 100%), radial-gradient(88% 271%, rgba(255, 255, 255, 0.25) 0%, rgba(254, 254, 254, 0.25) 1%, rgba(0, 0, 0, 0.25) 100%), radial-gradient(50% 100%, rgba(255, 255, 255, 0.30) 0%, rgba(0, 0, 0, 0.30) 100%);\n background-blend-mode: normal, lighten, soft-light;",
"image": "https://itmeo.com/public/webgradients_png/5)%201%,%20rgba(0,%200,%200,%200.25)%20100%),%20radial-gradien.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #505285 0%, #585e92 12%, #65689f 25%, #7474b0 37%, #7e7ebb 50%, #8389c7 62%, #9795d4 75%, #a2a1dc 87%, #b5aee4 100%);",
"image": "https://itmeo.com/public/webgradients_png/072%20Spiky%20Naga.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #ff0844 0%, #ffb199 100%);",
"image": "https://itmeo.com/public/webgradients_png/073%20Love%20Kiss.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background: #C9CCD3;\n background-image: linear-gradient(-180deg, rgba(255,255,255,0.50) 0%, rgba(0,0,0,0.50) 100%);\n background-blend-mode: lighten;",
"image": "https://itmeo.com/public/webgradients_png/074%20Sharp%20Glass.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(45deg, #93a5cf 0%, #e4efe9 100%);",
"image": "https://itmeo.com/public/webgradients_png/075%20Clean%20Mirror.png"
},
{
"name": "Premium Dark",
"css": "background-image: linear-gradient(to right, #434343 0%, black 100%);",
"image": "https://itmeo.com/public/webgradients_png/076%20Premium%20Dark.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #0c3483 0%, #a2b6df 100%, #6b8cce 100%, #a2b6df 100%);",
"image": "https://itmeo.com/public/webgradients_png/077%20Cold%20Evening.png"
},
{
"name": "PI:NAME:<NAME>END_PI Lake",
"css": "background-image: linear-gradient(45deg, #93a5cf 0%, #e4efe9 100%);",
"image": "https://itmeo.com/public/webgradients_png/078%20Cochiti%20Lake.png"
},
{
"name": "Summer Games",
"css": "background-image: linear-gradient(to right, #92fe9d 0%, #00c9ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/079%20Summer%20Games.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #ff758c 0%, #ff7eb3 100%);",
"image": "https://itmeo.com/public/webgradients_png/080%20Passionate%20Bed.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #868f96 0%, #596164 100%);",
"image": "https://itmeo.com/public/webgradients_png/081%20Mountain%20Rock.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #c79081 0%, #dfa579 100%);",
"image": "https://itmeo.com/public/webgradients_png/082%20Desert%20Hump.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(45deg, #8baaaa 0%, #ae8b9c 100%);",
"image": "https://itmeo.com/public/webgradients_png/083%20Jungle%20Day.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #f83600 0%, #f9d423 100%);",
"image": "https://itmeo.com/public/webgradients_png/084%20Phoenix%20Start.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-20deg, #b721ff 0%, #21d4fd 100%);",
"image": "https://itmeo.com/public/webgradients_png/085%20October%20Silence.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-20deg, #6e45e2 0%, #88d3ce 100%);",
"image": "https://itmeo.com/public/webgradients_png/086%20Faraway%20River.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-20deg, #d558c8 0%, #24d292 100%);",
"image": "https://itmeo.com/public/webgradients_png/087%20Alchemist%20Lab.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(60deg, #abecd6 0%, #fbed96 100%);",
"image": "https://itmeo.com/public/webgradients_png/088%20Over%20Sun.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #d5d4d0 0%, #d5d4d0 1%, #eeeeec 31%, #efeeec 75%, #e9e9e7 100%);",
"image": "https://itmeo.com/public/webgradients_png/089%20Premium%20White.png"
},
{
"name": "Mars Party",
"css": "background-image: linear-gradient(to top, #5f72bd 0%, #9b23ea 100%);",
"image": "https://itmeo.com/public/webgradients_png/090%20Mars%20Party.png"
},
{
"name": "Eternal Constance",
"css": "background-image: linear-gradient(to top, #09203f 0%, #537895 100%);",
"image": "https://itmeo.com/public/webgradients_png/091%20Eternal%20Constance.png"
},
{
"name": "Japan Blush",
"css": "background-image: linear-gradient(-20deg, #ddd6f3 0%, #faaca8 100%, #faaca8 100%);",
"image": "https://itmeo.com/public/webgradients_png/092%20Japan%20Blush.png"
},
{
"name": "Smiling Rain",
"css": "background-image: linear-gradient(-20deg, #dcb0ed 0%, #99c99c 100%);",
"image": "https://itmeo.com/public/webgradients_png/093%20Smiling%20Rain.png"
},
{
"name": "Cloudy Apple",
"css": "background-image: linear-gradient(to top, #f3e7e9 0%, #e3eeff 99%, #e3eeff 100%);",
"image": "https://itmeo.com/public/webgradients_png/094%20Cloudy%20Apple.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #c71d6f 0%, #d09693 100%);",
"image": "https://itmeo.com/public/webgradients_png/095%20Big%20Mango.png"
},
{
"name": "Healthy Water",
"css": "background-image: linear-gradient(60deg, #96deda 0%, #50c9c3 100%);",
"image": "https://itmeo.com/public/webgradients_png/096%20Healthy%20Water.png"
},
{
"name": "Amour Amour",
"css": "background-image: linear-gradient(to top, #f77062 0%, #fe5196 100%);",
"image": "https://itmeo.com/public/webgradients_png/097%20Amour%20Amour.png"
},
{
"name": "Risky Concrete",
"css": "background-image: linear-gradient(to top, #c4c5c7 0%, #dcdddf 52%, #ebebeb 100%);",
"image": "https://itmeo.com/public/webgradients_png/098%20Risky%20Concrete.png"
},
{
"name": "Strong Stick",
"css": "background-image: linear-gradient(to right, #a8caba 0%, #5d4157 100%);",
"image": "https://itmeo.com/public/webgradients_png/099%20Strong%20Stick.png"
},
{
"name": "Vicious Stance",
"css": "background-image: linear-gradient(60deg, #29323c 0%, #485563 100%);",
"image": "https://itmeo.com/public/webgradients_png/100%20Vicious%20Stance.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-60deg, #16a085 0%, #f4d03f 100%);",
"image": "https://itmeo.com/public/webgradients_png/101%20Palo%20Alto.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-60deg, #ff5858 0%, #f09819 100%);",
"image": "https://itmeo.com/public/webgradients_png/102%20Happy%20Memories.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-20deg, #2b5876 0%, #4e4376 100%);",
"image": "https://itmeo.com/public/webgradients_png/103%20Midnight%20Bloom.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-20deg, #00cdac 0%, #8ddad5 100%);",
"image": "https://itmeo.com/public/webgradients_png/104%20Crystalline.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background: linear-gradient(-180deg, #BCC5CE 0%, #929EAD 98%), radial-gradient(at top left, rgba(255,255,255,0.30) 0%, rgba(0,0,0,0.30) 100%);\n background-blend-mode: screen;",
"image": "https://itmeo.com/public/webgradients_png/105%20Raccoon%20Back.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #4481eb 0%, #04befe 100%);",
"image": "https://itmeo.com/public/webgradients_png/106%20Party%20Bliss.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #dad4ec 0%, #dad4ec 1%, #f3e7e9 100%);",
"image": "https://itmeo.com/public/webgradients_png/107%20Confident%20Cloud.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(45deg, #874da2 0%, #c43a30 100%);",
"image": "https://itmeo.com/public/webgradients_png/108%20Le%20Cocktail.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #4481eb 0%, #04befe 100%);",
"image": "https://itmeo.com/public/webgradients_png/109%20River%20City.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #e8198b 0%, #c7eafd 100%);",
"image": "https://itmeo.com/public/webgradients_png/110%20Frozen%20Berry.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: radial-gradient(73% 147%, #EADFDF 59%, #ECE2DF 100%), radial-gradient(91% 146%, rgba(255,255,255,0.50) 47%, rgba(0,0,0,0.50) 100%);\n background-blend-mode: screen;",
"image": "https://itmeo.com/public/webgradients_png/111%20Elegance.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-20deg, #f794a4 0%, #fdd6bd 100%);",
"image": "https://itmeo.com/public/webgradients_png/112%20Child%20Care.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(60deg, #64b3f4 0%, #c2e59c 100%);",
"image": "https://itmeo.com/public/webgradients_png/113%20Flying%20Lemon.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #3b41c5 0%, #a981bb 49%, #ffc8a9 100%);",
"image": "https://itmeo.com/public/webgradients_png/114%20New%20Retrowave.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #0fd850 0%, #f9f047 100%);",
"image": "https://itmeo.com/public/webgradients_png/115%20Hidden%20Jaguar.png"
},
{
"name": "Above The Sky",
"css": "background-image: linear-gradient(to top, lightgrey 0%, lightgrey 1%, #e0e0e0 26%, #efefef 48%, #d9d9d9 75%, #bcbcbc 100%);",
"image": "https://itmeo.com/public/webgradients_png/116%20Above%20The%20Sky.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(45deg, #ee9ca7 0%, #ffdde1 100%);",
"image": "https://itmeo.com/public/webgradients_png/117%20Nega.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #3ab5b0 0%, #3d99be 31%, #56317a 100%);",
"image": "https://itmeo.com/public/webgradients_png/118%20Dense%20Water.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-color: #CDDCDC;\n background-image: radial-gradient(at 50% 100%, rgba(255,255,255,0.50) 0%, rgba(0,0,0,0.50) 100%), linear-gradient(to bottom, rgba(255,255,255,0.25) 0%, rgba(0,0,0,0.25) 100%);\n background-blend-mode: screen, overlay;",
"image": "https://itmeo.com/public/webgradients_png/119%20Chemic%20Aqua.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #209cff 0%, #68e0cf 100%);",
"image": "https://itmeo.com/public/webgradients_png/120%20Seashore.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #bdc2e8 0%, #bdc2e8 1%, #e6dee9 100%);",
"image": "https://itmeo.com/public/webgradients_png/121%20Marble%20Wall.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #e6b980 0%, #eacda3 100%);",
"image": "https://itmeo.com/public/webgradients_png/122%20Cheerful%20Caramel.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #1e3c72 0%, #1e3c72 1%, #2a5298 100%);",
"image": "https://itmeo.com/public/webgradients_png/123%20Night%20Sky.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #d5dee7 0%, #ffafbd 0%, #c9ffbf 100%);",
"image": "https://itmeo.com/public/webgradients_png/124%20Magic%20Lake.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #9be15d 0%, #00e3ae 100%);",
"image": "https://itmeo.com/public/webgradients_png/125%20Young%20Grass.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #ed6ea0 0%, #ec8c69 100%);",
"image": "https://itmeo.com/public/webgradients_png/126%20Colorful%20Peach.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #ffc3a0 0%, #ffafbd 100%);",
"image": "https://itmeo.com/public/webgradients_png/127%20Gentle%20Care.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #cc208e 0%, #6713d2 100%);",
"image": "https://itmeo.com/public/webgradients_png/128%20Plum%20Bath.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #b3ffab 0%, #12fff7 100%);",
"image": "https://itmeo.com/public/webgradients_png/129%20Happy%20Unicorn.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background: linear-gradient(to bottom, #D5DEE7 0%, #E8EBF2 50%, #E2E7ED 100%), linear-gradient(to bottom, rgba(0,0,0,0.02) 50%, rgba(255,255,255,0.02) 61%, rgba(0,0,0,0.02) 73%), linear-gradient(33deg, rgba(255,255,255,0.20) 0%, rgba(0,0,0,0.20) 100%);\n background-blend-mode: normal,color-burn;",
"image": "https://itmeo.com/public/webgradients_png/130%20Full%20Metal.png"
},
{
"name": "AfrPI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #65bd60 0%, #5ac1a8 25%, #3ec6ed 50%, #b7ddb7 75%, #fef381 100%);",
"image": "https://itmeo.com/public/webgradients_png/131%20African%20Field.png"
},
{
"name": "Solid Stone",
"css": "background-image: linear-gradient(to right, #243949 0%, #517fa4 100%);",
"image": "https://itmeo.com/public/webgradients_png/132%20Solid%20Stone.png"
},
{
"name": "Orange Juice",
"css": "background-image: linear-gradient(-20deg, #fc6076 0%, #ff9a44 100%);",
"image": "https://itmeo.com/public/webgradients_png/133%20Orange%20Juice.png"
},
{
"name": "Glass Water",
"css": "background-image: linear-gradient(to top, #dfe9f3 0%, white 100%);",
"image": "https://itmeo.com/public/webgradients_png/134%20Glass%20Water.png"
},
{
"name": "PI:NAME:<NAME>END_PI Carbon",
"css": "background: linear-gradient(to bottom, #323232 0%, #3F3F3F 40%, #1C1C1C 150%), linear-gradient(to top, rgba(255,255,255,0.40) 0%, rgba(0,0,0,0.25) 200%);\n background-blend-mode: multiply;",
"image": "https://itmeo.com/public/webgradients_png/135%20Slick%20Carbon.png"
},
{
"name": "North Miracle",
"css": "background-image: linear-gradient(to right, #00dbde 0%, #fc00ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/136%20North%20Miracle.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #f9d423 0%, #ff4e50 100%);",
"image": "https://itmeo.com/public/webgradients_png/137%20Fruit%20Blend.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #50cc7f 0%, #f5d100 100%);",
"image": "https://itmeo.com/public/webgradients_png/138%20Millennium%20Pine.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #0acffe 0%, #495aff 100%);",
"image": "https://itmeo.com/public/webgradients_png/139%20High%20Flight.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-20deg, #616161 0%, #9bc5c3 100%);",
"image": "https://itmeo.com/public/webgradients_png/140%20Mole%20Hall.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-color: #E4E4E1;\n background-image: radial-gradient(at top center, rgba(255,255,255,0.03) 0%, rgba(0,0,0,0.03) 100%), linear-gradient(to top, rgba(255,255,255,0.1) 0%, rgba(143,152,157,0.60) 100%);\n \tbackground-blend-mode: normal, multiply;",
"image": "https://itmeo.com/public/webgradients_png/141%20Earl%20Gray.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(60deg, #3d3393 0%, #2b76b9 37%, #2cacd1 65%, #35eb93 100%);",
"image": "https://itmeo.com/public/webgradients_png/142%20Space%20Shift.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #df89b5 0%, #bfd9fe 100%);",
"image": "https://itmeo.com/public/webgradients_png/143%20Forest%20Inei.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #ed6ea0 0%, #ec8c69 100%);",
"image": "https://itmeo.com/public/webgradients_png/144%20Royal%20Garden.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #d7d2cc 0%, #304352 100%);",
"image": "https://itmeo.com/public/webgradients_png/145%20Rich%20Metal.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to top, #e14fad 0%, #f9d423 100%);",
"image": "https://itmeo.com/public/webgradients_png/146%20Juicy%20Cake.png"
},
{
"name": "Smart Indigo",
"css": "background-image: linear-gradient(to top, #b224ef 0%, #7579ff 100%);",
"image": "https://itmeo.com/public/webgradients_png/147%20Smart%20Indigo.png"
},
{
"name": "Sand PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(to right, #c1c161 0%, #c1c161 0%, #d4d4b1 100%);",
"image": "https://itmeo.com/public/webgradients_png/148%20Sand%20Strike.png"
},
{
"name": "Norse Beauty",
"css": "background-image: linear-gradient(to right, #ec77ab 0%, #7873f5 100%);",
"image": "https://itmeo.com/public/webgradients_png/149%20Norse%20Beauty.png"
},
{
"name": "Aqua Guidance",
"css": "background-image: linear-gradient(to top, #007adf 0%, #00ecbc 100%);",
"image": "https://itmeo.com/public/webgradients_png/150%20Aqua%20Guidance.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #20E2D7 0%, #F9FEA5 100%);",
"image": "https://itmeo.com/public/webgradients_png/151%20Sun%20Veggie.png"
},
{
"name": "Sea Lord",
"css": "background-image: linear-gradient(-225deg, #2CD8D5 0%, #C5C1FF 56%, #FFBAC3 100%);",
"image": "https://itmeo.com/public/webgradients_png/152%20Sea%20Lord.png"
},
{
"name": "Black Sea",
"css": "background-image: linear-gradient(-225deg, #2CD8D5 0%, #6B8DD6 48%, #8E37D7 100%);",
"image": "https://itmeo.com/public/webgradients_png/153%20Black%20Sea.png"
},
{
"name": "PI:NAME:<NAME>END_PIass Shampoo",
"css": "background-image: linear-gradient(-225deg, #DFFFCD 0%, #90F9C4 48%, #39F3BB 100%);",
"image": "https://itmeo.com/public/webgradients_png/154%20Grass%20Shampoo.png"
},
{
"name": "Landing Aircraft",
"css": "background-image: linear-gradient(-225deg, #5D9FFF 0%, #B8DCFF 48%, #6BBBFF 100%);",
"image": "https://itmeo.com/public/webgradients_png/155%20Landing%20Aircraft.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #A8BFFF 0%, #884D80 100%);",
"image": "https://itmeo.com/public/webgradients_png/156%20Witch%20Dance.png"
},
{
"name": "Sleepless Night",
"css": "background-image: linear-gradient(-225deg, #5271C4 0%, #B19FFF 48%, #ECA1FE 100%);",
"image": "https://itmeo.com/public/webgradients_png/157%20Sleepless%20Night.png"
},
{
"name": "PI:NAME:<NAME>END_PI Care",
"css": "background-image: linear-gradient(-225deg, #FFE29F 0%, #FFA99F 48%, #FF719A 100%);",
"image": "https://itmeo.com/public/webgradients_png/158%20Angel%20Care.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #22E1FF 0%, #1D8FE1 48%, #625EB1 100%);",
"image": "https://itmeo.com/public/webgradients_png/159%20Crystal%20River.png"
},
{
"name": "Soft PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #B6CEE8 0%, #F578DC 100%);",
"image": "https://itmeo.com/public/webgradients_png/160%20Soft%20Lipstick.png"
},
{
"name": "Salt Mountain",
"css": "background-image: linear-gradient(-225deg, #FFFEFF 0%, #D7FFFE 100%);",
"image": "https://itmeo.com/public/webgradients_png/161%20Salt%20Mountain.png"
},
{
"name": "Perfect White",
"css": "background-image: linear-gradient(-225deg, #E3FDF5 0%, #FFE6FA 100%);",
"image": "https://itmeo.com/public/webgradients_png/162%20Perfect%20White.png"
},
{
"name": "Fresh Oasis",
"css": "background-image: linear-gradient(-225deg, #7DE2FC 0%, #B9B6E5 100%);",
"image": "https://itmeo.com/public/webgradients_png/163%20Fresh%20Oasis.png"
},
{
"name": "Strict November",
"css": "background-image: linear-gradient(-225deg, #CBBACC 0%, #2580B3 100%);",
"image": "https://itmeo.com/public/webgradients_png/164%20Strict%20November.png"
},
{
"name": "Morning Salad",
"css": "background-image: linear-gradient(-225deg, #B7F8DB 0%, #50A7C2 100%);",
"image": "https://itmeo.com/public/webgradients_png/165%20Morning%20Salad.png"
},
{
"name": "Deep Relief",
"css": "background-image: linear-gradient(-225deg, #7085B6 0%, #87A7D9 50%, #DEF3F8 100%);",
"image": "https://itmeo.com/public/webgradients_png/166%20Deep%20Relief.png"
},
{
"name": "Sea Strike",
"css": "background-image: linear-gradient(-225deg, #77FFD2 0%, #6297DB 48%, #1EECFF 100%);",
"image": "https://itmeo.com/public/webgradients_png/167%20Sea%20Strike.png"
},
{
"name": "Night Call",
"css": "background-image: linear-gradient(-225deg, #AC32E4 0%, #7918F2 48%, #4801FF 100%);",
"image": "https://itmeo.com/public/webgradients_png/168%20Night%20Call.png"
},
{
"name": "Supreme Sky",
"css": "background-image: linear-gradient(-225deg, #D4FFEC 0%, #57F2CC 48%, #4596FB 100%);",
"image": "https://itmeo.com/public/webgradients_png/169%20Supreme%20Sky.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #9EFBD3 0%, #57E9F2 48%, #45D4FB 100%);",
"image": "https://itmeo.com/public/webgradients_png/170%20Light%20Blue.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #473B7B 0%, #3584A7 51%, #30D2BE 100%);",
"image": "https://itmeo.com/public/webgradients_png/171%20Mind%20Crawl.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #65379B 0%, #886AEA 53%, #6457C6 100%);",
"image": "https://itmeo.com/public/webgradients_png/172%20Lily%20Meadow.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #A445B2 0%, #D41872 52%, #FF0066 100%);",
"image": "https://itmeo.com/public/webgradients_png/173%20Sugar%20Lollipop.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #7742B2 0%, #F180FF 52%, #FD8BD9 100%);",
"image": "https://itmeo.com/public/webgradients_png/174%20Sweet%20Dessert.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #FF3CAC 0%, #562B7C 52%, #2B86C5 100%);",
"image": "https://itmeo.com/public/webgradients_png/175%20Magic%20Ray.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #FF057C 0%, #8D0B93 50%, #321575 100%);",
"image": "https://itmeo.com/public/webgradients_png/176%20Teen%20Party.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #FF057C 0%, #7C64D5 48%, #4CC3FF 100%);",
"image": "https://itmeo.com/public/webgradients_png/177%20Frozen%20Heat.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #69EACB 0%, #EACCF8 48%, #6654F1 100%);",
"image": "https://itmeo.com/public/webgradients_png/178%20Gagarin%20View.png"
},
{
"name": "Fabled Sunset",
"css": "background-image: linear-gradient(-225deg, #231557 0%, #44107A 29%, #FF1361 67%, #FFF800 100%);",
"image": "https://itmeo.com/public/webgradients_png/179%20Fabled%20Sunset.png"
},
{
"name": "PI:NAME:<NAME>END_PI",
"css": "background-image: linear-gradient(-225deg, #3D4E81 0%, #5753C9 48%, #6E7FF3 100%);",
"image": "https://itmeo.com/public/webgradients_png/180%20Perfect%20Blue.png"
}
]
module.exports = {
gradients: gradients
getCSS: (name) ->
gradients.find((item) -> item.name is name)?.css
getImage: (name) ->
gradients.find((item) -> item.name is name)?.image
}
|
[
{
"context": "des as described on the [wiki](https://github.com/greenheartgames/gdt-modAPI/wiki/missionOverrides)\n---\n@customType",
"end": 3874,
"score": 0.9993229508399963,
"start": 3859,
"tag": "USERNAME",
"value": "greenheartgames"
},
{
"context": "il.Filesystem.Path()\n\n\t\tconvert: ->\n\t\t\t{\n\t\t\t\tname: @name\n\t\t\t\tid: @id\n\t\t\t\tcompany: @company\n\t\t\t\tstartAm",
"end": 51723,
"score": 0.9804065227508545,
"start": 51723,
"tag": "NAME",
"value": ""
},
{
"context": ".Filesystem.Path()\n\n\t\tconvert: ->\n\t\t\t{\n\t\t\t\tname: @name\n\t\t\t\tid: @id\n\t\t\t\tcompany: @company\n\t\t\t\tstartAmount",
"end": 51729,
"score": 0.417845219373703,
"start": 51725,
"tag": "NAME",
"value": "name"
},
{
"context": "ons[1]] = value\n\t\t\t@\n\n\t\tconvert: ->\n\t\t\t{\n\t\t\t\tname: @name\n\t\t\t\tid: @id\n\t\t\t\tgenreWeight: convertClasses(@",
"end": 53201,
"score": 0.9926082491874695,
"start": 53201,
"tag": "NAME",
"value": ""
},
{
"context": "s[1]] = value\n\t\t\t@\n\n\t\tconvert: ->\n\t\t\t{\n\t\t\t\tname: @name\n\t\t\t\tid: @id\n\t\t\t\tgenreWeight: convertClasses(@genr",
"end": 53207,
"score": 0.5569977760314941,
"start": 53203,
"tag": "NAME",
"value": "name"
},
{
"context": "rgetZone ?= 2\n\n\t\tconvert: ->\n\t\t\titem = {\n\t\t\t\tname: @name\n\t\t\t\tid: @id\n\t\t\t\tdescription: @description\n\t\t\t",
"end": 53570,
"score": 0.9946721196174622,
"start": 53570,
"tag": "NAME",
"value": ""
},
{
"context": "etZone ?= 2\n\n\t\tconvert: ->\n\t\t\titem = {\n\t\t\t\tname: @name\n\t\t\t\tid: @id\n\t\t\t\tdescription: @description\n\t\t\t\tpoi",
"end": 53576,
"score": 0.642490804195404,
"start": 53572,
"tag": "NAME",
"value": "name"
},
{
"context": "duration ?= 0\n\n\t\tconvert: ->\n\t\t\titem = {\n\t\t\t\tname: @name\n\t\t\t\tid: @id\n\t\t\t\tcost: @cost\n\t\t\t\tpointsCost: @",
"end": 54153,
"score": 0.9967755675315857,
"start": 54153,
"tag": "NAME",
"value": ""
},
{
"context": "ration ?= 0\n\n\t\tconvert: ->\n\t\t\titem = {\n\t\t\t\tname: @name\n\t\t\t\tid: @id\n\t\t\t\tcost: @cost\n\t\t\t\tpointsCost: @poin",
"end": 54159,
"score": 0.507758617401123,
"start": 54155,
"tag": "NAME",
"value": "name"
},
{
"context": "?= 0\n\t\t\t@dF ?= 0\n\n\t\tconvert:\n\t\t\titem = {\n\t\t\t\tname: @name\n\t\t\t\tid: @id\n\t\t\t\tsize: @size\n\t\t\t\tdescription: ",
"end": 54699,
"score": 0.9722310304641724,
"start": 54699,
"tag": "NAME",
"value": ""
},
{
"context": " 0\n\t\t\t@dF ?= 0\n\n\t\tconvert:\n\t\t\titem = {\n\t\t\t\tname: @name\n\t\t\t\tid: @id\n\t\t\t\tsize: @size\n\t\t\t\tdescription: @des",
"end": 54705,
"score": 0.6749003529548645,
"start": 54701,
"tag": "NAME",
"value": "name"
},
{
"context": "s classes.Publisher extends Base\n\t\tconstructor: (@name, @id) ->\n\t\t\tsuper\n\n\t\tconvert: ->\n\t\t\titem = {\n\t\t\t\t",
"end": 54962,
"score": 0.7857767343521118,
"start": 54958,
"tag": "NAME",
"value": "name"
},
{
"context": ") ->\n\t\t\tsuper\n\n\t\tconvert: ->\n\t\t\titem = {\n\t\t\t\tname: @name\n\t\t\t\tid: @id\n\t\t\t\tcard: @card\n\t\t\t\tgenerateCard:",
"end": 55017,
"score": 0.9901939034461975,
"start": 55017,
"tag": "NAME",
"value": ""
},
{
"context": "->\n\t\t\tsuper\n\n\t\tconvert: ->\n\t\t\titem = {\n\t\t\t\tname: @name\n\t\t\t\tid: @id\n\t\t\t\tcard: @card\n\t\t\t\tgenerateCard: if ",
"end": 55023,
"score": 0.659626841545105,
"start": 55019,
"tag": "NAME",
"value": "name"
},
{
"context": "lts\n\t\t\tgetSettings: (company, size) ->\n\t\t\t\tkey = \"contracts#{size}\"\n\t\t\t\tsettings = company.flags[key]\n\t\t\t\tif not sett",
"end": 66561,
"score": 0.9804943203926086,
"start": 66544,
"tag": "KEY",
"value": "contracts#{size}\""
},
{
"context": " \"Electronic Mass Productions\"\n\t\t}, {\n\t\t\tid: \"RockvilleSoftworks\",\n\t\t\tname: \"Rockville Softworks\"\n\t\t}, {\n\t\t\tid: \"B",
"end": 71391,
"score": 0.5748599171638489,
"start": 71377,
"tag": "USERNAME",
"value": "villeSoftworks"
},
{
"context": "\t\t\tname: \"Rockville Softworks\"\n\t\t}, {\n\t\t\tid: \"BlueBitGames\",\n\t\t\tname: \"Blue Bit Games\"\n\t\t}, {\n\t\t\tid: \"CapeCo",
"end": 71452,
"score": 0.5290639400482178,
"start": 71444,
"tag": "USERNAME",
"value": "BitGames"
},
{
"context": "es\",\n\t\t\tname: \"Blue Bit Games\"\n\t\t}, {\n\t\t\tid: \"CapeCom\",\n\t\t\tname: \"CapeCom\"\n\t\t}, {\n\t\t\tid: \"Codemeisters\"",
"end": 71503,
"score": 0.5978630185127258,
"start": 71500,
"tag": "USERNAME",
"value": "Com"
},
{
"context": "\tid: \"CapeCom\",\n\t\t\tname: \"CapeCom\"\n\t\t}, {\n\t\t\tid: \"Codemeisters\",\n\t\t\tname: \"Codemeisters\"\n\t\t}, {\n\t\t\tid: \"DeepPlat",
"end": 71552,
"score": 0.8018162250518799,
"start": 71540,
"tag": "USERNAME",
"value": "Codemeisters"
},
{
"context": "\t\t\tid: \"TGQ\",\n\t\t\tname: \"TGQ\"\n\t\t}, {\n\t\t\tid: \"\\u00dcberSoft\",\n\t\t\tname: \"\\u00dcberSoft\"\n\t\t}]`\n\t\tGDT.Publisher ",
"end": 71813,
"score": 0.6601723432540894,
"start": 71806,
"tag": "USERNAME",
"value": "berSoft"
},
{
"context": "ame: \"TGQ\"\n\t\t}, {\n\t\t\tid: \"\\u00dcberSoft\",\n\t\t\tname: \"\\u00dcberSoft\"\n\t\t}]`\n\t\tGDT.Publisher = {\n\t\t\tpublish",
"end": 71824,
"score": 0.9256337285041809,
"start": 71824,
"tag": "USERNAME",
"value": ""
},
{
"context": "TGQ\"\n\t\t}, {\n\t\t\tid: \"\\u00dcberSoft\",\n\t\t\tname: \"\\u00dcberSoft\"\n\t\t}]`\n\t\tGDT.Publisher = {\n\t\t\tpublishers: publish",
"end": 71839,
"score": 0.9421396851539612,
"start": 71830,
"tag": "USERNAME",
"value": "dcberSoft"
},
{
"context": "pany(\"Ninvento\")\n\tCompanies.createVanillaCompany(\"Vena\")\n\tCompanies.createVanillaCompany(\"Vonny\")\n\tCompa",
"end": 99858,
"score": 0.8950101733207703,
"start": 99854,
"tag": "NAME",
"value": "Vena"
},
{
"context": "aCompany(\"Vena\")\n\tCompanies.createVanillaCompany(\"Vonny\")\n\tCompanies.createVanillaCompany(\"KickIT\")\n]\nCom",
"end": 99899,
"score": 0.9720008969306946,
"start": 99894,
"tag": "NAME",
"value": "Vonny"
},
{
"context": " takenNames.indexOf(name) != -1\n\t\ttakenNames.push(name)\n\t\tsalary = Character.BASE_SALARY_PER_LEVEL * lev",
"end": 105003,
"score": 0.7997264266014099,
"start": 104999,
"tag": "NAME",
"value": "name"
},
{
"context": "salary/1e3) * 1e3\n\t\tnewApplicants.push {\n\t\t\tname : name,\n\t\t\tqualityFactor : q,\n\t\t\ttechnologyFactor : t / ",
"end": 105198,
"score": 0.8865352272987366,
"start": 105194,
"tag": "NAME",
"value": "name"
}
] | main.coffee | Spartan322/Spartan-Dev-Project | 1 | ### Definitions for the devised SpartaDoc
All types can either contain the name of the types as found here or the vanilla API as analogs, this is corrected by the SDP
---
@customType ResearchItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [String] type The SDP.GDT.Research.types string this represents
@instruction('optional' if 'v')
@attribute [Integer] pointsCost The cost of the research in research points
@attribute [Integer] duration The time it takes to complete the research in milliseconds
@attribute [Integer] researchCost The cost this research will take to research, without devCost, small scale devCost = researchCost * 4
@instruction('optional' if 'researchCost') @attribute [Integer] devCost The cost to develop with this research on in small scale
@attribute [Integer] engineCost The cost to put this into an engine
@defaults(pointsCost) @attribute [Integer] enginePoints The amount of points this will cost to put in an engine
@attribute [String] category May be SDP.Constants.ResearchCategory of the object, or maybe something else
@attribute [String] categoryDisplayName Similar to category, human readable version
@optional
@attribute [Integer] v A basic value to scale the research by
@attribute [String] group The group to assign this research to, prevents more then one group being selected on games
@attribute [Boolean] consolePart Whether this research applies to console creation as well
@attribute [Boolean] engineStart Whether the research is available to all engines without research, overrides canResearch to always return false
@attribute [Function(Game)] canUse Determines whether this research can be used
@fparam [Game] game The game to test use against
@freturn [Boolean] Whether the research can be used
@attribute [Function(CompanyItem)] canResearch Determines whether this research is allowed to be researched
@fparam [CompanyItem] company The company to check whether its researchable for
@freturn [Boolean] Whether the research can be researched
---
@customType PlatformItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [String] company The company name this platform belongs to
@attribute [Float] startAmount The starting amount of units sold on release (multiplied by 5000000)
@attribute [Float] unitsSold The resulting units sold by the end (multiplied by 5000000)
@attribute [Integer] licensePrice The one time license price to develop on the platform
@attribute [String] publishDate The release date of the platform
@attribute [String] retireDate The retire date of the platform
@attribute [Integer] devCost The dev cost for developing on the platform
@attribute [Integer] techLevel The tech level of the platform (1-9, determines how ingenious the platform and the games for it will be)
@attribute [String] iconUri The icon refered to for the icon of the platform (or base uri if contains imageDates)
@attribute [Array {String date, Float amount}] marketPoints The key date points of the market in which the units sold change to the amount
@attribute [Array [6 Float]] genreWeight The weightings per genre based on SDP.Constants.Genre
@attribute [Array [3 Float]] audienceWeight The weightings per audience based on SDP.Constants.Audience
@optional @attribute [Array [String]] imageDates The dates for the platform image to change
---
@customType TopicItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [Array [6 Float]] genreWeight The weightings per genre based on SDP.Constants.Genre
@attribute [Array [3 Float]] audienceWeight The weightings per audience based on SDP.Constants.Audience
@attribute [Array [6 Array [9 Float]]] overrides The mission overrides as described on the [wiki](https://github.com/greenheartgames/gdt-modAPI/wiki/missionOverrides)
---
@customType ResearchProjectItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [String] description The description of the project
@attribute [Integer] pointsCost The cost to make in research points
@attribute [String] iconUri The uri of the icon to display for the project
@attribute [Integer] targetZone The zone for the project to take place in (0 for Hardware Lab, 2 for Research Lab, Effects of 1 unknown)
@optional @attribute [Boolean] repeatable Determiners whether the project can be repeated
@optional @attribute [Function(CompanyItem)] canResearch Determines whether research can be done
@fparam [CompanyItem] company The company being tested
@freturn [Boolean] Whether research can be done on the project
@optional @attribute [Function(CompanyItem)] complete A function to perform on completion
@fparam [CompanyItem] company The company responsible for completing the project
@optional @attribute [Function(CompanyItem)] cancel Activates on cancelation of the project
@fparam [CompanyItem] company The company canceling the project
---
@customType TrainingItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [Integer] pointsCost The cost in research points
@attribute [Integer] duration How long it will take to complete the training
@attribute [String] category The category of the object
@attribute [String] categoryDisplayName Similar to category, human readable version
@optional
@attribute [Integer] cost The cost in money
@attribute [Function(CharacterObject, CompanyItem)] canSee Determines whether the staff can see this training
@fparam [CharacterObject] staff The staff that should be able to see the training
@fparam [CompanyItem] company The company the training is taken place in
@freturn [Boolean] Whether the training can be seen
@attribute [Function(CharacterObject, CompanyItem)] canUse Determines whether the staff can use this training
@fparam [CharacterObject] staff The staff that should be able to use the training
@fparam [CompanyItem] company The company the training is taken place in
@freturn [Boolean] Whether the training can be used
@attribute [Function(CharacterObject, Integer)] tick Triggers every game tick this training is active
@fparam [CharacterObject] staff The staff that is performing the training
@fparam [Integer] delta The amount of milliseconds passed from the last tick
@attribute [Function(CharacterObject)] complete Triggers on training completion
@fparam [CharacterObject] staff The staff to complete the training
---
@customType ContractItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [String] description The description of the contract
@attribute [String] size The size of the contract, either small, medium, or large
@attribute [Float] tF The tech factor of the contract
@attribute [Float] dF The design factor of the contract
@optional
@attribute [Function(CompanyItem, MersenneTwister)] generateCard Generates a contract card depending on the company and random
@fparam [CompanyItem] company The company to generate the card for
@fparam [MersenneTwister] random The random object used for generating the contract
@freturn [ContractCardItem] The card item representing the contract generated
@attribute [ContractCardItem] card The card item to repsent the contract definitely (generateCard takes priority)
@attribute [Function(CompanyItem)] complete A function to perform on completion
@fparam [CompanyItem] company The company responsible for completing the contract
@note generateCard and card can be ignored if tF and dF are supplied and vice versa
@optional
@attribute [Float] rF The research factor generated
---
@customType PublisherItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
---
@customType ReviewerItem
---
@customType NotificationItem
@attribute [String] header The header of the notification
@attribute [String] text The text to display upon notifcation being tiggered
@instruction('optional' if 'options')
@attribute [String] buttonTxt The text for the button to display
@instruction('optional' if 'buttonTxt')
@attribute [Array [1-3 String]] options A collection of possible button options to choose from
@optional
@attribute [String] image The image uri for the notification
@attribute [String] sourceId The id of the corresponding event object
@attribute [Integer] weeksUntilFire The amount of weeks that must pass before this notification is fired
---
@customType EventItem
@attribute [String] id The id of the event
@attribute [Function(CompanyItem)] trigger Determines whether the event can trigger
@fparam [CompanyItem] company The company to test this trigger by
@instruction('optional' if 'getNotification') @attribute [NotificationItem] notification The notification for this event (overrides getNotification)
@instruction('optional' if 'notification') @attribute [Function(CompanyItem)] Retrieves a notification for this event
@fparam [CompanyItem] company The company to retrieve the notification for
@freturn [NotificationItem] The notification that was produced
@optional
@attribute [Boolean] isRandomEvent Determines whether this event is random
@attribute [Function(Integer)] complete Determines what happens upon completion (this.runningCompany refers to the active company for this event)
@fparam [Integer] decision The decision chosen in the notification from 0 to 2
---
@customType ContractCardItem
@optional
@attribute [Integer] techPoints The tech points to generate for the contract (overrides tF)
@attribute [Integer] designPoints The design points to generate for the contract (overrides dF)
@attribute [Float] tF The tech factor generated for the card
@attribute [Float] dF The design factor generated for the card
@attribute [Integer] minPoints The minimum points to generate based on factors (ignored if techPoints and designPoints supplied)
@attribute [Integer] pay The pay available upon the contract's completion
@attribute [Integer] penalty The penalty for job failure
@attribute [Integer] weeks The amount of weeks determined to finish the contracts
###
style = require('./lib-js/style')
# @namespace Spartan Dev Project
#
# The primary namespace holding all of the SDP
SDP = {}
Companies = {}
JobApplicants = {}
###
jSTORAGE
###
`(function(){function C(){var a="{}";if("userDataBehavior"==f){g.load("jStorage");try{a=g.getAttribute("jStorage")}catch(b){}try{r=g.getAttribute("jStorage_update")}catch(c){}h.jStorage=a}D();x();E()}function u(){var a;clearTimeout(F);F=setTimeout(function(){if("localStorage"==f||"globalStorage"==f)a=h.jStorage_update;else if("userDataBehavior"==f){g.load("jStorage");try{a=g.getAttribute("jStorage_update")}catch(b){}}if(a&&a!=r){r=a;var l=p.parse(p.stringify(c.__jstorage_meta.CRC32)),k;C();k=p.parse(p.stringify(c.__jstorage_meta.CRC32));
var d,n=[],e=[];for(d in l)l.hasOwnProperty(d)&&(k[d]?l[d]!=k[d]&&"2."==String(l[d]).substr(0,2)&&n.push(d):e.push(d));for(d in k)k.hasOwnProperty(d)&&(l[d]||n.push(d));s(n,"updated");s(e,"deleted")}},25)}function s(a,b){a=[].concat(a||[]);var c,k,d,n;if("flushed"==b){a=[];for(c in m)m.hasOwnProperty(c)&&a.push(c);b="deleted"}c=0;for(d=a.length;c<d;c++){if(m[a[c]])for(k=0,n=m[a[c]].length;k<n;k++)m[a[c]][k](a[c],b);if(m["*"])for(k=0,n=m["*"].length;k<n;k++)m["*"][k](a[c],b)}}function v(){var a=(+new Date).toString();
if("localStorage"==f||"globalStorage"==f)try{h.jStorage_update=a}catch(b){f=!1}else"userDataBehavior"==f&&(g.setAttribute("jStorage_update",a),g.save("jStorage"));u()}function D(){if(h.jStorage)try{c=p.parse(String(h.jStorage))}catch(a){h.jStorage="{}"}else h.jStorage="{}";z=h.jStorage?String(h.jStorage).length:0;c.__jstorage_meta||(c.__jstorage_meta={});c.__jstorage_meta.CRC32||(c.__jstorage_meta.CRC32={})}function w(){if(c.__jstorage_meta.PubSub){for(var a=+new Date-2E3,b=0,l=c.__jstorage_meta.PubSub.length;b<
l;b++)if(c.__jstorage_meta.PubSub[b][0]<=a){c.__jstorage_meta.PubSub.splice(b,c.__jstorage_meta.PubSub.length-b);break}c.__jstorage_meta.PubSub.length||delete c.__jstorage_meta.PubSub}try{h.jStorage=p.stringify(c),g&&(g.setAttribute("jStorage",h.jStorage),g.save("jStorage")),z=h.jStorage?String(h.jStorage).length:0}catch(k){}}function q(a){if("string"!=typeof a&&"number"!=typeof a)throw new TypeError("Key name must be string or numeric");if("__jstorage_meta"==a)throw new TypeError("Reserved key name");
return!0}function x(){var a,b,l,k,d=Infinity,n=!1,e=[];clearTimeout(G);if(c.__jstorage_meta&&"object"==typeof c.__jstorage_meta.TTL){a=+new Date;l=c.__jstorage_meta.TTL;k=c.__jstorage_meta.CRC32;for(b in l)l.hasOwnProperty(b)&&(l[b]<=a?(delete l[b],delete k[b],delete c[b],n=!0,e.push(b)):l[b]<d&&(d=l[b]));Infinity!=d&&(G=setTimeout(x,Math.min(d-a,2147483647)));n&&(w(),v(),s(e,"deleted"))}}function E(){var a;if(c.__jstorage_meta.PubSub){var b,l=A,k=[];for(a=c.__jstorage_meta.PubSub.length-1;0<=a;a--)b=
c.__jstorage_meta.PubSub[a],b[0]>A&&(l=b[0],k.unshift(b));for(a=k.length-1;0<=a;a--){b=k[a][1];var d=k[a][2];if(t[b])for(var n=0,e=t[b].length;n<e;n++)try{t[b][n](b,p.parse(p.stringify(d)))}catch(g){}}A=l}}var y=window.jQuery||window.$||(window.$={}),p={parse:window.JSON&&(window.JSON.parse||window.JSON.decode)||String.prototype.evalJSON&&function(a){return String(a).evalJSON()}||y.parseJSON||y.evalJSON,stringify:Object.toJSON||window.JSON&&(window.JSON.stringify||window.JSON.encode)||y.toJSON};if("function"!==
typeof p.parse||"function"!==typeof p.stringify)throw Error("No JSON support found, include //cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js to page");var c={__jstorage_meta:{CRC32:{}}},h={jStorage:"{}"},g=null,z=0,f=!1,m={},F=!1,r=0,t={},A=+new Date,G,B={isXML:function(a){return(a=(a?a.ownerDocument||a:0).documentElement)?"HTML"!==a.nodeName:!1},encode:function(a){if(!this.isXML(a))return!1;try{return(new XMLSerializer).serializeToString(a)}catch(b){try{return a.xml}catch(c){}}return!1},
decode:function(a){var b="DOMParser"in window&&(new DOMParser).parseFromString||window.ActiveXObject&&function(a){var b=new ActiveXObject("Microsoft.XMLDOM");b.async="false";b.loadXML(a);return b};if(!b)return!1;a=b.call("DOMParser"in window&&new DOMParser||window,a,"text/xml");return this.isXML(a)?a:!1}};y.jStorage={version:"0.4.12",set:function(a,b,l){q(a);l=l||{};if("undefined"==typeof b)return this.deleteKey(a),b;if(B.isXML(b))b={_is_xml:!0,xml:B.encode(b)};else{if("function"==typeof b)return;
b&&"object"==typeof b&&(b=p.parse(p.stringify(b)))}c[a]=b;for(var k=c.__jstorage_meta.CRC32,d=p.stringify(b),g=d.length,e=2538058380^g,h=0,f;4<=g;)f=d.charCodeAt(h)&255|(d.charCodeAt(++h)&255)<<8|(d.charCodeAt(++h)&255)<<16|(d.charCodeAt(++h)&255)<<24,f=1540483477*(f&65535)+((1540483477*(f>>>16)&65535)<<16),f^=f>>>24,f=1540483477*(f&65535)+((1540483477*(f>>>16)&65535)<<16),e=1540483477*(e&65535)+((1540483477*(e>>>16)&65535)<<16)^f,g-=4,++h;switch(g){case 3:e^=(d.charCodeAt(h+2)&255)<<16;case 2:e^=
(d.charCodeAt(h+1)&255)<<8;case 1:e^=d.charCodeAt(h)&255,e=1540483477*(e&65535)+((1540483477*(e>>>16)&65535)<<16)}e^=e>>>13;e=1540483477*(e&65535)+((1540483477*(e>>>16)&65535)<<16);k[a]="2."+((e^e>>>15)>>>0);this.setTTL(a,l.TTL||0);s(a,"updated");return b},get:function(a,b){q(a);return a in c?c[a]&&"object"==typeof c[a]&&c[a]._is_xml?B.decode(c[a].xml):c[a]:"undefined"==typeof b?null:b},deleteKey:function(a){q(a);return a in c?(delete c[a],"object"==typeof c.__jstorage_meta.TTL&&a in c.__jstorage_meta.TTL&&
delete c.__jstorage_meta.TTL[a],delete c.__jstorage_meta.CRC32[a],w(),v(),s(a,"deleted"),!0):!1},setTTL:function(a,b){var l=+new Date;q(a);b=Number(b)||0;return a in c?(c.__jstorage_meta.TTL||(c.__jstorage_meta.TTL={}),0<b?c.__jstorage_meta.TTL[a]=l+b:delete c.__jstorage_meta.TTL[a],w(),x(),v(),!0):!1},getTTL:function(a){var b=+new Date;q(a);return a in c&&c.__jstorage_meta.TTL&&c.__jstorage_meta.TTL[a]?(a=c.__jstorage_meta.TTL[a]-b)||0:0},flush:function(){c={__jstorage_meta:{CRC32:{}}};w();v();s(null,
"flushed");return!0},storageObj:function(){function a(){}a.prototype=c;return new a},index:function(){var a=[],b;for(b in c)c.hasOwnProperty(b)&&"__jstorage_meta"!=b&&a.push(b);return a},storageSize:function(){return z},currentBackend:function(){return f},storageAvailable:function(){return!!f},listenKeyChange:function(a,b){q(a);m[a]||(m[a]=[]);m[a].push(b)},stopListening:function(a,b){q(a);if(m[a])if(b)for(var c=m[a].length-1;0<=c;c--)m[a][c]==b&&m[a].splice(c,1);else delete m[a]},subscribe:function(a,
b){a=(a||"").toString();if(!a)throw new TypeError("Channel not defined");t[a]||(t[a]=[]);t[a].push(b)},publish:function(a,b){a=(a||"").toString();if(!a)throw new TypeError("Channel not defined");c.__jstorage_meta||(c.__jstorage_meta={});c.__jstorage_meta.PubSub||(c.__jstorage_meta.PubSub=[]);c.__jstorage_meta.PubSub.unshift([+new Date,a,b]);w();v()},reInit:function(){C()},noConflict:function(a){delete window.$.jStorage;a&&(window.jStorage=this);return this}};(function(){var a=!1;if("localStorage"in
window)try{window.localStorage.setItem("_tmptest","tmpval"),a=!0,window.localStorage.removeItem("_tmptest")}catch(b){}if(a)try{window.localStorage&&(h=window.localStorage,f="localStorage",r=h.jStorage_update)}catch(c){}else if("globalStorage"in window)try{window.globalStorage&&(h="localhost"==window.location.hostname?window.globalStorage["localhost.localdomain"]:window.globalStorage[window.location.hostname],f="globalStorage",r=h.jStorage_update)}catch(k){}else if(g=document.createElement("link"),
g.addBehavior){g.style.behavior="url(#default#userData)";document.getElementsByTagName("head")[0].appendChild(g);try{g.load("jStorage")}catch(d){g.setAttribute("jStorage","{}"),g.save("jStorage"),g.load("jStorage")}a="{}";try{a=g.getAttribute("jStorage")}catch(m){}try{r=g.getAttribute("jStorage_update")}catch(e){}h.jStorage=a;f="userDataBehavior"}else{g=null;return}D();x();"localStorage"==f||"globalStorage"==f?"addEventListener"in window?window.addEventListener("storage",u,!1):document.attachEvent("onstorage",
u):"userDataBehavior"==f&&setInterval(u,1E3);E();"addEventListener"in window&&window.addEventListener("pageshow",function(a){a.persisted&&u()},!1)})()})()`
###
jSTORAGE End
###
"use strict"
SDP.Util = ( ->
util = {}
fs = require('fs')
path = require('path')
normalizeStringPosix = (path, allowAboveRoot) ->
res = ''
lastSlash = -1
dots = 0
code = undefined
for i in [0..path.length]
if i < path.length then code = path.charCodeAt(i)
else if code is 47 then break
else code = 47
if code is 47
if lastSlash is i - 1 or dots is 1
#NOOP
else if lastSlash isnt i - 1 and dots is 2
if res.length < 2 or res.charCodeAt(res.length - 1) isnt 46 or res.charCodeAt(res.length - 2) isnt 46
if res.length > 2
start = res.length - 1
j = start
for j in [start..0]
if res.charCodeAt(j) is 47 then break
if j isnt start
if j is -1 then res = ''
else res = res.slice(0, j)
lastSlash = i
dots = 0
continue
else if res.length is 2 or res.length is 1
res = ''
lastSlash = i
dots = 0
continue
if allowAboveRoot
if res.length > 0 then res += '/..'
else res = '..'
else
if res.length > 0 then res += '/' + path.slice(lastSlash + 1, i)
else res = path.slice(lastSlash + 1, i)
lastSlash = i
dots = 0
else if code is 46 and dots isnt -1 then ++dots else dots = -1
return res
# Define very useful, efficent (as much as possible), basic utility functions
util.GLOBAL = (Function("return this"))()
util.kindOf = (obj) -> Object.prototype.toString.call(obj).slice(8, -1)
util.hasOwn = (obj, key) -> Object.prototype.hasOwnProperty.call(obj, key)
util.isKind = (obj, kind) -> util.kindOf(obj) is kind
util.isUndefined = (obj) -> obj is undefined
util.isNull = (obj) -> obj is null
util.isString = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is String
util.isArray = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is Array
util.isNumber = (obj) ->
if obj is undefined or obj is null or obj isnt obj then return false
return obj.constructor is Number
util.isInteger = (obj) -> util.isNumber(obj) and (obj % 1 is 0)
util.isFloat = (obj) -> util.isNumber(obj) and (obj % 1 isnt 0)
util.isObject = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is Object
util.isBoolean = (obj) -> obj is true or obj is false
util.isFunction = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is Function
util.isDate = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is Date
util.isRegExp = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is RegExp
util.isPlainObject = (obj) -> not not value and typeof value is 'object' and value.constructor is Object
util.isArguments = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is Arguments
util.isEmpty = (obj) ->
if util.isNull(obj) then return true
else if util.isString(obj) or util.isArray(obj) then return not obj.length
return false for key of obj when util.hasOwn(obj, key)
return true
util.isFinite = (obj) -> util.isNumber(obj) and obj isnt Infinity and obj isnt -Infinity
util.isNaN = (obj) -> obj isnt obj or not util.isNumber(obj)
util.toArray = (obj) ->
if not obj then return []
if obj.length is null or util.isString(obj) or util.isFunction(obj) or util.isRegExp(obj) or obj is util.GLOBAL then return [obj]
else
n = obj.length
result = []
result[n] = obj[n] while(--n)
return result
util.toNumber = (obj) ->
if util.isNumber(obj) then return obj
if not obj then return 0
if util.isString(obj) then return parseFloat(obj)
if util.isArray(obj) or util.isNaN(obj) then return NaN
Number(obj)
util.toString = (obj) ->
return if obj is null then '' else obj.toString()
String::capitalize = (index = 0) ->
halfResult = @charAt(index).toUpperCase() + @slice(index+1)
if halfResult.length is @length then return halfResult
@slice(0, index) + halfResult
util.Filesystem = ( ->
fsys = {}
inspect = require('util').inspect
assertPath = (path) -> if typeof path isnt 'string' then throw new TypeError('Path must be a string. Received ' + inspect(path))
_format = (sep, pathObject) ->
dir = pathObject.dir or pathObject.root
base = pathObject.base or ((pathObject.name or '') + (pathObject.ext or ''))
if not dir then return base
if dir is pathObject.root then return dir + base
return dir + sep + base
# Provides for path.posix not found in nodejs version 0.10
# Allows posix standard path management, which is prefered in this project
fsys.path = {
resolve: (args...) ->
resolvedPath = ''
resolvedAbsolute = false
cwd = undefined
`for (var i = args.length - 1 i >= -1 && !resolvedAbsolute i--) {
var path;
if(i>=0) path = args[i];
else {
if (cwd === undefined) cwd = process.cwd();
path = cwd;
}
assertPath(path);
if(path.length === 0) continue;
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charCodeAt(0) is 47/*/*/);
}`
resolvedPath = normalizeStringPosix(resolvedPath, not resolvedAbsolute)
if resolvedAbsolute
if resolvedPath.length > 0 then return "/#{resolvedPath}" else return '/'
else if resolvedPath.length > 0 then return resolvedPath else return '.'
normalize: (path) ->
assertPath(path)
if path.length is 0 then return '.'
`const isAbsolute = path.charCodeAt(0) is 47/*/*/;
const trailingSeparator = path.charCodeAt(path.length - 1) is 47/*/*/`
path = normalizeStringPosix(path, !isAbsolute)
if path.length is 0 and not isAbsolute then path = '.'
if path.length is 0 and trailingSeparator then path += '/'
if isAbsolute then return "/#{path}"
return path
isAbsolute: (path) ->
assertPath(path)
return path.length > 0 and path.charCodeAt(0) is 47
join: (args...) ->
if args.length is 0 then return '.'
joined = undefined
for i, arg in args
assertPath(arg)
if joined is undefined then joined = arg else joined += "#{joined}/#{arg}"
if joined is undefined then return '.'
return fsys.path.normalize(joined)
relative: (from, to) ->
assertPath(from)
assertPath(to)
if from is to then return ''
from = fsys.path.resolve(from)
to = fsys.path.resolve(to)
if from is to then return ''
fromStart = 1
break for fromStart in [fromStart..from.length] when from.charCodeAt(fromStart) isnt 47
fromEnd = from.length
fromLen = (fromEnd-fromStart)
toStart = 1
break for toStart in [toStart..to.length] when to.charCodeAt(toStart) isnt 47
toEnd = to.length
toLen = (toEnd-toStart)
length = if fromLen < toLen then fromLen else toLen
lastCommonSep = -1
i = 0
for i in [i..length]
if i is length
if toLen > length
if to.charCodeAt(toStart + i) is 47 then return to.slice(toStart+i+1)
else if i is 0 then to.slice(toStart+i)
else if fromLen > length
if from.charCodeAt(fromStart + i) is 47 then lastCommonSep = i
else if i is 0 then lastCommonSep = 0
break
fromCode = from.charCodeAt(fromStart + i)
toCode = to.charCodeAt(toStart + i)
if fromCode isnt toCode then break
else if fromCode is 47 then lastCommonSep = i
out = ''
for i in [fromStart+lastCommonSep+1..fromEnd]
if i is fromEnd or from.charCodeAt(i) is 47
if out.length is 0 then out += '..' else out += '/..'
if out.length > 0 then return out+to.slice(toStart+lastCommonSep)
else
toStart += lastCommonSep
if to.charCodeAt(toStart) is 47 then ++toStart
return to.slice(toStart)
dirname: (path) ->
assertPath(path)
if path.length is 0 then return '.'
code = path.charCodeAt(0)
hasRoot = code is 47
end = -1
matchedSlash = true
for i in [path.length-1..1]
code = path.charCodeAt(i)
if code is 47
if not matchedSlash
end = i
break
else matchedSlash = false
if end is -1 then return if hasRoot then '/' else '.'
if hasRoot and end is 1 then return '//'
return path.slice(0, end)
basename: (path, ext) ->
if ext isnt undefined and typeof ext isnt 'string' then throw new TypeError('"ext" argument must be a string')
assertPath(path)
start = 0
end = -1
matchedSlash = true
i = undefined
if ext isnt undefined and ext.length > 0 and ext.length <= path.length
if ext.length is path.length and ext is path then return ''
extIdx = ext.length - 1
firstNonSlashEnd = -1
for i in [path.length-1..0]
code = path.charCodeAt(i)
if code is 47
if not matchedSlash
start = i + 1
break
else
if firstNonSlashEnd is -1
matchedSlash = false
firstNonSlashEnd = i + 1
if extIdx >= 0
if code is ext.charCodeAt(extIdx)
if --extIdx is -1 then end = i
else
extIdx = -1
end = firstNonSlashEnd
if start is end then end = firstNonSlashEnd
else if end is -1 then end = path.length
return path.slice(start, end)
else
for i in [path.length-1..0]
if path.charCodeAt(i) is 47
if not matchedSlash
start = i + 1
break
else if end is -1
matchedSlash = false
end = i + 1
if end is -1 then return ''
return path.slice(start, end)
extname: (path) ->
assertPath(path)
startDot = -1
startPart = 0
end = -1
matchedSlash = true
preDotState = 0
for i in [path.length-1..0]
code = path.charCodeAt(i)
if code is 47
if not matchedSlash
startPart = i + 1
break
continue
if end is -1
matchedSlash = false
end = i + 1
if code is 46#.
if startDot is -1 then startDot = i
else if preDotState isnt 1 then preDotState = 1
else if startDot isnt -1 then preDotState = -1
if startDot is -1 or end is -1 or preDotState is 0 or (preDotState is 1 and startDot is end - 1 and startDot is startPart + 1) then return ''
return path.slice(startDot, end)
format: (pathObject) ->
if pathObject is null or typeof pathObject isnt 'object' then throw new TypeError("Parameter 'pathObject' must be an object, not #{typeof pathObject}")
return _format('/', pathObject)
parse: (path) ->
assertPath(path)
ret = { root: '', dir: '', base: '', ext: '', name: '' }
if path.length is 0 then return ret
code = path.charCodeAt(0)
isAbsolute = code is 47
start = undefined
if isAbsolute
ret.root = '/'
start = 1
else start = 0
startDot = -1
startPart = 0
end = -1
matchedSlash = true
i = path.length - 1
preDotState = 0
for i in [path.length-1..start]
code = path.charCodeAt(i)
if code is 47
if not matchedSlash
startPart = i + 1
break
continue
if end is -1
matchedSlash = false
end = i + 1
if code is 46#.
if startDot is -1 then startDot = i
else if preDotState isnt 1 then preDotState = 1
else if startDot isnt -1 then preDotState = -1
if startDot is -1 or end is -1 or (preDotState is 1 and startDot is end - 1 and startDot is startPart + 1)
if end isnt -1
if startPart is 0 and isAbsolute then ret.base = ret.name = path.slice(1, end)
else ret.base = ret.name = path.slice(startPart, end)
else
if startPart is 0 and isAbsolute
ret.name = path.slice(1, startDot)
ret.base = path.slice(1, end)
else
ret.name = path.slice(startPart, startDot)
ret.base = path.slice(startPart, end)
ret.ext = path.slice(startDot, end)
if startPart > 0 then ret.dir = path.slice(0, startPart - 1)
else if isAbsolute then ret.dir = '/'
return ret
sep: '/'
delimiter: ':'
win32: null
posix: null
}
fsys.cwd = -> PlatformShim.getScriptPath(true)
fsys.walk = (dir, finish) ->
results = []
fs.readdir(p.get(), (err, files) ->
if err then return finsh(err)
pending = files.length
if not pending then return finish(null, results)
files.forEach((file) ->
file = fsys.path.resolve(dir, file)
fs.stat(file, (err, stat) ->
if stat and stat.isDirectory() then walk(file, (err, res) ->
results = results.concat(res)
if not --pending then finish(null, results)
)
else
results.push(file)
if not --pending then return finish(null, results)
)
)
)
fsys.readJSONFile = (p) ->
if p.constructor isnt util.Path then p = new fsys.Path(path)
if p.isDirectory() then throw new TypeError("SDP.Util.Filesystem.readJSONFile can not operate on directories")
if p.extname() isnt '.json' then throw new TypeError("SDP.Util.Filesystem.readJSONFile only operates on JSON files")
result = null
fs.readFile(p.get(), (err, data) ->
if err then util.Logger.alert(err)
result = JSON.parse(data)
)
result
fsys.readJSONDirectory = (p, callback) ->
if p.constructor isnt util.Path then p = new fsys.Path(path)
if not p.isDirectory() then throw new TypeError("SDP.Util.Filesystem.readJSONDirectory can not operate on just files")
return fsys.walk(p.get(), (err, files) ->
if err then util.Logger.alert(err)
results = []
files.forEach((file) ->
pa = new fsys.Path(file)
json = fsys.readJSONFile(pa)
if pa.extname() is '.json' then results.push(json)
if util.isFunction(callback) then callback(json)
)
results
)
fsys.registerJSONFile = (p) ->
if p.constructor isnt util.Path then p = new fsys.Path(path)
if p.isDirectory() then throw new TypeError("SDP.Util.Filesystem.registerJSONFile can not operate on directories")
if p.extname() isnt '.json' then throw new TypeError("SDP.Util.Filesystem.registerJSONFile only operates on JSON files")
return util.registerJSONObject(fsys.readJSONFile(p))
fsys.registerJSONDirectory = (p) ->
if p.constructor isnt util.Path then p = new fsys.Path(path)
if not p.isDirectory() then throw new TypeError("SDP.Util.Filesystem.registerJSONDirectory can only operate on directories")
fsys.readJSONDirectory(p, (json) -> util.registerJSONObject(json))
class fsys.Path
constructor: (uri) ->
if util.isObject(uri) then uri = fsys.path.format(uri)
if uri is undefined then uri = fsys.cwd()
fsys.Path.check(uri)
@get = ->
fsys.Path.check(uri)
uri
@check: (uri) ->
if fsys.path.isAbsolute(uri) then throw new TypeError("SDP's Path may not store absolute paths")
if not fsys.path.resolve(uri).startsWith(fsys.cwd()) then throw new TypeError("SDP's Path may not leave the current working directory")
cd: (to) ->
uri = fsys.path.resolve(@get(), to)
fsys.Path.check(uri)
@get = ->
fsys.Path.check(uri)
uri
basename: (ext) ->
fsys.path.basename(@get(), ext)
dirname: ->
fsys.path.dirname(@get())
extname: ->
fsys.path.extname(@get())
parse: ->
fsys.path.parse(@get())
isFile: ->
fs.lstatSync(@get()).isFile()
isDirectory: ->
fs.lstatSync(@get()).isDirectory()
convert: ->
@get()
fsys
)()
util.registerJSONObject = (item) ->
if not util.isString(item.objectType) then throw new TypeError("SDP.Util.registerJSONObject can not work on items that don't contain an objectType field")
func = SDP.Functional["add#{item.objectType.capitalize()}Item"]
if not func
util.Logger.alert("SDP.Util.registerJSONObject could not find the function for objectType #{item.objectType}")
return
func(item)
util.getOverridePositions = (genre, category) ->
genre = genre.replace(/\s/g, "")
category = category.replace(/\s/g, "")
for g, i in SDP.Constants.Genre
if genre is g
if category is null then return [i]
for c, ci in SDP.Constants.ResearchCategory
if c is category then return [i, ci]
break
return undefined
util.fixItemNaming = (item, originalName, fixName) ->
if item[originalName]?
item[fixName] = item[originalName]
item[originalName] = undefined
item
class util.Image
constructor: (@uri) ->
@uri = null if not util.isString(@uri)
exists: ->
if @uri is null then return false
doesExist = true
fs.access(@uri, fs.constants.F_OK, (err) ->
if err then doesExist = false
)
doesExist
class util.Weight
constructor: (w1 = 0.8, w2 = w1, w3 = w2, w4, w5 = w4, w6 = w5) ->
if w1 is true or (not util.isNumber(w1) and not util.isArray(w1)) then @arr = [0.8,0.8,0.8]
else if w1 is false then @arr = [0.8,0.8,0.8,0.8,0.8,0.8]
else
if util.isArray(w1)
if w1.length > 3
w1.push(w1.last()) while w1.length < 6
else
w1.push(w1.last()) while w1.length < 3
@arr = w1
else
@arr = [w1,w2,w3]
if w4 then @arr.push(w4,w5,w6)
@arr[i] = num/100 for num, i in @arr when num > 1
@isGenre = -> @arr.length is 6
@isAudience = -> @arr.length is 3
get: (index) ->
if index is null then return @arr
@arr[index]
convert: ->
new Array(@arr)
class util.Date
START = '1/1/1'
END = '260/12/4'
constructor: (y = 1, m, w) ->
if util.isString(y)
[y,m,w] = m.split('/')
if util.isString(y) then [y,m,w] = m.split(' ')
if y is true then [y,m,w] = END.split('/')
if y is false then [y,m,w] = START.split('/')
if m is undefined then m = y
if w is undefined then w = m
@string = "#{y}/#{m}/#{w}"
convert: ->
new String(@string)
util.Error = ( ->
Error = {
logs: []
}
( ->
update = false
saving = false
Error.save = ->
if not saving
json = JSON.stringify(Error.logs)
saving = true
DataStore.saveToSlotAsync("SDP.Util.Error.logs", json, ->
saving = false
if update
update = false
Error.save()
, (m) -> saving = false )
else update = true
)()
Error.addErrorLog = (level, message, error) ->
if not error then error = {}
Error.logs.push {
date: (new Date()).toISOString()
level: level
msg: message
errorMsg: error.message
stacktrace: e.stack
number: e.number
}
if Error.logs.length > 100 then Error.logs.splice(0, errorLogs.length - 100)
Error.save()
Error
)()
util.Logger = ( ->
utilRequire = require('util')
logger = {
enabled: true
enableAlerts: true
formatter: logger.printf
show: 200
levels: {}
addLevel: (level, weight, sty, prefix = level) ->
if sty.constructor is style.FormattedStyle then sty = sty.getStyle()
logger.levels[level] = {
level: level
prefix: prefix
style: sty
weight: weight
format: (msg...) -> logger.format(level, msg...)
formatWithTime: (msg...) -> logger.formatWithTime(level, msg...)
log: (msg...) -> logger.log(level, msg...)
alert: (msg...) -> logger.alert(level, msg...)
}
if logger[level] is undefined then logger[level] = logger.levels[level].log
if logger["#{level}Alert"] is undefined then logger["#{level}Alert"] = logger.levels[level].alert
setShow: (level) ->
if level.constructor is Object then logger.show = level.weight
else if level.constructor is String then logger.show = logger.levels[level].weight
else logger.show = level
}
logger.addLevel('verbose', 0, { fg: 'blue', bg: 'black' }, 'VERBOSE')
logger.addLevel('debug', 100, { fg: 'blue'}, 'DEBUG')
logger.addLevel('info', 200, { fg: 'green'}, 'INFO')
logger.addLevel('warn', 300, { fg: 'black', bg: 'yellow' }, 'WARN')
logger.addLevel('error', 400, { fg: 'red', bg: 'black' }, 'ERROR')
logger.addLevel('fatal', 500, { fg: 'red', bg: 'black' }, 'FATAL')
stream = process.stderr
Object.defineProperty(logger, 'stream',
set: (newStream) ->
stream = newStream
style.stream = stream
get: -> stream
)
createTimestamp = (d) ->
formatNumbers = (n) -> if (n >= 0 and n < 10) then "0" + n else n + ""
[
[
formatNumbers(d.getFullYear())
formatNumbers(d.getMonth() + 1)
d.getDate()
].join("-")
[
formatNumbers(d.getHours())
formatNumbers(d.getMinutes())
formatNumbers(d.getHours())
].join(":")
].join("|")
logger.printf = {
formatWithTime: (level, msg...) ->
if logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
style.format(level.style, "[#{createTimestamp(new Date())}]#{level.prefix}: #{str.shift().format(msg...)}")
format: (level, msg...) ->
if logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
style.format(level.style, "#{level.prefix}: #{str.shift().format(msg...)}")
log: (level, msg...) ->
if not logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
if logger.enabled and logger.stream and logger.levels[level]?.weight >= logger.show
logger.stream.write(logger.printf.formatWithTime(level, msg))
alert: (level, msg...) ->
if not logger.levels[level]? then return "Level #{level} does not exist"
if logger.enabled and logger.enableAlerts and logger.levels[level]?.weight >= logger.show
string = if msg.length is 1 then msg[0] else str.shift().format(msg...)
PlatformShim.alert(string, logger.levels[level].prefix)
}
logger.format = {
formatWithTime: (level, msg...) ->
if logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
style.format(level.style, "[#{createTimestamp(new Date())}]#{level.prefix}: #{utilRequire.format(msg...)}")
format: (level, msg...) ->
if logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
style.format(level.style, "#{level.prefix}: #{utilRequire.format(msg...)}")
log: (level, msg...) ->
if not logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
if logger.enabled and logger.stream and logger.levels[level]?.weight >= logger.show
logger.stream.write(logger.format.formatWithTime(level, msg))
alert: (level, msg...) ->
if not logger.levels[level]? then return "Level #{level} does not exist"
if logger.enabled and logger.enableAlerts and logger.levels[level]?.weight >= logger.show
string = if msg.length is 1 then msg[0] else utilRequire.format(msg...)
PlatformShim.alert(string, logger.levels[level].prefix)
}
logger.formatWithTime = (level, msg...) ->
logger.formatter.formatWithTime(level, msg...)
logger.format = (level, msg...) ->
logger.formatter.format(level, msg...)
logger.log = (level, msg...) ->
logger.formatter.log(level, msg...)
logger.alert = (level, msg...) ->
logger.formatter.alert(level, msg...)
logger
)()
util.Check = ( ->
Check = {
usePopups: true
}
Check.error = (msg) ->
try throw new Error(msg)
catch e
if Checks.usePopups then util.Logger.errorAlert(msg, e) else util.Logger.error(msg, e)
Error.addErrorLog("MODERROR", msg, e)
Check.audienceWeightings = (w) ->
if not w or w.length < 3 or w.some((v) -> return v < 0 or v > 1)
Check.error('audience weigthing is invalid: %s', w)
return false
return true
Check.genreWeightings = (w) ->
if not w or w.length < 6 or w.some((v) -> return v < 0 or v > 1)
Check.error('genre weigthing is invalid: %s', w)
return false
return true
Check.missionOverrides = (overrides) ->
if overrides.length < 6 or overrides.some((o) -> o.length < 6 or o.some((w) -> w > 1 or w < 0))
Check.error('invalid missionOverrides: %s', w)
return false
return true
Check.date = (date) ->
if date and date.split
v = date.split('/')
if v and v.length is 3 and not v.some((t) -> t < 1) and v[1] <= 12 and v[2] <= 4 then return true
Check.error('date invalid: %s', date)
return false
Check.propertiesPresent = (obj, props) ->
if not obj then return false
if not props then return true
for p in props
if not p or p.length < 1 then continue
if not obj.hasOwnProperty(p)
Check.error('property not set on object: %s', p)
return false
return true
Check.uniqueness = (obj, prop, values, ignoreErr) ->
if values.some((v) -> v[prop] is obj[prop])
if not ignoreErr then Check.error('duplicate value for %s found: %s', prop, obj[prop])
return false
return true
Check
)()
util
)()
# @namespace Constants
#
# The constants of the SPD
SDP.Constants = {
# Categories of development
ResearchCategory: [
'Engine'
'Gameplay'
'Story/Quests'
'Dialogs'
'Level Design'
'AI'
'World Design'
'Graphic'
'Sound'
]
# Audiences to target
Audience: [
'young'
'everyone'
'mature'
]
# Genres to choose for games
Genre: [
'Action'
'Adventure'
'RPG'
'Simulation'
'Strategy'
'Casual'
]
}
# @namespace Functional
#
# Contains the function interface for the SDP
SDP.Functional = {}
# Registers a Research item
#
# @param [ResearchItem] item The item to register
SDP.Functional.addResearchItem = (item) ->
Checks = SDP.Util.Check
unless item.type? then item.type = 'engine'
if item.type is 'engine' and item.engineStart then item.canResearch = -> false
requirments = ['id', 'name', 'category', 'categoryDisplayName']
if item.v? then requirements.push('pointsCost','duration','researchCost','engineCost') else requirements.push('v')
if Checks.propertiesPresent(item, requirements) and Checks.uniqueness(item, 'id', SDP.GDT.Research.getAll())
SDP.GDT.Research.researches.push(item)
Research.engineItems.push(item)
return
SDP.Functional.addStartResearch = (item) ->
item.type = 'start'
SDP.Functional.addResearchItem(item)
SDP.Functional.addBasicResearch = (item) ->
item.type = 'basic'
SDP.Functional.addResearchItem(item)
SDP.Functional.addEngineResearch = (item) ->
item.type = 'engine'
SDP.Functional.addResearchItem(item)
SDP.Functional.addSpecialResearch = (item) ->
item.type = 'special'
SDP.Functional.addResearchItem(item)
# Registers a Platform item
#
# @param [PlatformItem] item The item to register
SDP.Functional.addPlatformItem = (item) ->
Checks = SDP.Util.Check
fix = SDP.Util.fixItemNaming
fix(item, 'licensePrice','licencePrize')
fix(item, 'publishDate', 'published')
fix(item, 'retireDate', 'platformRetireDate')
fix(item, 'devCosts', 'developmentCosts')
fix(item, 'genreWeight', 'genreWeightings')
fix(item, 'audienceWeight', 'audienceWeightings')
fix(item, 'marketPoints', 'marketKeyPoints')
if Checks.propertiesPresent(item, ['id', 'name', 'company', 'startAmount', 'unitsSold', 'licencePrize', 'published', 'platformRetireDate', 'developmentCosts', 'genreWeightings', 'audienceWeightings', 'techLevel', 'baseIconUri', 'imageDates']) and Checks.uniqueness(item, 'id', SDP.GDT.Platform.getAll()) and Checks.audienceWeightings(item.audienceWeightings) and Checks.genreWeightings(item.genreWeightings) and Checks.date(item.published) and Checks.date(item.platformRetireDate)
if item.marketKeyPoints then for point in item.marketKeyPoints
return unless Checks.date(point.date)
###
if Checks.checkUniqueness(item.name, 'name', Companies.getAllCompanies())
SDP.GDT.addCompany(item.name).addPlatform(item)
else
###
SDP.GDT.Platform.platforms.push(item)
if item.events then for event of item.events
GDT.addEvent(event)
return
# Registers a Topic item
#
# @param [TopicItem] item The item to register
SDP.Functional.addTopicItem = (item) ->
Checks = SDP.Util.Check
fix = SDP.Util.fixItemNaming
fix(item, 'genreWeight', 'genreWeightings')
fix(item, 'audienceWeight', 'audienceWeightings')
fix(item, 'overrides', 'missionOverrides')
if Checks.propertiesPresent(t, ['name', 'id', 'genreWeightings', 'audienceWeightings']) and Checks.audienceWeightings(t.audienceWeightings) and Checks.genreWeightings(t.genreWeightings) and Checks.uniqueness(t, 'id', SDP.GDT.Topic.getAll(), true)
SDP.GDT.Topic.topics.push(item)
return
SDP.Functional.addTopicItems = (list...) ->
if list.length is 1
list = list[0]
if not SDP.Util.isArray(list) then return SDP.Functional.addTopicItem(list)
SDP.Functional.addTopicItem(item) for item in list
# Registers a Research Project item
#
# @param [ResearchProjectItem] item The item to register
SDP.Functional.addResearchProjectItem = (item) ->
Checks = SDP.Util.Check
unless item.canResearch? then item.canResearch = ((company)->true)
if Checks.propertiesPresent(item, ['id', 'name', 'pointsCost', 'iconUri', 'description', 'targetZone']) and Checks.uniqueness(item, 'id', SDP.GDT.ResearchProject.getAll())
SDP.GDT.ResearchProject.projects.push(item)
return
SDP.Functional.addResearchProject = (item) -> SDP.Functional.addResearchProjectItem(item)
# Registers a Training item
#
# @param [TrainingItem] item The item to register
SDP.Functional.addTrainingItem = (item) ->
Checks = SDP.Util.Check
unless item.canSee? and item.canUse? then item.canSee = (staff, company) -> true
if Checks.propertiesPresent(item, ['id', 'name', 'pointsCost', 'duration', 'category', 'categoryDisplayName']) and Checks.uniqueness(item, 'id', SDP.GDT.Training.getAll())
SDP.GDT.Training.trainings.push(item)
return
# Registers a Contract item
#
# @param [ContractItem] item The item to register
SDP.Functional.addContractItem = (item) ->
Checks = SDP.Util.Check
if Checks.propertiesPresent(item, ['id', 'name', 'description', 'tF', 'dF']) and Checks.uniqueness(item, 'id', SDP.GDT.Contract.getAll())
SDP.GDT.Contract.contracts.push(item)
return
# Registers a Publisher item
#
# @param [PublisherItem] item The item to register
SDP.Functional.addPublisherItem = (item) ->
Checks = SDP.Util.Check
if Checks.propertiesPresent(item, ['id', 'name']) and Checks.uniqueness(item, 'id', SDP.GDT.Publisher.getAll())
SDP.GDT.Publisher.publishers.push(item)
return
# Registers a Reviewer item
#
# @param [ReviewerItem] item The item to register
###
SDP.Functional.addReviewerItem = (item) ->
Checks = SDP.Util.Check
if Checks.propertiesPresent(item, ['id', 'name']) and Checks.uniqueness(item, 'id', SDP.GDT.Review.getAll())
SDP.GDT.Review.reviewer.push(item)
return
###
SDP.Functional.addEvent = (event) ->
Checks = SDP.Util.Check
unless Checks.propertiesPresent(event, ['id']) and (event.notification or event.getNotification) then return
unless Checks.checkUniqueness(event, 'id', GDT.Event.getAll()) then return
# hacks in runningCompany to events because event.complete does not supply one, and overriding the UI system is a bit much for now
oldTrigger = event.trigger
event.trigger = (company) ->
result = oldTrigger(company)
@runningCompany = company if result and event.complete?
result
GDT.Event.events.push(event)
# Adds a notification to the triggering queue
#
# @param [NotificationItem] item The item to queue
SDP.Functional.addNotificationToQueue = (item) ->
if SDP.Util.isString(item)
item = item.split('\n')
if item.length is 1 then item = item[0].split(':')
if item.length is 1 then item = item[0].split(';')
item.forEach((e, i) -> item[i] = e.trim())
item = {
header: item[0]
text: item[1]
buttonText: item[2]
}
item.header = '?' unless item.header?
item.text = '?' unless item.text?
if not item instanceof Notification
item = new Notification {
header: item.header
text: item.text
buttonText: item.buttonText
weeksUntilFired: item.weeksUntilFired
image: item.image
options: item.options.slice(0, 3)
sourceId: item.sourceId
}
if GameManager?.company?.notifications? then GameManager.company.notifications.push(item) else SDP.GDT.Notification.queue.push(item)
SDP.Class = (
classes = {}
convertClasses = (classObj) ->
switch classObj.constructor
when SDP.Util.Date, SDP.Util.Weight, SDP.Util.Filesystem.Path then return classObj.convert()
when Array
classObj[i] = convertClasses(classObj[i]) for i of classObj
return classObj
else return classObj
class Base
constructor: (args...) ->
if SDP.Util.isObject(args[0])
@[arg] = args[0][arg] for arg in args[0] when args[0].hasOwnProperty(arg)
@wasNativeObject = true
else @wasNativeObject = false
@id ?= @name
class classes.Research extends Base
constructor: (@name, @type, @category, @categoryDisplayName = @category, @id) ->
super
convert: ->
item = {
name: @name
id: @id
type: @type
v: @v
pointsCost: @pointsCost
duration: @duration
researchCost: @researchCost
devCost: @devCost
engineCost: @engineCost
enginePoints: @enginePoints
category: @category
categoryDisplayName: @categoryDisplayName
group: @group
consolePart: @consolePart
engineStart: @engineStart
canUse: if @canUse? then @canUse.bind(item) else undefined
canResearch: if @canResearch? then @canResearch.bind(item) else undefined
}
class classes.Platform extends Base
constructor: (@name, @company, @id = @name) ->
super
@startAmount ?= 0
@unitsSold ?= 0
@audienceWeight ?= new SDP.Util.Weight(true)
@genreWeight ?= new SDP.Util.Weight(false)
@licensePrice ?= 0
@publishDate ?= new SDP.Util.Date(false)
@retireDate ?= new SDP.Util.Date(true)
@devCost ?= 0
@techLevel ?= 0
@iconUri ?= new SDP.Util.Filesystem.Path()
convert: ->
{
name: @name
id: @id
company: @company
startAmount: @startAmount
unitsSold: @unitsSold
licensePrice: @licensePrice
publishDate: convertClasses(@publishDate)
retireDate: convertClasses(@retireDate)
genreWeight: convertClasses(@genreWeight)
audienceWeight: convertClasses(@audienceWeight)
techLevel: @techLevel
iconUri: convertClasses(@iconUri)
imageDates: convertClasses(@imageDates)
marketPoints: convertClasses(@marketPoints)
}
class classes.Topic extends Base
BASE_OVERRIDE = [0,0,0,0,0,0,0,0,0]
constructor: (@name, @id) ->
super
@audienceWeight ?= new SDP.Util.Weight(true)
@genreWeight ?= new SDP.Util.Weight(false)
if not @overrides? or not SDP.Util.isArray(@overrides)
@overrides = [BASE_OVERRIDE,BASE_OVERRIDE,BASE_OVERRIDE,BASE_OVERRIDE,BASE_OVERRIDE,BASE_OVERRIDE]
@overrides.push(BASE_OVERRIDE) while @overrides.length < 6
o.push(0) for o in @overrides when o.length < 9
setOverride: (genreName, catName, value) ->
if SDP.Util.isArray(genreName)
@overrides = genreName
return @
if SDP.Util.isArray(catName) then value = catName
catOrNull = if value isnt catName and (SDP.Util.isString(catName) or SDP.Util.isInteger(catName)) then catName else null
positions = SDP.Util.getOverridePositions(genreName, catOrNull)
if value is catName
@overrides[positions[0]] = value
else
@overrides[positions[0]][positions[1]] = value
@
convert: ->
{
name: @name
id: @id
genreWeight: convertClasses(@genreWeight)
audienceWeight: convertClasses(@audienceWeight)
overrides: @overrides
}
class classes.ResearchProject extends Base
constructor: (@name, @description, @id) ->
super
@pointsCost ?= 0
@iconUri ?= new SDP.Util.Filesystem.Path()
@targetZone ?= 2
convert: ->
item = {
name: @name
id: @id
description: @description
pointsCost: @pointsCost
iconUri: convertClasses(@iconUri)
targetZone: @targetZone
repeatable: @repeatable
canResearch: if @canResearch? then @canResearch.bind(item) else undefined
complete: if @complete? then @complete.bind(item) else undefined
cancel: if @cancel? then @cancel.bind(item) else undefined
}
class classes.Training extends Base
constructor: (@name, @category, @categoryDisplayName = @category, @id) ->
super
@pointsCost ?= 0
@duration ?= 0
convert: ->
item = {
name: @name
id: @id
cost: @cost
pointsCost: @pointsCost
category: @category
categoryDisplayName: @categoryDisplayName
canSee: if @canSee? then @canSee.bind(item) else undefined
canUse: if @canUse? then @canUse.bind(item) else undefined
tick: if @tick? then @tick.bind(item) else undefined
complete: if @complete? then @complete.bind(item) else undefined
}
class classes.Contract extends Base
constructor: (@name, @size, @description, @id) ->
super
@tF ?= 0
@dF ?= 0
convert:
item = {
name: @name
id: @id
size: @size
description: @description
tF: @tF
dF: @dF
card: @card
generateCard: if @generateCard? then @generateCard.bind(item) else undefined
rF: @rF
}
class classes.Publisher extends Base
constructor: (@name, @id) ->
super
convert: ->
item = {
name: @name
id: @id
card: @card
generateCard: if @generateCard? then @generateCard.bind(item) else undefined
}
class classes.Event extends Base
constructor: (@id, @isRandomEvent) ->
super
@trigger ?= (company) -> false
convert: ->
item = {
id: @id
isRandomEvent: @isRandomEvent
notification: @notification
trigger: @tigger.bind(item)
getNotification: if @getNotification? then @getNotification.bind(item) else undefined
complete: if @complete? then @complete.bind(item) else undefined
}
)()
SDP.GDT = ( ->
GDT = {}
GDT.Company = {
companies: {}
clientUid: undefined
addCompany: (company) ->
if not company.uid then company.uid = GameManager.getGUID()
GDT.Company.companies[company.uid] = company
if company is GameManager.company then clientUid = company.uid
containsCompany: (company) -> companies[company.uid or company]?
getCompanies: -> GDT.Company.companies.slice()
getClientCompany: -> GDT.Company.companies[GDT.Company.clientUid]
getPlatformsFor: (company, includeInactive) ->
if includeInactive then return GDT.Platform.getAll().concat(company.licencedPlatforms)
company.availablePlatforms.concat(company.licencedPlatforms)
getByUid: (uid) -> GDT.Company.companes[uid]
}
Platforms.getPlatforms = GDT.Company.getPlatformsFor
oldResearchGetAll = Research.getAllItems
GDT.Research = {
researches: oldResearchGetAll().forEach((r) ->
switch r.category
when 'General' then r.type = 'basic'
when 'Game Design', 'Project Management', 'Technology', 'Publishing' then r.type = 'special'
else r.type = 'engine'
if r.id is 'Text Based' or r.id is '2D Graphics V1' or r.id is 'Basic Sound' then r.type = 'start'
if r.id is '2D Graphics V2' or r.id is 'Linear story' or r.id is 'Savegame' then r.engineStart = true
)
# start research is accessible without an engine
# basic research are researches that do not pertain specifically to engines
# engine research are researches that do pertain to engines
# special research is basically the misc, where it would fit nowhere else, for example Marketing
types: ['start', 'basic', 'engine', 'special']
getAll: -> GDT.Research.researches.concat(oldResearchGetAll().except(GDT.Research.researches))
getAvailable: (company, engine) -> GDT.Research.getAll().filter((r) ->
if r.type is 'start' then return true
if engine and engine.parts.first((e) -> e.id is r.id)? then return true
if r.enginePoints is 0 and company.researchCompleted.indexOf(r) isnt -1 then return true
if company.specialItems.indexOf(r) isnt -1 then return true
false
)
getAvailableEngineParts: (company) ->
if company.canDevelopEngine() then return GDT.Research.getAll().filter((r) ->
if r.engineStart then return true
if r.type is 'start' or r.type is 'basic' then return false
Research.getEnginePoints(r) isnt 0 and (Research.getEngineCost(r) isnt 0 and company.researchCompleted.indexOf(r) isnt -1)
)
[]
addSpecialItem: (company, idOrObj) -> company.specialItems.push(if SDP.Util.isString(idOrObj) then GDT.Researches.getAll().first((r) -> r.id is idOrObj) else idOrObj)
removeSpecialItem: (company, idOrObj) -> company.specialItems.remove(if SDP.Util.isString(idOrObj) then GDT.Researches.getAll().first((r) -> r.id is idOrObj) else idOrObj)
getById: (id) -> GDT.Research.getAll().first((r) -> r.id is id)
}
Research.getAllItems = GDT.Research.getAll
( ->
oldResearchPointsCost = Research.getPointsCost
Research.getPointsCost = (r) ->
if r.pointsCost then return r.pointsCost
return oldResearchPointsCost(r)
oldResearchDuration = Research.getDuration
Research.getDuration = (r) ->
if r.duration then return r.duration
return oldResearchDuration(r)
oldResearchDevCost = Research.getDevCost
Research.getDevCost = (r, game) ->
if r.devCost
value = r.devCost
if game
value *= General.getGameSizeDurationFactor(game.gameSize) * General.getMultiPlatformCostFactor(game)
value = Math.floor(value / 1e3) * 1e3
return value
return oldResearchDevCost(r, game)
oldResearchResearchCost = Research.getResearchCost
Research.getResearchCost = (r) ->
if r.researchCost then r.researchCost
return oldResearchResearchCost(r)
oldResearchEngineCost = Research.getEngineCost
Research.getEngineCost = (r) ->
if r.engineCost then return r.engineCost
return oldResearchEngineCost(r)
)()
GameManager.getAvailableGameFeatures = GDT.Research.getAvailable
General.getAvailableEngineParts = GDT.Research.getAvailableEngineParts
( ->
oldPlatformImage = Platforms.getPlatformImage
GDT.Platform = {
platforms: Platforms.allPlatforms
getAll: -> GDT.Platform.platforms.slice()
getAvailable: (company) ->
GDT.Company.getPlatformsFor(company).filter((p) ->
Platforms.getRetireDate(p) > Math.floor(company.currentWeek) and not p.isCustom or p.isCustom is true and (company.currentWeek > General.getWeekFromDateString(p.published) and not p.soldOut)
)
getImage: (platform, week) ->
if platform.id is 'PC' then return oldPlatformImage(platform, week)
if not platform.imageDates then return platform.iconUri
else if week
image = "{0}/{1}-{2}.png".format(baseUri, platform.id, String(i+1)) for date, i in platform.imageDates when General.getWeekFromDateString(date) <= week and i isnt 0
if not image then return "{0}/{1}.png".format(baseUri, platform.id) else return image
getById: (id) -> GDT.Platform.getAll().first((p) -> p.id is id)
}
Platforms.getPlatformsOnMarket = GDT.Platform.getAvailable
Platforms.getPlatformImage = GDT.Platform.getImage
)()
GDT.Topic = {
topics: Topics.topics
_topicBackup: JSON.parse(JSON.stringify(GDT.Topic.topics))
getAll: -> GDT.Topic.topics.slice()
getById: (id) -> GDT.Topic.getAll().first((t) -> t.id is id )
reset: (id) ->
index = GDT.Topic.topics.indexOf(GDT.Topic.getById(id))
if index isnt -1 then GDT.Topic.topics[index] = JSON.parse(JSON.stringify(GDT.Topic._topicBackup[index]))
}
GDT.ResearchProject = {
projects: Research.bigProjects
getAll: -> GDT.ResearchProject.projects.slice()
getAvailable: (company, zone) ->
GDT.ResearchProject.getAll().filter((p) ->
p.targetZone is zone and p.canResearch(company)
)
getById: (id) -> GDT.ResearchProject.getAll().first((r) -> r.id is id)
}
General.getAvailableProjects = GDT.ResearchProject.getAvailable
GDT.Training = {
trainings: Training.getAllTrainings()
getAll: ->
results = []
for item in GDT.Training.trainings.slice()
if item.id? and (item.pointsCost? and item.duration?)
item.isTraining = true
results.push(item)
results
getAvailable: (staff) ->
results = []
for t in GDT.Training.getAll()
results.push(t) if (t.canSee and t.canSee(staff, staff.company) or not t.canUse?) or (not t.canSee and t.canUse(staff, staff.company))
results
getById: (id) -> GDT.Training.getAll().first((t) -> t.id is id)
}
Training.getAllTrainings = GDT.Training.getAll
Training.getAvailableTraining = GDT.Training.getAvailable
# To prevent namespace clutter, stuck the contract stuff in a seperate function block
( ->
`var smallContracts = [{
name: "Logo Animation".localize("heading"),
description: "Create an animation for an existing logo.".localize(),
tF: 1,
dF: 2.5,
rF: 1.5
}, {
name: "Character Design".localize("heading"),
description: "Design some game characters.".localize(),
tF: 1,
dF: 4.5,
rF: 1.5
}, {
name: "Playtest".localize("heading"),
description: "Help to playtest a game.".localize(),
tF: 1,
dF: 1,
rF: 1.5
}, {
name: "Game Backdrops".localize("heading"),
description: "Design some simple background graphics for a game.".localize(),
tF: 1,
dF: 2,
rF: 1.5
}, {
name: "Setup Computers".localize("heading"),
description: "Install Mirconoft BOSS on computers".localize(),
tF: 2,
dF: 0.4
}, {
name: "Debug program".localize("heading"),
description: "Help debugging a convoluted BASE program.".localize(),
tF: 2,
dF: 0.2
}, {
name: "Spritesheet Software".localize("heading"),
description: "Our staff needs to be taught how to use these modern technologies.".localize(),
tF: 3,
dF: 2
}, {
name: "Library Software".localize("heading"),
description: "Develop a simple library management system".localize(),
tF: 5,
dF: 1
}];
var mediumContracts = [{
name: "Usability Study".localize("heading"),
description: "Perform a detailed usability study.".localize(),
tF: 5,
dF: 6.5
}, {
name: "Review Game Concept".localize("heading"),
description: "Review a game concept using your expertise.".localize(),
tF: 3,
dF: 8,
rF: 1.5
}, {
name: "Game Art".localize("heading"),
description: "Help out on a project with some game art".localize(),
tF: 5,
dF: 6,
rF: 1.5
}, {
name: "Clean up database".localize("heading"),
description: "Should one table really have 200 columns? Probably not.".localize(),
tF: 5,
dF: 1
}, {
name: "Accounting Software".localize("heading"),
description: "Develop a simple accounting software. Are those ever simple?".localize(),
tF: 5,
dF: 1
}, {
name: "Time Tracking".localize("heading"),
description: "Design and develop a time tracking system.".localize(),
tF: 3,
dF: 1
}, {
name: "Design a board game".localize("heading"),
description: "Let's see how your skills translate to traditional games.".localize(),
dF: 5,
tF: 0.2,
rF: 2
}, {
name: "Horoscope Generator".localize("heading"),
description: "Making up horoscopes is hard work. We want it automated.".localize(),
dF: 5,
tF: 1
}, {
name: "Character Dialogues".localize("heading"),
description: "Improve our character dialogues.".localize(),
dF: 5,
tF: 1,
rF: 1.4
}, {
name: "Futuristic Application".localize("heading"),
description: "We need an application that looks futuristic for a movie.".localize(),
dF: 3,
tF: 2,
rF: 1.5
}, {
name: "Vacuum Robot".localize("heading"),
description: "Create a revolutionary AI for a vacuum robot".localize(),
tF: 2,
dF: 1.4
}, {
name: "Website".localize("heading"),
description: "We just heard of this thing called internet. We want to have one.".localize(),
tF: 2,
dF: 1.3
}];
var largeContracts = [{
name: "Game Port".localize("heading"),
description: "Port a game to a different platform.".localize(),
tF: 3.2,
dF: 1.7,
rF: 1.2
}, {
name: "Cut Scenes".localize("heading"),
description: "Deliver professional cut scenes for a game.".localize(),
tF: 1,
dF: 1,
rF: 1.5
}, {
name: "Space Shuttle".localize("heading"),
description: "Deliver part of the space shuttle control software.".localize(),
tF: 3,
dF: 2
}, {
name: "Alien Search".localize("heading"),
description: "Optimize our search for alien life forms using advanced AI techniques.".localize(),
tF: 3,
dF: 1.8,
rF: 1.3
}, {
name: "Movies".localize("heading"),
description: "We need your skills in our latest blockbuster production.".localize(),
tF: 1,
dF: 1,
rF: 1.5
}]`
GDT.Contract = {
contracts: []
getAll: -> GDT.Contract.contracts.slice()
getAvailable: (company) ->
results = []
for c in GDT.Contract.getAll().filter((contract) -> not contract.isAvailable? or contract.isAvailable(company))
results.push(c)
results
getSettings: (company, size) ->
key = "contracts#{size}"
settings = company.flags[key]
if not settings
settings = {id:key}
company.flags[key] = settings
settings
getSeed: (settings) ->
newSeed = ->
settings.seed = Math.floor(Math.random() * 65535);
settings.expireBy = GameManager.gameTime + 24 * GameManager.SECONDS_PER_WEEK * 1e3;
settings.contractsDone = []
if not settings.seed
newSeed()
settings.intialSettings = true
else if settings.expireBy <= GameManager.gameTime
newSeed()
settings.intialSettings = false
settings.seed
createFromTemplate: (company, template, random) ->
item = if template.generateCard? then template.generateCard(company, random) else template.card
r = random.random()
if random.random > 0.8 then r+= random.random()
t = undefined
d = undefined
pay = undefined
weeks = undefined
penalty = undefined
if item.techPoints then t = item.techPoints
if item.designPoints then d = item.designPoints
if item.payment then pay = item.payment
if item.weeks then weeks = item.weeks
if item.penalty then penalty = item.penalty
unless t and d and pay and weeks and penalty
minPoints = undefined
tF = template.tF or item.tF
dF = template.dF or item.dF
unless t and d and not item.minPoints then minPoints = item.minPoints else
minPoints = switch template.size
when 'small' then 11
when 'medium' then 30
when 'large' then 100
minPoints += 6 if minPoints is 12 and company.staff.length > 2
minPoints += minPoints * (company.getCurrentDate().year / 25)
points = minPoints + minPoints * r
pointPart = points / (dF + tF)
unless d
d = pointPart * dF
d += d * 0.2 * random.random() * random.randomSign()
d = Math.floor(d)
unless t
t = pointPart * tF
t += t * 0.2 * random.random() * random.randomSign()
t = Math.floor(t)
unless pay then pay = Math.floor(points*1e3/1e3) * 1e3
unless weeks then (weeks = if template.size is small then Math.floor(3 + 3 * random.random()) else Math.floor(3 + 7 * random.random()))
unless penalty then penalty = Math.floor((pay * 0.2 + pay * 0.3 * random.random())/1e3) * 1e3
contractObject = {
name: template.name
description: template.description
id: 'genericContracts'
requiredD: d
requiredT: t
spawnedD: 0
spawnedT: 0
payment: pay
penalty: -penalty
weeksToFinish: weeks
rF: template.rF
isGeneric: true
size: template.size
complete: if template.complete? then template.complete.bind(contractObject) else undefined
}
generate: (company, size, max) ->
settings = GDT.Contract.getSettings(company, size)
random = new MersenneTwister(GDT.Contract.getSeed(settings))
count = Math.max(max - 1, Math.floor(random.random() * max))
results = []
set = GDT.Contract.getAvailable(company).filter((e) -> e.size is size)
if settings.initialSettings then count = Math.max(1, count)
i = 0
while i < count and set.length > 0
item = set.pickRandom(random)
set.remove(item)
contractInstance = GDT.Contract.createFromTemplate(company, item, random)
contractInstance.index = i
if settings.contractsDone and settings.contractsDone.indexOf(i) isnt -1
contract.skip = true
contracts.push(contract)
i++
contracts
getList: (company) ->
settings = GDT.Contract.getSettings(company, 'small')
results = GDT.Contract.generate(company, 'small', 4)
if company.flags.mediumContractsEnabled then results.addRange(GDT.Contract.generate(company, 'medium', 3))
if company.flags.largeContractsEnabled then results.addRange(GDT.Contract.generate(company, 'large', 2))
results.shuffle(new MersenneTwister(GDT.Contract.getSeed(settings))).filter((c) -> not c.skip)
getById: (id) -> GDT.Contract.getAll().first((c) -> c.id is id)
}
generateConvertContracts = (type) ->
(e) ->
e.size = type
e.id = e.name.replace(' ', '')
smallContracts.forEach(generateConvertContracts('small'))
mediumContracts.forEach(generateConvertContracts('medium'))
largeContracts.forEach(generateConvertContracts('large'))
GDT.Contract.contracts.addRange(smallContracts)
GDT.Contract.contracts.addRange(mediumContracts)
GDT.Contract.contracts.addRange(largeContracts)
ProjectContracts.generateContracts.getContract = GDT.Contract.getList
oldContractsComplete = ProjectContracts.genericContracts.complete
ProjectContracts.genericContracts.complete = (company, success, data) ->
contract.complete?()
oldContractsComplete(company, success, data)
)()
( ->
`var publishers = [{
id: "ActiveVisionaries",
name: "Active Visionaries"
}, {
id: "ea",
name: "Electronic Mass Productions"
}, {
id: "RockvilleSoftworks",
name: "Rockville Softworks"
}, {
id: "BlueBitGames",
name: "Blue Bit Games"
}, {
id: "CapeCom",
name: "CapeCom"
}, {
id: "Codemeisters",
name: "Codemeisters"
}, {
id: "DeepPlatinum",
name: "Deep Platinum"
}, {
id: "InfroGames",
name: "InfroGames"
}, {
id: "LoWoodProductions",
name: "LoWood Productions"
}, {
id: "TGQ",
name: "TGQ"
}, {
id: "\u00dcberSoft",
name: "\u00dcberSoft"
}]`
GDT.Publisher = {
publishers: publishers.slice()
getAll: -> GDT.Publisher.publishers.slice()
getAvailable: (company) ->
results = []
for p in GDT.Publisher.getAll().filter((publisher) -> not publisher.isAvailable? or publisher.isAvailable(company))
results.push(p)
results
generate: (company, max) ->
settings = GDT.Contract.getSettings(company, 'publisher')
seed = GDT.Contract.getSeed(settings)
random = new MersenneTwister(seed)
count = Math.max(max - 1, Math.floor(random.random() * max))
results = []
if settings.seed isnt seed
settings.topics = undefined
settings.researchedTopics = undefined
settings.excludes = undefined
settings.platforms = undefined
if not settings.topics or (not settings.researchedTopics or not settings.platforms)
topics = company.topics.slice()
topics.addRange(General.getTopicsAvailableForResearch(company))
settings.topics = topics.map((t) ->
t.id
)
researchedTopics = company.topics.map((t) ->
t.id
)
settings.researchedTopics = researchedTopics
platforms =
Platforms.getPlatformsOnMarket(company).filter((p) ->
not p.isCustom and Platforms.doesPlatformSupportGameSize(p, "medium")
)
settings.platforms = platforms.map((p) ->
p.id
)
settings.excludes = []
lastGame = company.gameLog.last()
if lastGame
settings.excludes.push {
genre: lastGame.genre.id
topic: lastGame.topic.id
}
else
topics = settings.topics.map((id) ->
Topics.topics.first((t) ->
t.id is id
)
)
researchedTopics = settings.researchedTopics.map((id) ->
Topics.topics.first((t) ->
t.id is id
)
)
allPlatforms = Platforms.getPlatforms(company, true);
platforms = settings.platforms.map((id) ->
allPlatforms.first((p) ->
p.id is id
)
)
excludes = settings.excludes.slice()
count = Math.max(max - 1, Math.floor(random.random() * max))
if settings.initialSetting then count = Math.max(1, count)
sizes = ['medium']
if company.canDevelopLargeGames() then sizes.addRange(["large", "large", "large"])
audiences = ["young", "everyone", "mature"]
sizeBasePay = { medium: 15e4, large: 15e5 / 2 }
for i in [0..count]
publisher = GDT.Publisher.getAvailable(company).pickRandom(random)
if publisher.generateCard or publisher.card
item = if publisher.generateCard? then publisher.generateCard(company) else publisher.card
if item and (item.size is 'small' or company["canDevelop#{item.size.capitalize()}Games"]?())
topic = item.topic
genre = item.genre
platform = item.platform
name = "#{if topic then topic.name else 'Any Topic'.localize()} / #{if genre then genre.name else 'Any Genre'.localize()}"
results.push contract = {
id: 'publisherContracts'
refNumber: Math.floor(Math.random() * 65535)
type: 'gameContract'
name: name
description: "Publisher: #{publisher.name}"
publisher: publisher.name
publisherObject: publisher
topic: if topic then topic.id else topic
genre: if genre then genre.id else genre
platform: if platform.id then platform.id else platform
gameSize: item.size,
gameAudience: item.audience,
minScore: item.minScore,
payment: item.pay,
penalty: item.penalty,
royaltyRate: item.royaltyRate
complete: if item.complete? then item.complete.bind(contract) else if publisher.complete then publisher.complete.bind(contract) else undefined
}
continue
diffculty = 0
topic = undefined
genre = undefined
if random.random() <= 0.7
genre = General.getAvailableGenres(company).pickRandom(random)
diffculty += 0.1
if random.random() <= 0.7
`do {
if (random.random() <= 0.7)
topic = topics.except(researchedTopics).pickRandom(random);
else
topic = topics.pickRandom(random);
if (topic === undefined)
break
} while (excludes.some(function (e) {
return (genre === undefined || e.genre === genre.id) && e.topic === topic.id
}))`
if topic? then diffculty += 0.1
if genre or topic then excludes.push {
genre: if genre then genre.id else undefined
topic: if topic then topic.id else undefined
}
platform = undefined
if random.random() <= 0.7 then platform = platforms.pickRandom(random)
audience = undefined
if company.canSetTargetAudience() and random.random() <= 0.2 then audience = audiences.pickRandom(random)
difficulty += 0.8 * random.random()
minScore = 4 + Math.floor(5 * difficulty)
size = undefined
`do
size = sizes.pickRandom(random);
while (platform != undefined && !Platforms.doesPlatformSupportGameSize(platform, size))`
basePay = sizeBasePay[size]
pay = Math.max(1, Math.floor((basePay * (minScore / 10))/5e3)) * 5e3
penalty = Math.floor((pay * 1.2 + pay * 1.8 * random.random())/5e3) * 5e3
pubObject = undefined
puName = undefined
if platform and (platform.company and random.random() <= 0.2) then pubName = platform.company
else
pubObject = publishers.pickRandom(random)
pubName = pubObject.name
royaltyRate = Math.floor(7 + 8 * difficulty) / 100
name = "#{if topic then topic.name else 'Any Topic'.localize()} / #{if genre then genre.name else 'Any Genre'.localize()}"
if not platform or Platforms.getPlatformsOnMarket(company).first((p) -> p.id is platform.id)
results.push contract = {
id: "publisherContracts"
refNumber: Math.floor(Math.random() * 65535)
type: "gameContract"
name: name
description: "Publisher: {0}".localize().format(pubName)
publisher: pubName
publisherObject: pubObject
topic: if topic then topic.id else topic
genre: if genre then genre.id else genre
platform: if platform then platform.id else undefined
gameSize: size
gameAudience: audience
minScore: minScore
payment: pay
penalty: penalty
royaltyRate: royaltyRate
complete: if pubObject.complete? then pubObject.complete.bind(contract) else undefined
}
else
count++
results
getById: (id) -> GDT.Publisher.getAll().first((p) -> p.id is id)
}
ProjectContracts.publisherContracts.getContract = (company) ->
GDT.Publisher.generate(company, 5).filter((p) -> not p.skip )
oldPublisherComplete = ProjectContracts.publisherContracts.complete
ProjectContracts.publisherContracts.complete = (company, success, data) ->
data.complete?(company, success, data)
oldPublisherComplete(company, success, data)
)()
( ->
reviewers = ["Star Games", "Informed Gamer", "Game Hero", "All Games"]
GDT.Review = {
reviewers: reviewers.slice()
messages: []
getAll: -> GDT.Review.reviewers.slice()
getAvailable: (company) ->
results = []
for r in GDT.Review.getAll().filter((reviewer) -> not reviewer.isAvailable? or reviewer.isAvailable(company))
results.push(r)
results
getAllMessages: -> GDT.Review.messages.slice()
pickReviewers: (count) ->
results = []
reviewers = GDT.Review.getAvailable()
r = undefined
for i in [0..count]
r = reviewers.pickRandom()
results.push(r)
reviewers.remove()
results
reviewLatestFor: (company) ->
negativeMessages = []
positiveMessages = []
mmoFactor = 1
game = company.currentGame
GDT.fire(GameManager, GDT.eventKeys.gameplay.beforeGameReview, {
company : company,
game : game
})
if game.flags.mmo then mmoFactor = 2
sequelTo = undefined
if game.sequelTo
sequelTo = company.getGameById(game.sequelTo)
if sequelTo.releaseWeek > company.currentWeek - 40 then game.flags.sequelsTooClose = true
tp = game.technologyPoints
dp = game.designPoints
generalModifier = 0
goodDecisions = 0
badDecisions = 0
if dp + tp >= 30
goldenRatio = GameGenre.getGoldenRatio(game.genre, game.secondGenre)
difference = dp * goldenRatio - tp
percentDifference = 0
percentDifference = if (tp > dp) then Math.abs(difference / tp * 100) else percentDifference = Math.abs(difference / dp * 100)
"goldenRatio percentDifference: {0}".format(percentDifference).log()
if Math.abs(percentDifference) <= 25
generalModifier += 0.1
goodDecisions += 1
positiveMessages.push("They achieved a great balance between technology and design.".localize())
else if Math.abs(percentDifference) > 50
generalModifier -= 0.1
if difference < 0 then negativeMessages.push("They should focus more on design.".localize())
else negativeMessages.push("They should focus more on technology.".localize())
executedDevMissions = game.featureLog.filter((m) -> m.missionType is "mission" )
optimalMissionFocus = executedDevMissions.filter((m) ->
percentage = m.duration / General.getGameSizeDurationFactor(game.gameSize) / General.getMultiPlatformDurationFactor(game) / (Missions.BASE_DURATION * 3)
Missions.getGenreWeighting(m, game) >= 0.9 and percentage >= 0.4
)
if optimalMissionFocus.length >= 2
generalModifier += 0.2
goodDecisions += optimalMissionFocus.length
positiveMessages.push("Their focus on {0} served this game very well.".localize().format(optimalMissionFocus.map((m) -> Missions.getMissionWithId(m.id)).pickRandom().name))
else if optimalMissionFocus.length is 1
generalModifier += 0.1
goodDecisions += 1
else
generalModifier -= 0.15 * mmoFactor
nonOptimalMissions = executedDevMissions.filter (m) ->
percentage = m.duration / General.getGameSizeDurationFactor(game.gameSize) / General.getMultiPlatformDurationFactor(game) / (Missions.BASE_DURATION * 3)
Missions.getGenreWeighting(m, game) < 0.8 and percentage >= 0.4
if nonOptimalMissions.length is 2
mission = Missions.getMissionWithId(nonOptimalMissions.pickRandom().id)
generalModifier -= 0.2 * mmoFactor
badDecisions += nonOptimalMissions.length
negativeMessages.push("Their focus on {0} is a bit odd.".localize().format(mission.name))
else if nonOptimalMissions.length is 1
generalModifier -= 0.1 * mmoFactor
badDecisions += 1
underdevelopedMissions = executedDevMissions.filter (m) ->
percentage = m.duration / General.getGameSizeDurationFactor(game.gameSize) / General.getMultiPlatformDurationFactor(game) / (Missions.BASE_DURATION * 3)
Missions.getGenreWeighting(m, game) >= 0.9 and percentage <= 0.2
for m in underdevelopedMissions
mission = Missions.getMissionWithId(m.id)
generalModifier -= 0.15 * mmoFactor
badDecisions += 1
negativeMessages.push("They shouldn't forget about {0}.".localize().format(mission.name))
value = (dp + tp) / 2 / General.getGameSizePointsFactor(game)
topicGenreMatch = GameGenre.getGenreWeighting(game.topic.genreWeightings, game.genre, game.secondGenre)
if topicGenreMatch <= 0.6
negativeMessages.push("{0} and {1} is a terrible combination.".localize().format(game.topic.name, game.getGenreDisplayName()))
else if topicGenreMatch is 1
positiveMessages.push("{0} and {1} is a great combination.".localize().format(game.topic.name, game.getGenreDisplayName()))
genreText = game.genre.name
if game.secondGenre then genreText += "-" + game.secondGenre.name
previousGame = company.gameLog.last()
if previousGame and (not game.flags.isExtensionPack and (previousGame.genre is game.genre and (previousGame.secondGenre is game.secondGenre and previousGame.topic is game.topic)))
penalty = -0.4
badDecisions += 1
sameGenreTopic = "Another {0}/{1} game?".localize().format(genreText, game.topic.name)
negativeMessages.push(sameGenreTopic)
game.flags.sameGenreTopic = true
"repeat genre/topic penalty: {0}:".format(penalty).log()
generalModifier += penalty
platformGenreMatch = Platforms.getGenreWeighting(game.platforms, game.genre, game.secondGenre)
if platformGenreMatch <= 0.6
smallestWeighting = Platforms.getNormGenreWeighting(game.platforms[0].genreWeightings, game.genre, game.secondGenre)
smallestWeightingIndex = 0
for p,i in game.platforms
tempWeighting = Platforms.getNormGenreWeighting(p.genreWeightings, game.genre, game.secondGenre)
if tempWeighting < smallestWeighting then smallestWeightingIndex = i
negativeMessages.push("{0} games don't work well on {1}.".localize().format(genreText, game.platforms[smallestWeightingIndex].name))
else if platformGenreMatch > 1
highestWeighting = Platforms.getNormGenreWeighting(game.platforms[0].genreWeightings, game.genre, game.secondGenre)
highestWeightingIndex = 0
for p,i in game.platforms
tempWeighting = Platforms.getNormGenreWeighting(p.genreWeightings, game.genre, game.secondGenre)
if tempWeighting > highestWeighting then highestWeightingIndex = i
positiveMessages.push("{0} games work well on {1}.".localize().format(genreText, game.platforms[highestWeightingIndex].name))
gameAudienceWeighting = General.getAudienceWeighting(game.topic.audienceWeightings, game.targetAudience)
if gameAudienceWeighting <= 0.6
negativeMessages.push("{0} is a horrible topic for {1} audiences.".localize().format(game.topic.name, General.getAudienceLabel(game.targetAudience)))
if game.flags.sequelsTooClose
generalModifier -= 0.4
badDecisions += 1
if game.flags.isExtensionPack then negativeMessages.push("Already a expansion pack?".localize()) else negativeMessages.push("Didn't we just play {0} recently?".localize().format(sequelTo.title))
if game.flags.usesSameEngineAsSequel and not game.flags.isExtensionPack
generalModifier -= 0.1
badDecisions += 1
else if game.flags.hasBetterEngineThanSequel
generalModifier += 0.2
goodDecisions += 1
if game.flags.mmo
weighting = GameGenre.getGenreWeighting(game.topic.genreWeightings, game.genre, game.secondGenre)
if weighting < 1 then generalModifier -= 0.15
bugModifier = 1
if game.bugs > 0
perc = 100 / (game.technologyPoints + game.designPoints)
bugsPercentage = (game.bugs * perc).clamp(0, 100)
bugModifier = 1 - 0.8 * (bugsPercentage / 100)
if bugModifier <= 0.6 then negativeMessages.push("Riddled with bugs.".localize())
else if bugModifier < 0.9 then negativeMessages.push("Too many bugs.".localize())
techLevelModifier = 1
if game.platforms.length > 1
maxTech = game.platforms[0].techLevel
if game.platforms[0].id is "PC" then maxTech = game.platforms[1].techLevel
minTech = maxTech
for p in game.platforms when p.id isnt "PC"
maxTech = Math.max(maxTech, p.techLevel)
minTech = Math.min(minTech, p.techLevel)
techLevelModifier -= (maxTech - minTech) / 20
value += value * generalModifier
value *= platformGenreMatch
value *= gameAudienceWeighting
value *= bugModifier
value *= techLevelModifier
trendModifier = GameTrends.getCurrentTrendFactor(game)
game.flags.trendModifier = trendModifier
value *= trendModifier
topScore = getCurrentTopScoreBarrier(company)
achievedRatio = value / topScore
if achievedRatio >= 0.6 and (gameAudienceWeighting <= 0.7 or topicGenreMatch <= 0.7)
achievedRatio = 0.6 + (achievedRatio - 0.6) / 2
if achievedRatio > 0.7
for p in game.platforms
if Platforms.getPlatformsAudienceWeighting(p.audienceWeightings, game.targetAudience) <= 0.8
value *= Platforms.getPlatformsAudienceWeighting(p.audienceWeightings, game.targetAudience, true)
achievedRatio = value / topScore
break
"achieved {0} / top game {1} = {2}".format(value, Reviews.topScore, achievedRatio).log()
demote = false
finalScore = (achievedRatio * 10).clamp(1, 10)
game.flags.teamContribution = 0
company.staff.forEach((s) -> if s.flags.gamesContributed < 1 then game.flags.teamContribution elsegame.flags.teamContribution += game.getRatioWorked(s) )
game.flags.teamContribution /= company.staff.length
if company.lastTopScore > 0 and finalScore <= 5.2 - 0.2 * game.platforms.length
if goodDecisions > 0 and (goodDecisions > badDecisions and game.flags.teamContribution >= 0.8)
baseScore = 6
numberWorkedOnGame = 0
for key of game.flags.staffContribution
if not game.flags.staffContribution.hasOwnProperty(key) then continue
numberWorkedOnGame++
optimalSize = General.getOptimalTeamSize(game)
diff = Math.abs(optimalSize - numberWorkedOnGame)
if diff > 1 then baseScore -= diff - 1
newStaff = Reviews.getNewStaff(game)
if newStaff
if newStaff.length > 0 then baseScore -= newStaff.length / 2
baseScore += goodDecisions / 2 - badDecisions / 2
if bugModifier < 0.9 then baseScore -= 0.5
else if bugModifier <= 0.6 then baseScore -= 1
if platformGenreMatch <= 0.8 then baseScore -= 1 - platformGenreMatch
if gameAudienceWeighting <= 0.8 then baseScore -= 1 - gameAudienceWeighting
if game.platforms.length > 1
maxTech = game.platforms[0].techLevel
if game.platforms[0].id is "PC"
maxTech = game.platforms[1].techLevel
minTech = maxTech
for p in game.platforms when p.id isnt "PC"
maxTech = Math.max(maxTech, p.techLevel)
minTech = Math.min(minTech, p.techLevel)
baseScore -= (maxTech - minTech) / 0.5
baseScore -= company.getRandom()
baseScore = Math.min(baseScore, 7.7)
if finalScore < baseScore
game.flags.scoreWithoutBrackets = finalScore
finalScore = baseScore
if company.gameLog.length > 3
topScoreDecrease = true
for i in [1..3]
tempGame = company.gameLog[company.gameLog.length - i]
if tempGame.score > 5.2 - 0.2 * tempGame.platforms.length and not tempGame.flags.scoreWithoutBrackets
topScoreDecrease = false
break
if topScoreDecrease
company.lastTopScore = value
game.flags.topScoreDecreased = true
maxScoreFactor = getMaxScorePossible(company, game) / 10
if game.gameSize isnt "medium" and (game.gameSize isnt "small" and maxScoreFactor < 1)
negativeMessages.push("Technology is not state of the art.".localize())
finalScore *= maxScoreFactor
if finalScore >= 9
if generalModifier < 0.1 and company.getRandom() < 0.8 then demote = true
else
newStaff = Reviews.getNewStaff(game)
if newStaff.length > 0
demote = true
game.flags.newStaffIds = newStaff.map((staff) -> staff.id )
if demote
if game.flags.newStaffIds and game.flags.newStaffIds.length > 0
finalScore = 8.15 + 0.95 / game.flags.newStaffIds.length * company.getRandom()
else
finalScore = 8.45 + 0.65 * company.getRandom()
if company.getRandom() < 0.1
finalScore = 9 + 0.25 * company.getRandom()
updateTopScore(company, value)
if sequelTo
if finalScore <= 4
if game.flags.isExtensionPack then negativeMessages.push("What a horrible expansion pack!".localize()) else negativeMessages.push("What a horrible sequel!".localize())
else if finalScore <= 7
if game.flags.isExtensionPack then negativeMessages.push("Average expansion pack.".localize()) else negativeMessages.push("Average sequel.".localize())
else
if game.flags.isExtensionPack then positiveMessages.push("Great expansion pack.".localize()) else positiveMessages.push("Great sequel!".localize())
if company.topScoreAchievements < 2 and company.getCurrentDate().year < 4
if finalScore == 10
finalScore -= 1.05 + 0.45 * company.getRandom()
setTopScoreAchievement(company, value)
else if finalScore >= 9
finalScore -= 1.05 + 0.2 * company.getRandom()
setTopScoreAchievement(company, value)
else if finalScore > 8.5 then finalScore -= 0.4 + 0.2 * company.getRandom()
if finalScore >= 9 then setTopScoreAchievement(company, value)
if finalScore isnt 10 and (game.flags.topScore and company.topScoreAchievements is 3) then finalScore = 10
game.score = finalScore
"final score: {0}".format(finalScore).log()
if sequelTo
if company.getRandom() <= 0.5 or not company.gameLog.some((g) -> g.sequelTo? )
if game.flags.isExtensionPack then Media.createExtensionPackStory(company, game)
else Media.createSequelStory(company, game)
retVal = Reviews.getReviews(game, finalScore, positiveMessages, negativeMessages)
GDT.fire(GameManager, GDT.eventKeys.gameplay.afterGameReview, {
company : company,
game : game,
reviews : retVal
})
retVal
generate: (game, finalScore, positiveMessages, negativeMessages) ->
intScore = Math.floor(finalScore).clamp(1, 10)
if finalScore >= 9.5 then intScore = 10
reviewers = GDT.Reviewer.pickReviewers(4)
reviews = []
usedMessages = []
scores = []
variation = 1
for reviewer in reviewers
if intScore is 5 or intScore is 6 then (variation = if GameManager.company.getRandom() < 0.05 then 2 else 1)
scoreVariation = if Math.randomSign() is 1 then 0 else variation * Math.randomSign()
score = (intScore + scoreVariation).clamp(1, 10)
if score is 10 and (scores.length is 3 and scores.average() is 10)
if not game.flags.psEnabled
if Math.floor(finalScore) < 10 or GameManager.company.getRandom() < 0.8 then score--
else if Math.floor(finalScore) is 10 and GameManager.company.getRandom() < 0.4 then score++
message = if reviewer.getMessage? then reviewer.getMessage(game, finalScore) else undefined
if message is undefined
`do {
if (GameManager.company.getRandom() <= 0.2)
if (scoreVariation >= 0 && (score > 2 && positiveMessages.length != 0))
message = positiveMessages.pickRandom();
else {
if (scoreVariation < 0 && (score < 6 && negativeMessages != 0))
message = negativeMessages.pickRandom()
}
else
message = undefined;
if (!message)
message = Reviews.getGenericReviewMessage(game, score)
} while (usedMessages.weakIndexOf(message) != -1)`
usedMessages.push(message)
scores.push(score)
reviews.push {
score : score,
message : message,
reviewerName : reviewer.name
}
reviews
getById: (id) -> GDT.Reviewer.getAll().first((r) -> r.id is id)
getMessageById: (id) -> GDT.Reviewer.getAllMessages.first((m) -> m.id is id)
}
GDT.Reviewer.reviewers.forEach((e, i) -> GDT.Reviewer.reviewers[i] = {name: e, id: e.replace(' ', '')})
)()
GDT.Event = {
events: DecisionNotifications.getAllNotificationsObjects()
getAll: -> GDT.Event.slice()
getAvailable: (company) ->
events = GDT.Event.getAll().filter((e) -> not e.isRandom and GDT.Event.isAvailable(e))
getRandom: (company) ->
spawnEvent = company.flags.nextRandomEvent and company.flags.nextRandomEvent <= GameManager.gameTime
unless company.flags.nextRandomEvent
company.flags.nextRandomEvent = (48 + 24 * company.getRandom()) * GameManager.SECONDS_PER_WEEK * 1e3
if spawnEvent
company.flags.nextRandomEvent = GameManager.gameTime + (36 + 48 * company.getRandom()) * GameManager.SECONDS_PER_WEEK * 1e3
candidates = GDT.Event.getAll().filter((e) ->
e.isRandomEvent and (company.flags.lastRandomEventId isnt e.id and GDT.Event.isAvailable(company, e))
)
event = candidates.pickRandom()
unless event then return []
company.flags.lastRandomEventId = event.id
return event
return []
trigger: (company, event) ->
unless company.eventTriggerCounts[event.id] then company.eventTriggerCounts[event.id] = 1
else company.eventTriggerCounts[event.id]++
return if event.notification then event.notification else event.getNotification(company)
isAvailable: (company, event) ->
if event.date
return false if Math.floor(company.currentWeek) < General.getWeekFromDateString(event.date, event.ignoreGameLengthModifier)
if event.maxTriggers or event.date
count = GameManager.company.eventTriggerCounts[event.id]
return false if count and count >= (if event.date then 1 else event.maxTriggers)
event.date or event.trigger and event.trigger(company)
getById: (id) -> GDT.Event.getAll().first((e) -> e.id is id )
}
GDT.Notification = {
queue: []
getNotification: (company, event) -> if event.notification then event.notification else event.getNotification(company)
getNewNotifications: (company) ->
results = GDT.Event.getAvailable(company).map((e) -> GDT.Event.trigger(company, e))
if results.length is 0 then results = [GDT.Event.trigger(company, GDT.Event.getRandom(company))]
results
}
DecisionNotifications.getNewNotifications = GDT.Notification.getNewNotifications
GDT.ModSupport = ( ->
ModSupport = {}
oldLoad = ModSupport.loadMod
ModSupport.loadMod = (enableMods, i) ->
SDP.Util.Logger.formatter = SDP.Util.Logger.printf
oldLoad(enableMods, i)
ModSupport
)()
ModSupport.loadMod = GDT.ModSupport.loadMod
GDT
)()
# Adds a basic wrapper of UltimateLib functionality for easy conversion to the SDP
( ->
SDP.ULWrapper = {}
unless String::endsWith?
String::endsWith = (a) ->
@substr(@length - a.length) is a
unless String::startsWith?
String::startsWith = (a) ->
@substr(0, a.length) is a
unless Number::truncateDecimals?
Number::truncateDecimals = (a) ->
b = @ - Math.pow(10, -a) / 2
b += b / Math.pow(2, 53)
b.toFixed(a)
SDP.ULWrapper.Logger = ( ->
Loggger = { enabled: true }
Logger.log = (e, c) ->
if not Logger.enabled then return
unless c? then SDP.Util.Logger.debug(e) else SDP.Util.Logger.error("#{e}\n#{c.message}")
Logger
)()
SDP.ULWrapper.Contracts = ( ->
Contracts = {}
Contracts.add = (c) ->
isAvailable = (isRand, chance) ->
if isRand is true
if (1 is Math.floor((Math.random() * chance) + 1)) is false then isRand = false
if isRand is false then isRand = true
return isRand
c.isAvailable = (company) ->
c.canTrigger(company) and isAvailable(c.isRandom, c.randomChance)
c.card = {
techPoints: c.requiredT
designPoints: c.requiredD
payment: c.payment
penalty: c.penalty
weeks: c.weeksToFinish
}
SDP.Functional.addContractItem(c)
Contracts.collection = (company) ->
SDP.GDT.Contract.getAvailable(company).filter((c) ->
c.size is 'small' or (company.flags.mediumContractsEnabled and c.size is 'medium') or (company.flags.largeContractsEnabled and c.size is 'large')
)
Contracts
)()
SDP.ULWrapper.Publishers = ( ->
Publishers = {}
# add Publisher modifications here
Publishers
)()
SDP.ULWrapper.Research = ( ->
Research = {}
# add Research modifications here
Research
)()
)()
###
Adds company tracking system
Companies.createCompany = (item) ->
if item.constructor is String then item = {name: item}
if not item.id? and item.name? then item.id = name.replace(/\s/g,"")
item.platforms = []
item.platforms.push(p) for p of Platforms.allPlatforms when p.company is item.name
item.sort = ->
item.platforms.sort (a,b) ->
General.getWeekFromDateString(a.published) - General.getWeekFromDateString(b.published)
item.addPlatform = (platform) ->
return if item.platforms.find((val) -> platform.id is val.id)?
platform.company = item.name
SDP.GDT.addPlatform(platform)
item.platforms.push(platform)
item.sort()
platform
item.sort()
item
Companies.createVanillaCompany = (item) ->
Companies.createCompany(item)
item.isVanilla = true
item
Companies.vanillaCompanies = [
Companies.createVanillaCompany("Micronoft")
Companies.createVanillaCompany("Grapple")
Companies.createVanillaCompany("Govodore")
Companies.createVanillaCompany("Ninvento")
Companies.createVanillaCompany("Vena")
Companies.createVanillaCompany("Vonny")
Companies.createVanillaCompany("KickIT")
]
Companies.moddedCompanies = []
Companies.getAllCompanies = ->
c = Companies.vanillaCompanies.filter (val) -> val.id?
c.addRange(Companies.moddedCompanies.filter (val) -> val.id?)
for comp of c
comp.sort = ->
comp.platforms.sort (a,b) ->
General.getWeekFromDateString(a.published) - General.getWeekFromDateString(b.published)
comp.sort()
c.sort (a,b) ->
General.getWeekFromDateString(a.platforms[0].published) - General.getWeekFromDateString(b.platforms[0].published)
c
Companies.getAvailableCompanies = (company) ->
week = Math.floor(company.currentWeek)
Companies.getAllCompanies().filter (val) ->
General.getWeekFromDateString(val.platforms[0].published) <= week
###
GDT.on(GDT.eventKeys.saves.loaded, ->
GameManager.company.notifications.push(i) for i in SDP.GDT.Notification.queue
SDP.GDT.Notification.queue = [])
GDT.on(GDT.eventKeys.saves.newGame, ->
GameManager.company.notifications.push(i) for i in SDP.GDT.Notification.queue
SDP.GDT.Notification.queue = [])
###
Modifies GDT classes to make all objects indepedent of GameManager.company
###
( ->
oldGameConst = Game
oldGame = oldGameConst::
Game = (company) ->
oldGameConst.call(@, company)
@company = company
return
Game:: = oldGame
)()
( ->
oldCharConst = Character
oldChar = oldCharConst::
Character = (args...) ->
oldCharConst.call(@, args)
@company = args[0].company or SDP.GDT.Company.getAllCompanies()[args[0].uid] or SDP.GDT.Company.getClientCompany()
return
Character:: = oldChar
oldSave = Character::save
Character::save = ->
oldSave.call(@).companyId = @company.uid
)()
( ->
oldCompanyConst = Company
oldCompany = oldCompanyConst::
Company = (args...) ->
oldCompanyConst.call(@, args)
SDP.GDT.Company.addCompany(@)
return
Company:: = oldCompany
)()
###
Allow adding famous people and adding custom applicant algorithims
JobApplicants.moddedFamous = []
JobApplicants.moddedAlgorithims = []
JobApplicants.getRandomMale = (random) ->
results = []
JobApplicants.moddedAlgorithims.forEach (val) ->
results.push(val.apply(random)) if val.forMale
results.pickRandom(random)
JobApplicants.getRandomFemale = (random) ->
results = []
JobApplicants.moddedAlgorithims.forEach (val) ->
results.push(val.apply(random)) if not val.forMale
results.pickRandom(random)
JobApplicants.getFamousMale = (tech, design, random) ->
results = []
JobApplicants.moddedFamous.forEach (val) ->
results.push(val.apply(random, tech, design)) if val.forMale
results.pickRandom(random)
JobApplicants.getFamousFemale = (tech, design, random) ->
results = []
JobApplicants.moddedFamous.forEach (val) ->
results.push(val.apply(random, tech, design)) if not val.forMale
results.pickRandom(random)
JobApplicants.searchTests =
[
{
id : "ComplexAlgorithms"
name : "Complex Algorithms".localize()
minT : 0.6
}
{
id : "GameDemo"
name : "Game Demo".localize()
minD : 0.3,
minT : 0.3
}
{
id : "Showreel"
name : "Showreel".localize()
minD : 0.6
}
]
UI.__olgGenerateJobApplicants = UI._generateJobApplicants
UI._generateJobApplicants = ->
oldApplicants = UI.__olgGenerateJobApplicants()
settings = GameManager.uiSettings["findStaffData"]
settings = {ratio : 0.1, tests : []} if not settings
settings.seed = Math.floor(GameManager.company.getRandom() * 65535) if not settings.seed
ratio = settings.ratio
test = JobApplicants.searchTests.first (t) -> t.id is settings.tests.first()
company = GameManager.company
random = new MersenneTwister(settings.seed)
newApplicants = []
count = Math.floor(2 + 3 * (ratio + 0.2).clamp(0, 1))
rerolls = 0
maxRerolls = 2
maxBonus = if company.currentLevel is 4 then 4 / 5 else 2 / 5
takenNames = GameManager.company.staff.map (s) -> s.name
for i in [0...count]
qBonusFactor = ratio / 3 + (1 - ratio / 3) * random.random()
maxBonus += 1 / 5 if random.random() >= 0.95
q = 1 / 5 + maxBonus * qBonusFactor
level = Math.floor(q * 5).clamp(1,5)
maxD = 1
minD = 0
if test
maxD -= test.minT if test.minT
if test.minD
minD = test.minD
maxD -= minD
baseValue = 200 * level
d = baseValue * minD + baseValue * maxD * random.random()
t = baseValue - d
rBonusFactor = random.random()
r = 1 / 5 + maxBonus * rBonusFactor
sBonusFactor = random.random()
s = 1 / 5 + maxBonus * sBonusFactor
goodRoll = sBonusFactor > 0.5 and (qBonusFactor > 0.5 and rBonusFactor > 0.5)
if not goodRoll and (rerolls < maxRerolls and random.random() <= (ratio + 0.1).clamp(0, 0.7))
i--
rerolls++
continue
rerolls = 0
isFamous = false
sex = "male"
loop
sex = "male"
if goodRoll
name = JobApplicants.getFamousMale(t, d, random) if (random.random() > 0.15)
else
name = JobApplicants.getFamousFemale(t, d, random)
sex = "female"
isFamous = true
else
name = JobApplicants.getRandomMale(random) if random.random() > 0.25
else
name = JobApplicants.getRandomFemale(random)
sex = "female"
isFamous = false
break unless takenNames.indexOf(name) != -1
takenNames.push(name)
salary = Character.BASE_SALARY_PER_LEVEL * level
salary += salary * 0.2 * random.random() * random.randomSign()
salary = Math.floor(salary/1e3) * 1e3
newApplicants.push {
name : name,
qualityFactor : q,
technologyFactor : t / 500,
designFactor : d / 500,
researchFactor : r,
speedFactor : s,
salary : salary,
isFamous : isFamous,
sex : sex
}
GDT.fire GameManager, GDT.eventKeys.gameplay.staffApplicantsGenerated, {
newApplicants : newApplicants
settings : settings
rng : random
}
applicants = []
for i in [0...count]
if random.random() >= 0.5
a = newApplicants.pickRandom(random)
applicants.push(a)
newApplicants.remove(a)
else
a = oldApplicants.pickRandom(random)
applicants.push(a)
oldApplicants.remove(a)
return applicants
### | 120433 | ### Definitions for the devised SpartaDoc
All types can either contain the name of the types as found here or the vanilla API as analogs, this is corrected by the SDP
---
@customType ResearchItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [String] type The SDP.GDT.Research.types string this represents
@instruction('optional' if 'v')
@attribute [Integer] pointsCost The cost of the research in research points
@attribute [Integer] duration The time it takes to complete the research in milliseconds
@attribute [Integer] researchCost The cost this research will take to research, without devCost, small scale devCost = researchCost * 4
@instruction('optional' if 'researchCost') @attribute [Integer] devCost The cost to develop with this research on in small scale
@attribute [Integer] engineCost The cost to put this into an engine
@defaults(pointsCost) @attribute [Integer] enginePoints The amount of points this will cost to put in an engine
@attribute [String] category May be SDP.Constants.ResearchCategory of the object, or maybe something else
@attribute [String] categoryDisplayName Similar to category, human readable version
@optional
@attribute [Integer] v A basic value to scale the research by
@attribute [String] group The group to assign this research to, prevents more then one group being selected on games
@attribute [Boolean] consolePart Whether this research applies to console creation as well
@attribute [Boolean] engineStart Whether the research is available to all engines without research, overrides canResearch to always return false
@attribute [Function(Game)] canUse Determines whether this research can be used
@fparam [Game] game The game to test use against
@freturn [Boolean] Whether the research can be used
@attribute [Function(CompanyItem)] canResearch Determines whether this research is allowed to be researched
@fparam [CompanyItem] company The company to check whether its researchable for
@freturn [Boolean] Whether the research can be researched
---
@customType PlatformItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [String] company The company name this platform belongs to
@attribute [Float] startAmount The starting amount of units sold on release (multiplied by 5000000)
@attribute [Float] unitsSold The resulting units sold by the end (multiplied by 5000000)
@attribute [Integer] licensePrice The one time license price to develop on the platform
@attribute [String] publishDate The release date of the platform
@attribute [String] retireDate The retire date of the platform
@attribute [Integer] devCost The dev cost for developing on the platform
@attribute [Integer] techLevel The tech level of the platform (1-9, determines how ingenious the platform and the games for it will be)
@attribute [String] iconUri The icon refered to for the icon of the platform (or base uri if contains imageDates)
@attribute [Array {String date, Float amount}] marketPoints The key date points of the market in which the units sold change to the amount
@attribute [Array [6 Float]] genreWeight The weightings per genre based on SDP.Constants.Genre
@attribute [Array [3 Float]] audienceWeight The weightings per audience based on SDP.Constants.Audience
@optional @attribute [Array [String]] imageDates The dates for the platform image to change
---
@customType TopicItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [Array [6 Float]] genreWeight The weightings per genre based on SDP.Constants.Genre
@attribute [Array [3 Float]] audienceWeight The weightings per audience based on SDP.Constants.Audience
@attribute [Array [6 Array [9 Float]]] overrides The mission overrides as described on the [wiki](https://github.com/greenheartgames/gdt-modAPI/wiki/missionOverrides)
---
@customType ResearchProjectItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [String] description The description of the project
@attribute [Integer] pointsCost The cost to make in research points
@attribute [String] iconUri The uri of the icon to display for the project
@attribute [Integer] targetZone The zone for the project to take place in (0 for Hardware Lab, 2 for Research Lab, Effects of 1 unknown)
@optional @attribute [Boolean] repeatable Determiners whether the project can be repeated
@optional @attribute [Function(CompanyItem)] canResearch Determines whether research can be done
@fparam [CompanyItem] company The company being tested
@freturn [Boolean] Whether research can be done on the project
@optional @attribute [Function(CompanyItem)] complete A function to perform on completion
@fparam [CompanyItem] company The company responsible for completing the project
@optional @attribute [Function(CompanyItem)] cancel Activates on cancelation of the project
@fparam [CompanyItem] company The company canceling the project
---
@customType TrainingItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [Integer] pointsCost The cost in research points
@attribute [Integer] duration How long it will take to complete the training
@attribute [String] category The category of the object
@attribute [String] categoryDisplayName Similar to category, human readable version
@optional
@attribute [Integer] cost The cost in money
@attribute [Function(CharacterObject, CompanyItem)] canSee Determines whether the staff can see this training
@fparam [CharacterObject] staff The staff that should be able to see the training
@fparam [CompanyItem] company The company the training is taken place in
@freturn [Boolean] Whether the training can be seen
@attribute [Function(CharacterObject, CompanyItem)] canUse Determines whether the staff can use this training
@fparam [CharacterObject] staff The staff that should be able to use the training
@fparam [CompanyItem] company The company the training is taken place in
@freturn [Boolean] Whether the training can be used
@attribute [Function(CharacterObject, Integer)] tick Triggers every game tick this training is active
@fparam [CharacterObject] staff The staff that is performing the training
@fparam [Integer] delta The amount of milliseconds passed from the last tick
@attribute [Function(CharacterObject)] complete Triggers on training completion
@fparam [CharacterObject] staff The staff to complete the training
---
@customType ContractItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [String] description The description of the contract
@attribute [String] size The size of the contract, either small, medium, or large
@attribute [Float] tF The tech factor of the contract
@attribute [Float] dF The design factor of the contract
@optional
@attribute [Function(CompanyItem, MersenneTwister)] generateCard Generates a contract card depending on the company and random
@fparam [CompanyItem] company The company to generate the card for
@fparam [MersenneTwister] random The random object used for generating the contract
@freturn [ContractCardItem] The card item representing the contract generated
@attribute [ContractCardItem] card The card item to repsent the contract definitely (generateCard takes priority)
@attribute [Function(CompanyItem)] complete A function to perform on completion
@fparam [CompanyItem] company The company responsible for completing the contract
@note generateCard and card can be ignored if tF and dF are supplied and vice versa
@optional
@attribute [Float] rF The research factor generated
---
@customType PublisherItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
---
@customType ReviewerItem
---
@customType NotificationItem
@attribute [String] header The header of the notification
@attribute [String] text The text to display upon notifcation being tiggered
@instruction('optional' if 'options')
@attribute [String] buttonTxt The text for the button to display
@instruction('optional' if 'buttonTxt')
@attribute [Array [1-3 String]] options A collection of possible button options to choose from
@optional
@attribute [String] image The image uri for the notification
@attribute [String] sourceId The id of the corresponding event object
@attribute [Integer] weeksUntilFire The amount of weeks that must pass before this notification is fired
---
@customType EventItem
@attribute [String] id The id of the event
@attribute [Function(CompanyItem)] trigger Determines whether the event can trigger
@fparam [CompanyItem] company The company to test this trigger by
@instruction('optional' if 'getNotification') @attribute [NotificationItem] notification The notification for this event (overrides getNotification)
@instruction('optional' if 'notification') @attribute [Function(CompanyItem)] Retrieves a notification for this event
@fparam [CompanyItem] company The company to retrieve the notification for
@freturn [NotificationItem] The notification that was produced
@optional
@attribute [Boolean] isRandomEvent Determines whether this event is random
@attribute [Function(Integer)] complete Determines what happens upon completion (this.runningCompany refers to the active company for this event)
@fparam [Integer] decision The decision chosen in the notification from 0 to 2
---
@customType ContractCardItem
@optional
@attribute [Integer] techPoints The tech points to generate for the contract (overrides tF)
@attribute [Integer] designPoints The design points to generate for the contract (overrides dF)
@attribute [Float] tF The tech factor generated for the card
@attribute [Float] dF The design factor generated for the card
@attribute [Integer] minPoints The minimum points to generate based on factors (ignored if techPoints and designPoints supplied)
@attribute [Integer] pay The pay available upon the contract's completion
@attribute [Integer] penalty The penalty for job failure
@attribute [Integer] weeks The amount of weeks determined to finish the contracts
###
style = require('./lib-js/style')
# @namespace Spartan Dev Project
#
# The primary namespace holding all of the SDP
SDP = {}
Companies = {}
JobApplicants = {}
###
jSTORAGE
###
`(function(){function C(){var a="{}";if("userDataBehavior"==f){g.load("jStorage");try{a=g.getAttribute("jStorage")}catch(b){}try{r=g.getAttribute("jStorage_update")}catch(c){}h.jStorage=a}D();x();E()}function u(){var a;clearTimeout(F);F=setTimeout(function(){if("localStorage"==f||"globalStorage"==f)a=h.jStorage_update;else if("userDataBehavior"==f){g.load("jStorage");try{a=g.getAttribute("jStorage_update")}catch(b){}}if(a&&a!=r){r=a;var l=p.parse(p.stringify(c.__jstorage_meta.CRC32)),k;C();k=p.parse(p.stringify(c.__jstorage_meta.CRC32));
var d,n=[],e=[];for(d in l)l.hasOwnProperty(d)&&(k[d]?l[d]!=k[d]&&"2."==String(l[d]).substr(0,2)&&n.push(d):e.push(d));for(d in k)k.hasOwnProperty(d)&&(l[d]||n.push(d));s(n,"updated");s(e,"deleted")}},25)}function s(a,b){a=[].concat(a||[]);var c,k,d,n;if("flushed"==b){a=[];for(c in m)m.hasOwnProperty(c)&&a.push(c);b="deleted"}c=0;for(d=a.length;c<d;c++){if(m[a[c]])for(k=0,n=m[a[c]].length;k<n;k++)m[a[c]][k](a[c],b);if(m["*"])for(k=0,n=m["*"].length;k<n;k++)m["*"][k](a[c],b)}}function v(){var a=(+new Date).toString();
if("localStorage"==f||"globalStorage"==f)try{h.jStorage_update=a}catch(b){f=!1}else"userDataBehavior"==f&&(g.setAttribute("jStorage_update",a),g.save("jStorage"));u()}function D(){if(h.jStorage)try{c=p.parse(String(h.jStorage))}catch(a){h.jStorage="{}"}else h.jStorage="{}";z=h.jStorage?String(h.jStorage).length:0;c.__jstorage_meta||(c.__jstorage_meta={});c.__jstorage_meta.CRC32||(c.__jstorage_meta.CRC32={})}function w(){if(c.__jstorage_meta.PubSub){for(var a=+new Date-2E3,b=0,l=c.__jstorage_meta.PubSub.length;b<
l;b++)if(c.__jstorage_meta.PubSub[b][0]<=a){c.__jstorage_meta.PubSub.splice(b,c.__jstorage_meta.PubSub.length-b);break}c.__jstorage_meta.PubSub.length||delete c.__jstorage_meta.PubSub}try{h.jStorage=p.stringify(c),g&&(g.setAttribute("jStorage",h.jStorage),g.save("jStorage")),z=h.jStorage?String(h.jStorage).length:0}catch(k){}}function q(a){if("string"!=typeof a&&"number"!=typeof a)throw new TypeError("Key name must be string or numeric");if("__jstorage_meta"==a)throw new TypeError("Reserved key name");
return!0}function x(){var a,b,l,k,d=Infinity,n=!1,e=[];clearTimeout(G);if(c.__jstorage_meta&&"object"==typeof c.__jstorage_meta.TTL){a=+new Date;l=c.__jstorage_meta.TTL;k=c.__jstorage_meta.CRC32;for(b in l)l.hasOwnProperty(b)&&(l[b]<=a?(delete l[b],delete k[b],delete c[b],n=!0,e.push(b)):l[b]<d&&(d=l[b]));Infinity!=d&&(G=setTimeout(x,Math.min(d-a,2147483647)));n&&(w(),v(),s(e,"deleted"))}}function E(){var a;if(c.__jstorage_meta.PubSub){var b,l=A,k=[];for(a=c.__jstorage_meta.PubSub.length-1;0<=a;a--)b=
c.__jstorage_meta.PubSub[a],b[0]>A&&(l=b[0],k.unshift(b));for(a=k.length-1;0<=a;a--){b=k[a][1];var d=k[a][2];if(t[b])for(var n=0,e=t[b].length;n<e;n++)try{t[b][n](b,p.parse(p.stringify(d)))}catch(g){}}A=l}}var y=window.jQuery||window.$||(window.$={}),p={parse:window.JSON&&(window.JSON.parse||window.JSON.decode)||String.prototype.evalJSON&&function(a){return String(a).evalJSON()}||y.parseJSON||y.evalJSON,stringify:Object.toJSON||window.JSON&&(window.JSON.stringify||window.JSON.encode)||y.toJSON};if("function"!==
typeof p.parse||"function"!==typeof p.stringify)throw Error("No JSON support found, include //cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js to page");var c={__jstorage_meta:{CRC32:{}}},h={jStorage:"{}"},g=null,z=0,f=!1,m={},F=!1,r=0,t={},A=+new Date,G,B={isXML:function(a){return(a=(a?a.ownerDocument||a:0).documentElement)?"HTML"!==a.nodeName:!1},encode:function(a){if(!this.isXML(a))return!1;try{return(new XMLSerializer).serializeToString(a)}catch(b){try{return a.xml}catch(c){}}return!1},
decode:function(a){var b="DOMParser"in window&&(new DOMParser).parseFromString||window.ActiveXObject&&function(a){var b=new ActiveXObject("Microsoft.XMLDOM");b.async="false";b.loadXML(a);return b};if(!b)return!1;a=b.call("DOMParser"in window&&new DOMParser||window,a,"text/xml");return this.isXML(a)?a:!1}};y.jStorage={version:"0.4.12",set:function(a,b,l){q(a);l=l||{};if("undefined"==typeof b)return this.deleteKey(a),b;if(B.isXML(b))b={_is_xml:!0,xml:B.encode(b)};else{if("function"==typeof b)return;
b&&"object"==typeof b&&(b=p.parse(p.stringify(b)))}c[a]=b;for(var k=c.__jstorage_meta.CRC32,d=p.stringify(b),g=d.length,e=2538058380^g,h=0,f;4<=g;)f=d.charCodeAt(h)&255|(d.charCodeAt(++h)&255)<<8|(d.charCodeAt(++h)&255)<<16|(d.charCodeAt(++h)&255)<<24,f=1540483477*(f&65535)+((1540483477*(f>>>16)&65535)<<16),f^=f>>>24,f=1540483477*(f&65535)+((1540483477*(f>>>16)&65535)<<16),e=1540483477*(e&65535)+((1540483477*(e>>>16)&65535)<<16)^f,g-=4,++h;switch(g){case 3:e^=(d.charCodeAt(h+2)&255)<<16;case 2:e^=
(d.charCodeAt(h+1)&255)<<8;case 1:e^=d.charCodeAt(h)&255,e=1540483477*(e&65535)+((1540483477*(e>>>16)&65535)<<16)}e^=e>>>13;e=1540483477*(e&65535)+((1540483477*(e>>>16)&65535)<<16);k[a]="2."+((e^e>>>15)>>>0);this.setTTL(a,l.TTL||0);s(a,"updated");return b},get:function(a,b){q(a);return a in c?c[a]&&"object"==typeof c[a]&&c[a]._is_xml?B.decode(c[a].xml):c[a]:"undefined"==typeof b?null:b},deleteKey:function(a){q(a);return a in c?(delete c[a],"object"==typeof c.__jstorage_meta.TTL&&a in c.__jstorage_meta.TTL&&
delete c.__jstorage_meta.TTL[a],delete c.__jstorage_meta.CRC32[a],w(),v(),s(a,"deleted"),!0):!1},setTTL:function(a,b){var l=+new Date;q(a);b=Number(b)||0;return a in c?(c.__jstorage_meta.TTL||(c.__jstorage_meta.TTL={}),0<b?c.__jstorage_meta.TTL[a]=l+b:delete c.__jstorage_meta.TTL[a],w(),x(),v(),!0):!1},getTTL:function(a){var b=+new Date;q(a);return a in c&&c.__jstorage_meta.TTL&&c.__jstorage_meta.TTL[a]?(a=c.__jstorage_meta.TTL[a]-b)||0:0},flush:function(){c={__jstorage_meta:{CRC32:{}}};w();v();s(null,
"flushed");return!0},storageObj:function(){function a(){}a.prototype=c;return new a},index:function(){var a=[],b;for(b in c)c.hasOwnProperty(b)&&"__jstorage_meta"!=b&&a.push(b);return a},storageSize:function(){return z},currentBackend:function(){return f},storageAvailable:function(){return!!f},listenKeyChange:function(a,b){q(a);m[a]||(m[a]=[]);m[a].push(b)},stopListening:function(a,b){q(a);if(m[a])if(b)for(var c=m[a].length-1;0<=c;c--)m[a][c]==b&&m[a].splice(c,1);else delete m[a]},subscribe:function(a,
b){a=(a||"").toString();if(!a)throw new TypeError("Channel not defined");t[a]||(t[a]=[]);t[a].push(b)},publish:function(a,b){a=(a||"").toString();if(!a)throw new TypeError("Channel not defined");c.__jstorage_meta||(c.__jstorage_meta={});c.__jstorage_meta.PubSub||(c.__jstorage_meta.PubSub=[]);c.__jstorage_meta.PubSub.unshift([+new Date,a,b]);w();v()},reInit:function(){C()},noConflict:function(a){delete window.$.jStorage;a&&(window.jStorage=this);return this}};(function(){var a=!1;if("localStorage"in
window)try{window.localStorage.setItem("_tmptest","tmpval"),a=!0,window.localStorage.removeItem("_tmptest")}catch(b){}if(a)try{window.localStorage&&(h=window.localStorage,f="localStorage",r=h.jStorage_update)}catch(c){}else if("globalStorage"in window)try{window.globalStorage&&(h="localhost"==window.location.hostname?window.globalStorage["localhost.localdomain"]:window.globalStorage[window.location.hostname],f="globalStorage",r=h.jStorage_update)}catch(k){}else if(g=document.createElement("link"),
g.addBehavior){g.style.behavior="url(#default#userData)";document.getElementsByTagName("head")[0].appendChild(g);try{g.load("jStorage")}catch(d){g.setAttribute("jStorage","{}"),g.save("jStorage"),g.load("jStorage")}a="{}";try{a=g.getAttribute("jStorage")}catch(m){}try{r=g.getAttribute("jStorage_update")}catch(e){}h.jStorage=a;f="userDataBehavior"}else{g=null;return}D();x();"localStorage"==f||"globalStorage"==f?"addEventListener"in window?window.addEventListener("storage",u,!1):document.attachEvent("onstorage",
u):"userDataBehavior"==f&&setInterval(u,1E3);E();"addEventListener"in window&&window.addEventListener("pageshow",function(a){a.persisted&&u()},!1)})()})()`
###
jSTORAGE End
###
"use strict"
SDP.Util = ( ->
util = {}
fs = require('fs')
path = require('path')
normalizeStringPosix = (path, allowAboveRoot) ->
res = ''
lastSlash = -1
dots = 0
code = undefined
for i in [0..path.length]
if i < path.length then code = path.charCodeAt(i)
else if code is 47 then break
else code = 47
if code is 47
if lastSlash is i - 1 or dots is 1
#NOOP
else if lastSlash isnt i - 1 and dots is 2
if res.length < 2 or res.charCodeAt(res.length - 1) isnt 46 or res.charCodeAt(res.length - 2) isnt 46
if res.length > 2
start = res.length - 1
j = start
for j in [start..0]
if res.charCodeAt(j) is 47 then break
if j isnt start
if j is -1 then res = ''
else res = res.slice(0, j)
lastSlash = i
dots = 0
continue
else if res.length is 2 or res.length is 1
res = ''
lastSlash = i
dots = 0
continue
if allowAboveRoot
if res.length > 0 then res += '/..'
else res = '..'
else
if res.length > 0 then res += '/' + path.slice(lastSlash + 1, i)
else res = path.slice(lastSlash + 1, i)
lastSlash = i
dots = 0
else if code is 46 and dots isnt -1 then ++dots else dots = -1
return res
# Define very useful, efficent (as much as possible), basic utility functions
util.GLOBAL = (Function("return this"))()
util.kindOf = (obj) -> Object.prototype.toString.call(obj).slice(8, -1)
util.hasOwn = (obj, key) -> Object.prototype.hasOwnProperty.call(obj, key)
util.isKind = (obj, kind) -> util.kindOf(obj) is kind
util.isUndefined = (obj) -> obj is undefined
util.isNull = (obj) -> obj is null
util.isString = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is String
util.isArray = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is Array
util.isNumber = (obj) ->
if obj is undefined or obj is null or obj isnt obj then return false
return obj.constructor is Number
util.isInteger = (obj) -> util.isNumber(obj) and (obj % 1 is 0)
util.isFloat = (obj) -> util.isNumber(obj) and (obj % 1 isnt 0)
util.isObject = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is Object
util.isBoolean = (obj) -> obj is true or obj is false
util.isFunction = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is Function
util.isDate = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is Date
util.isRegExp = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is RegExp
util.isPlainObject = (obj) -> not not value and typeof value is 'object' and value.constructor is Object
util.isArguments = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is Arguments
util.isEmpty = (obj) ->
if util.isNull(obj) then return true
else if util.isString(obj) or util.isArray(obj) then return not obj.length
return false for key of obj when util.hasOwn(obj, key)
return true
util.isFinite = (obj) -> util.isNumber(obj) and obj isnt Infinity and obj isnt -Infinity
util.isNaN = (obj) -> obj isnt obj or not util.isNumber(obj)
util.toArray = (obj) ->
if not obj then return []
if obj.length is null or util.isString(obj) or util.isFunction(obj) or util.isRegExp(obj) or obj is util.GLOBAL then return [obj]
else
n = obj.length
result = []
result[n] = obj[n] while(--n)
return result
util.toNumber = (obj) ->
if util.isNumber(obj) then return obj
if not obj then return 0
if util.isString(obj) then return parseFloat(obj)
if util.isArray(obj) or util.isNaN(obj) then return NaN
Number(obj)
util.toString = (obj) ->
return if obj is null then '' else obj.toString()
String::capitalize = (index = 0) ->
halfResult = @charAt(index).toUpperCase() + @slice(index+1)
if halfResult.length is @length then return halfResult
@slice(0, index) + halfResult
util.Filesystem = ( ->
fsys = {}
inspect = require('util').inspect
assertPath = (path) -> if typeof path isnt 'string' then throw new TypeError('Path must be a string. Received ' + inspect(path))
_format = (sep, pathObject) ->
dir = pathObject.dir or pathObject.root
base = pathObject.base or ((pathObject.name or '') + (pathObject.ext or ''))
if not dir then return base
if dir is pathObject.root then return dir + base
return dir + sep + base
# Provides for path.posix not found in nodejs version 0.10
# Allows posix standard path management, which is prefered in this project
fsys.path = {
resolve: (args...) ->
resolvedPath = ''
resolvedAbsolute = false
cwd = undefined
`for (var i = args.length - 1 i >= -1 && !resolvedAbsolute i--) {
var path;
if(i>=0) path = args[i];
else {
if (cwd === undefined) cwd = process.cwd();
path = cwd;
}
assertPath(path);
if(path.length === 0) continue;
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charCodeAt(0) is 47/*/*/);
}`
resolvedPath = normalizeStringPosix(resolvedPath, not resolvedAbsolute)
if resolvedAbsolute
if resolvedPath.length > 0 then return "/#{resolvedPath}" else return '/'
else if resolvedPath.length > 0 then return resolvedPath else return '.'
normalize: (path) ->
assertPath(path)
if path.length is 0 then return '.'
`const isAbsolute = path.charCodeAt(0) is 47/*/*/;
const trailingSeparator = path.charCodeAt(path.length - 1) is 47/*/*/`
path = normalizeStringPosix(path, !isAbsolute)
if path.length is 0 and not isAbsolute then path = '.'
if path.length is 0 and trailingSeparator then path += '/'
if isAbsolute then return "/#{path}"
return path
isAbsolute: (path) ->
assertPath(path)
return path.length > 0 and path.charCodeAt(0) is 47
join: (args...) ->
if args.length is 0 then return '.'
joined = undefined
for i, arg in args
assertPath(arg)
if joined is undefined then joined = arg else joined += "#{joined}/#{arg}"
if joined is undefined then return '.'
return fsys.path.normalize(joined)
relative: (from, to) ->
assertPath(from)
assertPath(to)
if from is to then return ''
from = fsys.path.resolve(from)
to = fsys.path.resolve(to)
if from is to then return ''
fromStart = 1
break for fromStart in [fromStart..from.length] when from.charCodeAt(fromStart) isnt 47
fromEnd = from.length
fromLen = (fromEnd-fromStart)
toStart = 1
break for toStart in [toStart..to.length] when to.charCodeAt(toStart) isnt 47
toEnd = to.length
toLen = (toEnd-toStart)
length = if fromLen < toLen then fromLen else toLen
lastCommonSep = -1
i = 0
for i in [i..length]
if i is length
if toLen > length
if to.charCodeAt(toStart + i) is 47 then return to.slice(toStart+i+1)
else if i is 0 then to.slice(toStart+i)
else if fromLen > length
if from.charCodeAt(fromStart + i) is 47 then lastCommonSep = i
else if i is 0 then lastCommonSep = 0
break
fromCode = from.charCodeAt(fromStart + i)
toCode = to.charCodeAt(toStart + i)
if fromCode isnt toCode then break
else if fromCode is 47 then lastCommonSep = i
out = ''
for i in [fromStart+lastCommonSep+1..fromEnd]
if i is fromEnd or from.charCodeAt(i) is 47
if out.length is 0 then out += '..' else out += '/..'
if out.length > 0 then return out+to.slice(toStart+lastCommonSep)
else
toStart += lastCommonSep
if to.charCodeAt(toStart) is 47 then ++toStart
return to.slice(toStart)
dirname: (path) ->
assertPath(path)
if path.length is 0 then return '.'
code = path.charCodeAt(0)
hasRoot = code is 47
end = -1
matchedSlash = true
for i in [path.length-1..1]
code = path.charCodeAt(i)
if code is 47
if not matchedSlash
end = i
break
else matchedSlash = false
if end is -1 then return if hasRoot then '/' else '.'
if hasRoot and end is 1 then return '//'
return path.slice(0, end)
basename: (path, ext) ->
if ext isnt undefined and typeof ext isnt 'string' then throw new TypeError('"ext" argument must be a string')
assertPath(path)
start = 0
end = -1
matchedSlash = true
i = undefined
if ext isnt undefined and ext.length > 0 and ext.length <= path.length
if ext.length is path.length and ext is path then return ''
extIdx = ext.length - 1
firstNonSlashEnd = -1
for i in [path.length-1..0]
code = path.charCodeAt(i)
if code is 47
if not matchedSlash
start = i + 1
break
else
if firstNonSlashEnd is -1
matchedSlash = false
firstNonSlashEnd = i + 1
if extIdx >= 0
if code is ext.charCodeAt(extIdx)
if --extIdx is -1 then end = i
else
extIdx = -1
end = firstNonSlashEnd
if start is end then end = firstNonSlashEnd
else if end is -1 then end = path.length
return path.slice(start, end)
else
for i in [path.length-1..0]
if path.charCodeAt(i) is 47
if not matchedSlash
start = i + 1
break
else if end is -1
matchedSlash = false
end = i + 1
if end is -1 then return ''
return path.slice(start, end)
extname: (path) ->
assertPath(path)
startDot = -1
startPart = 0
end = -1
matchedSlash = true
preDotState = 0
for i in [path.length-1..0]
code = path.charCodeAt(i)
if code is 47
if not matchedSlash
startPart = i + 1
break
continue
if end is -1
matchedSlash = false
end = i + 1
if code is 46#.
if startDot is -1 then startDot = i
else if preDotState isnt 1 then preDotState = 1
else if startDot isnt -1 then preDotState = -1
if startDot is -1 or end is -1 or preDotState is 0 or (preDotState is 1 and startDot is end - 1 and startDot is startPart + 1) then return ''
return path.slice(startDot, end)
format: (pathObject) ->
if pathObject is null or typeof pathObject isnt 'object' then throw new TypeError("Parameter 'pathObject' must be an object, not #{typeof pathObject}")
return _format('/', pathObject)
parse: (path) ->
assertPath(path)
ret = { root: '', dir: '', base: '', ext: '', name: '' }
if path.length is 0 then return ret
code = path.charCodeAt(0)
isAbsolute = code is 47
start = undefined
if isAbsolute
ret.root = '/'
start = 1
else start = 0
startDot = -1
startPart = 0
end = -1
matchedSlash = true
i = path.length - 1
preDotState = 0
for i in [path.length-1..start]
code = path.charCodeAt(i)
if code is 47
if not matchedSlash
startPart = i + 1
break
continue
if end is -1
matchedSlash = false
end = i + 1
if code is 46#.
if startDot is -1 then startDot = i
else if preDotState isnt 1 then preDotState = 1
else if startDot isnt -1 then preDotState = -1
if startDot is -1 or end is -1 or (preDotState is 1 and startDot is end - 1 and startDot is startPart + 1)
if end isnt -1
if startPart is 0 and isAbsolute then ret.base = ret.name = path.slice(1, end)
else ret.base = ret.name = path.slice(startPart, end)
else
if startPart is 0 and isAbsolute
ret.name = path.slice(1, startDot)
ret.base = path.slice(1, end)
else
ret.name = path.slice(startPart, startDot)
ret.base = path.slice(startPart, end)
ret.ext = path.slice(startDot, end)
if startPart > 0 then ret.dir = path.slice(0, startPart - 1)
else if isAbsolute then ret.dir = '/'
return ret
sep: '/'
delimiter: ':'
win32: null
posix: null
}
fsys.cwd = -> PlatformShim.getScriptPath(true)
fsys.walk = (dir, finish) ->
results = []
fs.readdir(p.get(), (err, files) ->
if err then return finsh(err)
pending = files.length
if not pending then return finish(null, results)
files.forEach((file) ->
file = fsys.path.resolve(dir, file)
fs.stat(file, (err, stat) ->
if stat and stat.isDirectory() then walk(file, (err, res) ->
results = results.concat(res)
if not --pending then finish(null, results)
)
else
results.push(file)
if not --pending then return finish(null, results)
)
)
)
fsys.readJSONFile = (p) ->
if p.constructor isnt util.Path then p = new fsys.Path(path)
if p.isDirectory() then throw new TypeError("SDP.Util.Filesystem.readJSONFile can not operate on directories")
if p.extname() isnt '.json' then throw new TypeError("SDP.Util.Filesystem.readJSONFile only operates on JSON files")
result = null
fs.readFile(p.get(), (err, data) ->
if err then util.Logger.alert(err)
result = JSON.parse(data)
)
result
fsys.readJSONDirectory = (p, callback) ->
if p.constructor isnt util.Path then p = new fsys.Path(path)
if not p.isDirectory() then throw new TypeError("SDP.Util.Filesystem.readJSONDirectory can not operate on just files")
return fsys.walk(p.get(), (err, files) ->
if err then util.Logger.alert(err)
results = []
files.forEach((file) ->
pa = new fsys.Path(file)
json = fsys.readJSONFile(pa)
if pa.extname() is '.json' then results.push(json)
if util.isFunction(callback) then callback(json)
)
results
)
fsys.registerJSONFile = (p) ->
if p.constructor isnt util.Path then p = new fsys.Path(path)
if p.isDirectory() then throw new TypeError("SDP.Util.Filesystem.registerJSONFile can not operate on directories")
if p.extname() isnt '.json' then throw new TypeError("SDP.Util.Filesystem.registerJSONFile only operates on JSON files")
return util.registerJSONObject(fsys.readJSONFile(p))
fsys.registerJSONDirectory = (p) ->
if p.constructor isnt util.Path then p = new fsys.Path(path)
if not p.isDirectory() then throw new TypeError("SDP.Util.Filesystem.registerJSONDirectory can only operate on directories")
fsys.readJSONDirectory(p, (json) -> util.registerJSONObject(json))
class fsys.Path
constructor: (uri) ->
if util.isObject(uri) then uri = fsys.path.format(uri)
if uri is undefined then uri = fsys.cwd()
fsys.Path.check(uri)
@get = ->
fsys.Path.check(uri)
uri
@check: (uri) ->
if fsys.path.isAbsolute(uri) then throw new TypeError("SDP's Path may not store absolute paths")
if not fsys.path.resolve(uri).startsWith(fsys.cwd()) then throw new TypeError("SDP's Path may not leave the current working directory")
cd: (to) ->
uri = fsys.path.resolve(@get(), to)
fsys.Path.check(uri)
@get = ->
fsys.Path.check(uri)
uri
basename: (ext) ->
fsys.path.basename(@get(), ext)
dirname: ->
fsys.path.dirname(@get())
extname: ->
fsys.path.extname(@get())
parse: ->
fsys.path.parse(@get())
isFile: ->
fs.lstatSync(@get()).isFile()
isDirectory: ->
fs.lstatSync(@get()).isDirectory()
convert: ->
@get()
fsys
)()
util.registerJSONObject = (item) ->
if not util.isString(item.objectType) then throw new TypeError("SDP.Util.registerJSONObject can not work on items that don't contain an objectType field")
func = SDP.Functional["add#{item.objectType.capitalize()}Item"]
if not func
util.Logger.alert("SDP.Util.registerJSONObject could not find the function for objectType #{item.objectType}")
return
func(item)
util.getOverridePositions = (genre, category) ->
genre = genre.replace(/\s/g, "")
category = category.replace(/\s/g, "")
for g, i in SDP.Constants.Genre
if genre is g
if category is null then return [i]
for c, ci in SDP.Constants.ResearchCategory
if c is category then return [i, ci]
break
return undefined
util.fixItemNaming = (item, originalName, fixName) ->
if item[originalName]?
item[fixName] = item[originalName]
item[originalName] = undefined
item
class util.Image
constructor: (@uri) ->
@uri = null if not util.isString(@uri)
exists: ->
if @uri is null then return false
doesExist = true
fs.access(@uri, fs.constants.F_OK, (err) ->
if err then doesExist = false
)
doesExist
class util.Weight
constructor: (w1 = 0.8, w2 = w1, w3 = w2, w4, w5 = w4, w6 = w5) ->
if w1 is true or (not util.isNumber(w1) and not util.isArray(w1)) then @arr = [0.8,0.8,0.8]
else if w1 is false then @arr = [0.8,0.8,0.8,0.8,0.8,0.8]
else
if util.isArray(w1)
if w1.length > 3
w1.push(w1.last()) while w1.length < 6
else
w1.push(w1.last()) while w1.length < 3
@arr = w1
else
@arr = [w1,w2,w3]
if w4 then @arr.push(w4,w5,w6)
@arr[i] = num/100 for num, i in @arr when num > 1
@isGenre = -> @arr.length is 6
@isAudience = -> @arr.length is 3
get: (index) ->
if index is null then return @arr
@arr[index]
convert: ->
new Array(@arr)
class util.Date
START = '1/1/1'
END = '260/12/4'
constructor: (y = 1, m, w) ->
if util.isString(y)
[y,m,w] = m.split('/')
if util.isString(y) then [y,m,w] = m.split(' ')
if y is true then [y,m,w] = END.split('/')
if y is false then [y,m,w] = START.split('/')
if m is undefined then m = y
if w is undefined then w = m
@string = "#{y}/#{m}/#{w}"
convert: ->
new String(@string)
util.Error = ( ->
Error = {
logs: []
}
( ->
update = false
saving = false
Error.save = ->
if not saving
json = JSON.stringify(Error.logs)
saving = true
DataStore.saveToSlotAsync("SDP.Util.Error.logs", json, ->
saving = false
if update
update = false
Error.save()
, (m) -> saving = false )
else update = true
)()
Error.addErrorLog = (level, message, error) ->
if not error then error = {}
Error.logs.push {
date: (new Date()).toISOString()
level: level
msg: message
errorMsg: error.message
stacktrace: e.stack
number: e.number
}
if Error.logs.length > 100 then Error.logs.splice(0, errorLogs.length - 100)
Error.save()
Error
)()
util.Logger = ( ->
utilRequire = require('util')
logger = {
enabled: true
enableAlerts: true
formatter: logger.printf
show: 200
levels: {}
addLevel: (level, weight, sty, prefix = level) ->
if sty.constructor is style.FormattedStyle then sty = sty.getStyle()
logger.levels[level] = {
level: level
prefix: prefix
style: sty
weight: weight
format: (msg...) -> logger.format(level, msg...)
formatWithTime: (msg...) -> logger.formatWithTime(level, msg...)
log: (msg...) -> logger.log(level, msg...)
alert: (msg...) -> logger.alert(level, msg...)
}
if logger[level] is undefined then logger[level] = logger.levels[level].log
if logger["#{level}Alert"] is undefined then logger["#{level}Alert"] = logger.levels[level].alert
setShow: (level) ->
if level.constructor is Object then logger.show = level.weight
else if level.constructor is String then logger.show = logger.levels[level].weight
else logger.show = level
}
logger.addLevel('verbose', 0, { fg: 'blue', bg: 'black' }, 'VERBOSE')
logger.addLevel('debug', 100, { fg: 'blue'}, 'DEBUG')
logger.addLevel('info', 200, { fg: 'green'}, 'INFO')
logger.addLevel('warn', 300, { fg: 'black', bg: 'yellow' }, 'WARN')
logger.addLevel('error', 400, { fg: 'red', bg: 'black' }, 'ERROR')
logger.addLevel('fatal', 500, { fg: 'red', bg: 'black' }, 'FATAL')
stream = process.stderr
Object.defineProperty(logger, 'stream',
set: (newStream) ->
stream = newStream
style.stream = stream
get: -> stream
)
createTimestamp = (d) ->
formatNumbers = (n) -> if (n >= 0 and n < 10) then "0" + n else n + ""
[
[
formatNumbers(d.getFullYear())
formatNumbers(d.getMonth() + 1)
d.getDate()
].join("-")
[
formatNumbers(d.getHours())
formatNumbers(d.getMinutes())
formatNumbers(d.getHours())
].join(":")
].join("|")
logger.printf = {
formatWithTime: (level, msg...) ->
if logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
style.format(level.style, "[#{createTimestamp(new Date())}]#{level.prefix}: #{str.shift().format(msg...)}")
format: (level, msg...) ->
if logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
style.format(level.style, "#{level.prefix}: #{str.shift().format(msg...)}")
log: (level, msg...) ->
if not logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
if logger.enabled and logger.stream and logger.levels[level]?.weight >= logger.show
logger.stream.write(logger.printf.formatWithTime(level, msg))
alert: (level, msg...) ->
if not logger.levels[level]? then return "Level #{level} does not exist"
if logger.enabled and logger.enableAlerts and logger.levels[level]?.weight >= logger.show
string = if msg.length is 1 then msg[0] else str.shift().format(msg...)
PlatformShim.alert(string, logger.levels[level].prefix)
}
logger.format = {
formatWithTime: (level, msg...) ->
if logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
style.format(level.style, "[#{createTimestamp(new Date())}]#{level.prefix}: #{utilRequire.format(msg...)}")
format: (level, msg...) ->
if logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
style.format(level.style, "#{level.prefix}: #{utilRequire.format(msg...)}")
log: (level, msg...) ->
if not logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
if logger.enabled and logger.stream and logger.levels[level]?.weight >= logger.show
logger.stream.write(logger.format.formatWithTime(level, msg))
alert: (level, msg...) ->
if not logger.levels[level]? then return "Level #{level} does not exist"
if logger.enabled and logger.enableAlerts and logger.levels[level]?.weight >= logger.show
string = if msg.length is 1 then msg[0] else utilRequire.format(msg...)
PlatformShim.alert(string, logger.levels[level].prefix)
}
logger.formatWithTime = (level, msg...) ->
logger.formatter.formatWithTime(level, msg...)
logger.format = (level, msg...) ->
logger.formatter.format(level, msg...)
logger.log = (level, msg...) ->
logger.formatter.log(level, msg...)
logger.alert = (level, msg...) ->
logger.formatter.alert(level, msg...)
logger
)()
util.Check = ( ->
Check = {
usePopups: true
}
Check.error = (msg) ->
try throw new Error(msg)
catch e
if Checks.usePopups then util.Logger.errorAlert(msg, e) else util.Logger.error(msg, e)
Error.addErrorLog("MODERROR", msg, e)
Check.audienceWeightings = (w) ->
if not w or w.length < 3 or w.some((v) -> return v < 0 or v > 1)
Check.error('audience weigthing is invalid: %s', w)
return false
return true
Check.genreWeightings = (w) ->
if not w or w.length < 6 or w.some((v) -> return v < 0 or v > 1)
Check.error('genre weigthing is invalid: %s', w)
return false
return true
Check.missionOverrides = (overrides) ->
if overrides.length < 6 or overrides.some((o) -> o.length < 6 or o.some((w) -> w > 1 or w < 0))
Check.error('invalid missionOverrides: %s', w)
return false
return true
Check.date = (date) ->
if date and date.split
v = date.split('/')
if v and v.length is 3 and not v.some((t) -> t < 1) and v[1] <= 12 and v[2] <= 4 then return true
Check.error('date invalid: %s', date)
return false
Check.propertiesPresent = (obj, props) ->
if not obj then return false
if not props then return true
for p in props
if not p or p.length < 1 then continue
if not obj.hasOwnProperty(p)
Check.error('property not set on object: %s', p)
return false
return true
Check.uniqueness = (obj, prop, values, ignoreErr) ->
if values.some((v) -> v[prop] is obj[prop])
if not ignoreErr then Check.error('duplicate value for %s found: %s', prop, obj[prop])
return false
return true
Check
)()
util
)()
# @namespace Constants
#
# The constants of the SPD
SDP.Constants = {
# Categories of development
ResearchCategory: [
'Engine'
'Gameplay'
'Story/Quests'
'Dialogs'
'Level Design'
'AI'
'World Design'
'Graphic'
'Sound'
]
# Audiences to target
Audience: [
'young'
'everyone'
'mature'
]
# Genres to choose for games
Genre: [
'Action'
'Adventure'
'RPG'
'Simulation'
'Strategy'
'Casual'
]
}
# @namespace Functional
#
# Contains the function interface for the SDP
SDP.Functional = {}
# Registers a Research item
#
# @param [ResearchItem] item The item to register
SDP.Functional.addResearchItem = (item) ->
Checks = SDP.Util.Check
unless item.type? then item.type = 'engine'
if item.type is 'engine' and item.engineStart then item.canResearch = -> false
requirments = ['id', 'name', 'category', 'categoryDisplayName']
if item.v? then requirements.push('pointsCost','duration','researchCost','engineCost') else requirements.push('v')
if Checks.propertiesPresent(item, requirements) and Checks.uniqueness(item, 'id', SDP.GDT.Research.getAll())
SDP.GDT.Research.researches.push(item)
Research.engineItems.push(item)
return
SDP.Functional.addStartResearch = (item) ->
item.type = 'start'
SDP.Functional.addResearchItem(item)
SDP.Functional.addBasicResearch = (item) ->
item.type = 'basic'
SDP.Functional.addResearchItem(item)
SDP.Functional.addEngineResearch = (item) ->
item.type = 'engine'
SDP.Functional.addResearchItem(item)
SDP.Functional.addSpecialResearch = (item) ->
item.type = 'special'
SDP.Functional.addResearchItem(item)
# Registers a Platform item
#
# @param [PlatformItem] item The item to register
SDP.Functional.addPlatformItem = (item) ->
Checks = SDP.Util.Check
fix = SDP.Util.fixItemNaming
fix(item, 'licensePrice','licencePrize')
fix(item, 'publishDate', 'published')
fix(item, 'retireDate', 'platformRetireDate')
fix(item, 'devCosts', 'developmentCosts')
fix(item, 'genreWeight', 'genreWeightings')
fix(item, 'audienceWeight', 'audienceWeightings')
fix(item, 'marketPoints', 'marketKeyPoints')
if Checks.propertiesPresent(item, ['id', 'name', 'company', 'startAmount', 'unitsSold', 'licencePrize', 'published', 'platformRetireDate', 'developmentCosts', 'genreWeightings', 'audienceWeightings', 'techLevel', 'baseIconUri', 'imageDates']) and Checks.uniqueness(item, 'id', SDP.GDT.Platform.getAll()) and Checks.audienceWeightings(item.audienceWeightings) and Checks.genreWeightings(item.genreWeightings) and Checks.date(item.published) and Checks.date(item.platformRetireDate)
if item.marketKeyPoints then for point in item.marketKeyPoints
return unless Checks.date(point.date)
###
if Checks.checkUniqueness(item.name, 'name', Companies.getAllCompanies())
SDP.GDT.addCompany(item.name).addPlatform(item)
else
###
SDP.GDT.Platform.platforms.push(item)
if item.events then for event of item.events
GDT.addEvent(event)
return
# Registers a Topic item
#
# @param [TopicItem] item The item to register
SDP.Functional.addTopicItem = (item) ->
Checks = SDP.Util.Check
fix = SDP.Util.fixItemNaming
fix(item, 'genreWeight', 'genreWeightings')
fix(item, 'audienceWeight', 'audienceWeightings')
fix(item, 'overrides', 'missionOverrides')
if Checks.propertiesPresent(t, ['name', 'id', 'genreWeightings', 'audienceWeightings']) and Checks.audienceWeightings(t.audienceWeightings) and Checks.genreWeightings(t.genreWeightings) and Checks.uniqueness(t, 'id', SDP.GDT.Topic.getAll(), true)
SDP.GDT.Topic.topics.push(item)
return
SDP.Functional.addTopicItems = (list...) ->
if list.length is 1
list = list[0]
if not SDP.Util.isArray(list) then return SDP.Functional.addTopicItem(list)
SDP.Functional.addTopicItem(item) for item in list
# Registers a Research Project item
#
# @param [ResearchProjectItem] item The item to register
SDP.Functional.addResearchProjectItem = (item) ->
Checks = SDP.Util.Check
unless item.canResearch? then item.canResearch = ((company)->true)
if Checks.propertiesPresent(item, ['id', 'name', 'pointsCost', 'iconUri', 'description', 'targetZone']) and Checks.uniqueness(item, 'id', SDP.GDT.ResearchProject.getAll())
SDP.GDT.ResearchProject.projects.push(item)
return
SDP.Functional.addResearchProject = (item) -> SDP.Functional.addResearchProjectItem(item)
# Registers a Training item
#
# @param [TrainingItem] item The item to register
SDP.Functional.addTrainingItem = (item) ->
Checks = SDP.Util.Check
unless item.canSee? and item.canUse? then item.canSee = (staff, company) -> true
if Checks.propertiesPresent(item, ['id', 'name', 'pointsCost', 'duration', 'category', 'categoryDisplayName']) and Checks.uniqueness(item, 'id', SDP.GDT.Training.getAll())
SDP.GDT.Training.trainings.push(item)
return
# Registers a Contract item
#
# @param [ContractItem] item The item to register
SDP.Functional.addContractItem = (item) ->
Checks = SDP.Util.Check
if Checks.propertiesPresent(item, ['id', 'name', 'description', 'tF', 'dF']) and Checks.uniqueness(item, 'id', SDP.GDT.Contract.getAll())
SDP.GDT.Contract.contracts.push(item)
return
# Registers a Publisher item
#
# @param [PublisherItem] item The item to register
SDP.Functional.addPublisherItem = (item) ->
Checks = SDP.Util.Check
if Checks.propertiesPresent(item, ['id', 'name']) and Checks.uniqueness(item, 'id', SDP.GDT.Publisher.getAll())
SDP.GDT.Publisher.publishers.push(item)
return
# Registers a Reviewer item
#
# @param [ReviewerItem] item The item to register
###
SDP.Functional.addReviewerItem = (item) ->
Checks = SDP.Util.Check
if Checks.propertiesPresent(item, ['id', 'name']) and Checks.uniqueness(item, 'id', SDP.GDT.Review.getAll())
SDP.GDT.Review.reviewer.push(item)
return
###
SDP.Functional.addEvent = (event) ->
Checks = SDP.Util.Check
unless Checks.propertiesPresent(event, ['id']) and (event.notification or event.getNotification) then return
unless Checks.checkUniqueness(event, 'id', GDT.Event.getAll()) then return
# hacks in runningCompany to events because event.complete does not supply one, and overriding the UI system is a bit much for now
oldTrigger = event.trigger
event.trigger = (company) ->
result = oldTrigger(company)
@runningCompany = company if result and event.complete?
result
GDT.Event.events.push(event)
# Adds a notification to the triggering queue
#
# @param [NotificationItem] item The item to queue
SDP.Functional.addNotificationToQueue = (item) ->
if SDP.Util.isString(item)
item = item.split('\n')
if item.length is 1 then item = item[0].split(':')
if item.length is 1 then item = item[0].split(';')
item.forEach((e, i) -> item[i] = e.trim())
item = {
header: item[0]
text: item[1]
buttonText: item[2]
}
item.header = '?' unless item.header?
item.text = '?' unless item.text?
if not item instanceof Notification
item = new Notification {
header: item.header
text: item.text
buttonText: item.buttonText
weeksUntilFired: item.weeksUntilFired
image: item.image
options: item.options.slice(0, 3)
sourceId: item.sourceId
}
if GameManager?.company?.notifications? then GameManager.company.notifications.push(item) else SDP.GDT.Notification.queue.push(item)
SDP.Class = (
classes = {}
convertClasses = (classObj) ->
switch classObj.constructor
when SDP.Util.Date, SDP.Util.Weight, SDP.Util.Filesystem.Path then return classObj.convert()
when Array
classObj[i] = convertClasses(classObj[i]) for i of classObj
return classObj
else return classObj
class Base
constructor: (args...) ->
if SDP.Util.isObject(args[0])
@[arg] = args[0][arg] for arg in args[0] when args[0].hasOwnProperty(arg)
@wasNativeObject = true
else @wasNativeObject = false
@id ?= @name
class classes.Research extends Base
constructor: (@name, @type, @category, @categoryDisplayName = @category, @id) ->
super
convert: ->
item = {
name: @name
id: @id
type: @type
v: @v
pointsCost: @pointsCost
duration: @duration
researchCost: @researchCost
devCost: @devCost
engineCost: @engineCost
enginePoints: @enginePoints
category: @category
categoryDisplayName: @categoryDisplayName
group: @group
consolePart: @consolePart
engineStart: @engineStart
canUse: if @canUse? then @canUse.bind(item) else undefined
canResearch: if @canResearch? then @canResearch.bind(item) else undefined
}
class classes.Platform extends Base
constructor: (@name, @company, @id = @name) ->
super
@startAmount ?= 0
@unitsSold ?= 0
@audienceWeight ?= new SDP.Util.Weight(true)
@genreWeight ?= new SDP.Util.Weight(false)
@licensePrice ?= 0
@publishDate ?= new SDP.Util.Date(false)
@retireDate ?= new SDP.Util.Date(true)
@devCost ?= 0
@techLevel ?= 0
@iconUri ?= new SDP.Util.Filesystem.Path()
convert: ->
{
name:<NAME> @<NAME>
id: @id
company: @company
startAmount: @startAmount
unitsSold: @unitsSold
licensePrice: @licensePrice
publishDate: convertClasses(@publishDate)
retireDate: convertClasses(@retireDate)
genreWeight: convertClasses(@genreWeight)
audienceWeight: convertClasses(@audienceWeight)
techLevel: @techLevel
iconUri: convertClasses(@iconUri)
imageDates: convertClasses(@imageDates)
marketPoints: convertClasses(@marketPoints)
}
class classes.Topic extends Base
BASE_OVERRIDE = [0,0,0,0,0,0,0,0,0]
constructor: (@name, @id) ->
super
@audienceWeight ?= new SDP.Util.Weight(true)
@genreWeight ?= new SDP.Util.Weight(false)
if not @overrides? or not SDP.Util.isArray(@overrides)
@overrides = [BASE_OVERRIDE,BASE_OVERRIDE,BASE_OVERRIDE,BASE_OVERRIDE,BASE_OVERRIDE,BASE_OVERRIDE]
@overrides.push(BASE_OVERRIDE) while @overrides.length < 6
o.push(0) for o in @overrides when o.length < 9
setOverride: (genreName, catName, value) ->
if SDP.Util.isArray(genreName)
@overrides = genreName
return @
if SDP.Util.isArray(catName) then value = catName
catOrNull = if value isnt catName and (SDP.Util.isString(catName) or SDP.Util.isInteger(catName)) then catName else null
positions = SDP.Util.getOverridePositions(genreName, catOrNull)
if value is catName
@overrides[positions[0]] = value
else
@overrides[positions[0]][positions[1]] = value
@
convert: ->
{
name:<NAME> @<NAME>
id: @id
genreWeight: convertClasses(@genreWeight)
audienceWeight: convertClasses(@audienceWeight)
overrides: @overrides
}
class classes.ResearchProject extends Base
constructor: (@name, @description, @id) ->
super
@pointsCost ?= 0
@iconUri ?= new SDP.Util.Filesystem.Path()
@targetZone ?= 2
convert: ->
item = {
name:<NAME> @<NAME>
id: @id
description: @description
pointsCost: @pointsCost
iconUri: convertClasses(@iconUri)
targetZone: @targetZone
repeatable: @repeatable
canResearch: if @canResearch? then @canResearch.bind(item) else undefined
complete: if @complete? then @complete.bind(item) else undefined
cancel: if @cancel? then @cancel.bind(item) else undefined
}
class classes.Training extends Base
constructor: (@name, @category, @categoryDisplayName = @category, @id) ->
super
@pointsCost ?= 0
@duration ?= 0
convert: ->
item = {
name:<NAME> @<NAME>
id: @id
cost: @cost
pointsCost: @pointsCost
category: @category
categoryDisplayName: @categoryDisplayName
canSee: if @canSee? then @canSee.bind(item) else undefined
canUse: if @canUse? then @canUse.bind(item) else undefined
tick: if @tick? then @tick.bind(item) else undefined
complete: if @complete? then @complete.bind(item) else undefined
}
class classes.Contract extends Base
constructor: (@name, @size, @description, @id) ->
super
@tF ?= 0
@dF ?= 0
convert:
item = {
name:<NAME> @<NAME>
id: @id
size: @size
description: @description
tF: @tF
dF: @dF
card: @card
generateCard: if @generateCard? then @generateCard.bind(item) else undefined
rF: @rF
}
class classes.Publisher extends Base
constructor: (@<NAME>, @id) ->
super
convert: ->
item = {
name:<NAME> @<NAME>
id: @id
card: @card
generateCard: if @generateCard? then @generateCard.bind(item) else undefined
}
class classes.Event extends Base
constructor: (@id, @isRandomEvent) ->
super
@trigger ?= (company) -> false
convert: ->
item = {
id: @id
isRandomEvent: @isRandomEvent
notification: @notification
trigger: @tigger.bind(item)
getNotification: if @getNotification? then @getNotification.bind(item) else undefined
complete: if @complete? then @complete.bind(item) else undefined
}
)()
SDP.GDT = ( ->
GDT = {}
GDT.Company = {
companies: {}
clientUid: undefined
addCompany: (company) ->
if not company.uid then company.uid = GameManager.getGUID()
GDT.Company.companies[company.uid] = company
if company is GameManager.company then clientUid = company.uid
containsCompany: (company) -> companies[company.uid or company]?
getCompanies: -> GDT.Company.companies.slice()
getClientCompany: -> GDT.Company.companies[GDT.Company.clientUid]
getPlatformsFor: (company, includeInactive) ->
if includeInactive then return GDT.Platform.getAll().concat(company.licencedPlatforms)
company.availablePlatforms.concat(company.licencedPlatforms)
getByUid: (uid) -> GDT.Company.companes[uid]
}
Platforms.getPlatforms = GDT.Company.getPlatformsFor
oldResearchGetAll = Research.getAllItems
GDT.Research = {
researches: oldResearchGetAll().forEach((r) ->
switch r.category
when 'General' then r.type = 'basic'
when 'Game Design', 'Project Management', 'Technology', 'Publishing' then r.type = 'special'
else r.type = 'engine'
if r.id is 'Text Based' or r.id is '2D Graphics V1' or r.id is 'Basic Sound' then r.type = 'start'
if r.id is '2D Graphics V2' or r.id is 'Linear story' or r.id is 'Savegame' then r.engineStart = true
)
# start research is accessible without an engine
# basic research are researches that do not pertain specifically to engines
# engine research are researches that do pertain to engines
# special research is basically the misc, where it would fit nowhere else, for example Marketing
types: ['start', 'basic', 'engine', 'special']
getAll: -> GDT.Research.researches.concat(oldResearchGetAll().except(GDT.Research.researches))
getAvailable: (company, engine) -> GDT.Research.getAll().filter((r) ->
if r.type is 'start' then return true
if engine and engine.parts.first((e) -> e.id is r.id)? then return true
if r.enginePoints is 0 and company.researchCompleted.indexOf(r) isnt -1 then return true
if company.specialItems.indexOf(r) isnt -1 then return true
false
)
getAvailableEngineParts: (company) ->
if company.canDevelopEngine() then return GDT.Research.getAll().filter((r) ->
if r.engineStart then return true
if r.type is 'start' or r.type is 'basic' then return false
Research.getEnginePoints(r) isnt 0 and (Research.getEngineCost(r) isnt 0 and company.researchCompleted.indexOf(r) isnt -1)
)
[]
addSpecialItem: (company, idOrObj) -> company.specialItems.push(if SDP.Util.isString(idOrObj) then GDT.Researches.getAll().first((r) -> r.id is idOrObj) else idOrObj)
removeSpecialItem: (company, idOrObj) -> company.specialItems.remove(if SDP.Util.isString(idOrObj) then GDT.Researches.getAll().first((r) -> r.id is idOrObj) else idOrObj)
getById: (id) -> GDT.Research.getAll().first((r) -> r.id is id)
}
Research.getAllItems = GDT.Research.getAll
( ->
oldResearchPointsCost = Research.getPointsCost
Research.getPointsCost = (r) ->
if r.pointsCost then return r.pointsCost
return oldResearchPointsCost(r)
oldResearchDuration = Research.getDuration
Research.getDuration = (r) ->
if r.duration then return r.duration
return oldResearchDuration(r)
oldResearchDevCost = Research.getDevCost
Research.getDevCost = (r, game) ->
if r.devCost
value = r.devCost
if game
value *= General.getGameSizeDurationFactor(game.gameSize) * General.getMultiPlatformCostFactor(game)
value = Math.floor(value / 1e3) * 1e3
return value
return oldResearchDevCost(r, game)
oldResearchResearchCost = Research.getResearchCost
Research.getResearchCost = (r) ->
if r.researchCost then r.researchCost
return oldResearchResearchCost(r)
oldResearchEngineCost = Research.getEngineCost
Research.getEngineCost = (r) ->
if r.engineCost then return r.engineCost
return oldResearchEngineCost(r)
)()
GameManager.getAvailableGameFeatures = GDT.Research.getAvailable
General.getAvailableEngineParts = GDT.Research.getAvailableEngineParts
( ->
oldPlatformImage = Platforms.getPlatformImage
GDT.Platform = {
platforms: Platforms.allPlatforms
getAll: -> GDT.Platform.platforms.slice()
getAvailable: (company) ->
GDT.Company.getPlatformsFor(company).filter((p) ->
Platforms.getRetireDate(p) > Math.floor(company.currentWeek) and not p.isCustom or p.isCustom is true and (company.currentWeek > General.getWeekFromDateString(p.published) and not p.soldOut)
)
getImage: (platform, week) ->
if platform.id is 'PC' then return oldPlatformImage(platform, week)
if not platform.imageDates then return platform.iconUri
else if week
image = "{0}/{1}-{2}.png".format(baseUri, platform.id, String(i+1)) for date, i in platform.imageDates when General.getWeekFromDateString(date) <= week and i isnt 0
if not image then return "{0}/{1}.png".format(baseUri, platform.id) else return image
getById: (id) -> GDT.Platform.getAll().first((p) -> p.id is id)
}
Platforms.getPlatformsOnMarket = GDT.Platform.getAvailable
Platforms.getPlatformImage = GDT.Platform.getImage
)()
GDT.Topic = {
topics: Topics.topics
_topicBackup: JSON.parse(JSON.stringify(GDT.Topic.topics))
getAll: -> GDT.Topic.topics.slice()
getById: (id) -> GDT.Topic.getAll().first((t) -> t.id is id )
reset: (id) ->
index = GDT.Topic.topics.indexOf(GDT.Topic.getById(id))
if index isnt -1 then GDT.Topic.topics[index] = JSON.parse(JSON.stringify(GDT.Topic._topicBackup[index]))
}
GDT.ResearchProject = {
projects: Research.bigProjects
getAll: -> GDT.ResearchProject.projects.slice()
getAvailable: (company, zone) ->
GDT.ResearchProject.getAll().filter((p) ->
p.targetZone is zone and p.canResearch(company)
)
getById: (id) -> GDT.ResearchProject.getAll().first((r) -> r.id is id)
}
General.getAvailableProjects = GDT.ResearchProject.getAvailable
GDT.Training = {
trainings: Training.getAllTrainings()
getAll: ->
results = []
for item in GDT.Training.trainings.slice()
if item.id? and (item.pointsCost? and item.duration?)
item.isTraining = true
results.push(item)
results
getAvailable: (staff) ->
results = []
for t in GDT.Training.getAll()
results.push(t) if (t.canSee and t.canSee(staff, staff.company) or not t.canUse?) or (not t.canSee and t.canUse(staff, staff.company))
results
getById: (id) -> GDT.Training.getAll().first((t) -> t.id is id)
}
Training.getAllTrainings = GDT.Training.getAll
Training.getAvailableTraining = GDT.Training.getAvailable
# To prevent namespace clutter, stuck the contract stuff in a seperate function block
( ->
`var smallContracts = [{
name: "Logo Animation".localize("heading"),
description: "Create an animation for an existing logo.".localize(),
tF: 1,
dF: 2.5,
rF: 1.5
}, {
name: "Character Design".localize("heading"),
description: "Design some game characters.".localize(),
tF: 1,
dF: 4.5,
rF: 1.5
}, {
name: "Playtest".localize("heading"),
description: "Help to playtest a game.".localize(),
tF: 1,
dF: 1,
rF: 1.5
}, {
name: "Game Backdrops".localize("heading"),
description: "Design some simple background graphics for a game.".localize(),
tF: 1,
dF: 2,
rF: 1.5
}, {
name: "Setup Computers".localize("heading"),
description: "Install Mirconoft BOSS on computers".localize(),
tF: 2,
dF: 0.4
}, {
name: "Debug program".localize("heading"),
description: "Help debugging a convoluted BASE program.".localize(),
tF: 2,
dF: 0.2
}, {
name: "Spritesheet Software".localize("heading"),
description: "Our staff needs to be taught how to use these modern technologies.".localize(),
tF: 3,
dF: 2
}, {
name: "Library Software".localize("heading"),
description: "Develop a simple library management system".localize(),
tF: 5,
dF: 1
}];
var mediumContracts = [{
name: "Usability Study".localize("heading"),
description: "Perform a detailed usability study.".localize(),
tF: 5,
dF: 6.5
}, {
name: "Review Game Concept".localize("heading"),
description: "Review a game concept using your expertise.".localize(),
tF: 3,
dF: 8,
rF: 1.5
}, {
name: "Game Art".localize("heading"),
description: "Help out on a project with some game art".localize(),
tF: 5,
dF: 6,
rF: 1.5
}, {
name: "Clean up database".localize("heading"),
description: "Should one table really have 200 columns? Probably not.".localize(),
tF: 5,
dF: 1
}, {
name: "Accounting Software".localize("heading"),
description: "Develop a simple accounting software. Are those ever simple?".localize(),
tF: 5,
dF: 1
}, {
name: "Time Tracking".localize("heading"),
description: "Design and develop a time tracking system.".localize(),
tF: 3,
dF: 1
}, {
name: "Design a board game".localize("heading"),
description: "Let's see how your skills translate to traditional games.".localize(),
dF: 5,
tF: 0.2,
rF: 2
}, {
name: "Horoscope Generator".localize("heading"),
description: "Making up horoscopes is hard work. We want it automated.".localize(),
dF: 5,
tF: 1
}, {
name: "Character Dialogues".localize("heading"),
description: "Improve our character dialogues.".localize(),
dF: 5,
tF: 1,
rF: 1.4
}, {
name: "Futuristic Application".localize("heading"),
description: "We need an application that looks futuristic for a movie.".localize(),
dF: 3,
tF: 2,
rF: 1.5
}, {
name: "Vacuum Robot".localize("heading"),
description: "Create a revolutionary AI for a vacuum robot".localize(),
tF: 2,
dF: 1.4
}, {
name: "Website".localize("heading"),
description: "We just heard of this thing called internet. We want to have one.".localize(),
tF: 2,
dF: 1.3
}];
var largeContracts = [{
name: "Game Port".localize("heading"),
description: "Port a game to a different platform.".localize(),
tF: 3.2,
dF: 1.7,
rF: 1.2
}, {
name: "Cut Scenes".localize("heading"),
description: "Deliver professional cut scenes for a game.".localize(),
tF: 1,
dF: 1,
rF: 1.5
}, {
name: "Space Shuttle".localize("heading"),
description: "Deliver part of the space shuttle control software.".localize(),
tF: 3,
dF: 2
}, {
name: "Alien Search".localize("heading"),
description: "Optimize our search for alien life forms using advanced AI techniques.".localize(),
tF: 3,
dF: 1.8,
rF: 1.3
}, {
name: "Movies".localize("heading"),
description: "We need your skills in our latest blockbuster production.".localize(),
tF: 1,
dF: 1,
rF: 1.5
}]`
GDT.Contract = {
contracts: []
getAll: -> GDT.Contract.contracts.slice()
getAvailable: (company) ->
results = []
for c in GDT.Contract.getAll().filter((contract) -> not contract.isAvailable? or contract.isAvailable(company))
results.push(c)
results
getSettings: (company, size) ->
key = "<KEY>
settings = company.flags[key]
if not settings
settings = {id:key}
company.flags[key] = settings
settings
getSeed: (settings) ->
newSeed = ->
settings.seed = Math.floor(Math.random() * 65535);
settings.expireBy = GameManager.gameTime + 24 * GameManager.SECONDS_PER_WEEK * 1e3;
settings.contractsDone = []
if not settings.seed
newSeed()
settings.intialSettings = true
else if settings.expireBy <= GameManager.gameTime
newSeed()
settings.intialSettings = false
settings.seed
createFromTemplate: (company, template, random) ->
item = if template.generateCard? then template.generateCard(company, random) else template.card
r = random.random()
if random.random > 0.8 then r+= random.random()
t = undefined
d = undefined
pay = undefined
weeks = undefined
penalty = undefined
if item.techPoints then t = item.techPoints
if item.designPoints then d = item.designPoints
if item.payment then pay = item.payment
if item.weeks then weeks = item.weeks
if item.penalty then penalty = item.penalty
unless t and d and pay and weeks and penalty
minPoints = undefined
tF = template.tF or item.tF
dF = template.dF or item.dF
unless t and d and not item.minPoints then minPoints = item.minPoints else
minPoints = switch template.size
when 'small' then 11
when 'medium' then 30
when 'large' then 100
minPoints += 6 if minPoints is 12 and company.staff.length > 2
minPoints += minPoints * (company.getCurrentDate().year / 25)
points = minPoints + minPoints * r
pointPart = points / (dF + tF)
unless d
d = pointPart * dF
d += d * 0.2 * random.random() * random.randomSign()
d = Math.floor(d)
unless t
t = pointPart * tF
t += t * 0.2 * random.random() * random.randomSign()
t = Math.floor(t)
unless pay then pay = Math.floor(points*1e3/1e3) * 1e3
unless weeks then (weeks = if template.size is small then Math.floor(3 + 3 * random.random()) else Math.floor(3 + 7 * random.random()))
unless penalty then penalty = Math.floor((pay * 0.2 + pay * 0.3 * random.random())/1e3) * 1e3
contractObject = {
name: template.name
description: template.description
id: 'genericContracts'
requiredD: d
requiredT: t
spawnedD: 0
spawnedT: 0
payment: pay
penalty: -penalty
weeksToFinish: weeks
rF: template.rF
isGeneric: true
size: template.size
complete: if template.complete? then template.complete.bind(contractObject) else undefined
}
generate: (company, size, max) ->
settings = GDT.Contract.getSettings(company, size)
random = new MersenneTwister(GDT.Contract.getSeed(settings))
count = Math.max(max - 1, Math.floor(random.random() * max))
results = []
set = GDT.Contract.getAvailable(company).filter((e) -> e.size is size)
if settings.initialSettings then count = Math.max(1, count)
i = 0
while i < count and set.length > 0
item = set.pickRandom(random)
set.remove(item)
contractInstance = GDT.Contract.createFromTemplate(company, item, random)
contractInstance.index = i
if settings.contractsDone and settings.contractsDone.indexOf(i) isnt -1
contract.skip = true
contracts.push(contract)
i++
contracts
getList: (company) ->
settings = GDT.Contract.getSettings(company, 'small')
results = GDT.Contract.generate(company, 'small', 4)
if company.flags.mediumContractsEnabled then results.addRange(GDT.Contract.generate(company, 'medium', 3))
if company.flags.largeContractsEnabled then results.addRange(GDT.Contract.generate(company, 'large', 2))
results.shuffle(new MersenneTwister(GDT.Contract.getSeed(settings))).filter((c) -> not c.skip)
getById: (id) -> GDT.Contract.getAll().first((c) -> c.id is id)
}
generateConvertContracts = (type) ->
(e) ->
e.size = type
e.id = e.name.replace(' ', '')
smallContracts.forEach(generateConvertContracts('small'))
mediumContracts.forEach(generateConvertContracts('medium'))
largeContracts.forEach(generateConvertContracts('large'))
GDT.Contract.contracts.addRange(smallContracts)
GDT.Contract.contracts.addRange(mediumContracts)
GDT.Contract.contracts.addRange(largeContracts)
ProjectContracts.generateContracts.getContract = GDT.Contract.getList
oldContractsComplete = ProjectContracts.genericContracts.complete
ProjectContracts.genericContracts.complete = (company, success, data) ->
contract.complete?()
oldContractsComplete(company, success, data)
)()
( ->
`var publishers = [{
id: "ActiveVisionaries",
name: "Active Visionaries"
}, {
id: "ea",
name: "Electronic Mass Productions"
}, {
id: "RockvilleSoftworks",
name: "Rockville Softworks"
}, {
id: "BlueBitGames",
name: "Blue Bit Games"
}, {
id: "CapeCom",
name: "CapeCom"
}, {
id: "Codemeisters",
name: "Codemeisters"
}, {
id: "DeepPlatinum",
name: "Deep Platinum"
}, {
id: "InfroGames",
name: "InfroGames"
}, {
id: "LoWoodProductions",
name: "LoWood Productions"
}, {
id: "TGQ",
name: "TGQ"
}, {
id: "\u00dcberSoft",
name: "\u00dcberSoft"
}]`
GDT.Publisher = {
publishers: publishers.slice()
getAll: -> GDT.Publisher.publishers.slice()
getAvailable: (company) ->
results = []
for p in GDT.Publisher.getAll().filter((publisher) -> not publisher.isAvailable? or publisher.isAvailable(company))
results.push(p)
results
generate: (company, max) ->
settings = GDT.Contract.getSettings(company, 'publisher')
seed = GDT.Contract.getSeed(settings)
random = new MersenneTwister(seed)
count = Math.max(max - 1, Math.floor(random.random() * max))
results = []
if settings.seed isnt seed
settings.topics = undefined
settings.researchedTopics = undefined
settings.excludes = undefined
settings.platforms = undefined
if not settings.topics or (not settings.researchedTopics or not settings.platforms)
topics = company.topics.slice()
topics.addRange(General.getTopicsAvailableForResearch(company))
settings.topics = topics.map((t) ->
t.id
)
researchedTopics = company.topics.map((t) ->
t.id
)
settings.researchedTopics = researchedTopics
platforms =
Platforms.getPlatformsOnMarket(company).filter((p) ->
not p.isCustom and Platforms.doesPlatformSupportGameSize(p, "medium")
)
settings.platforms = platforms.map((p) ->
p.id
)
settings.excludes = []
lastGame = company.gameLog.last()
if lastGame
settings.excludes.push {
genre: lastGame.genre.id
topic: lastGame.topic.id
}
else
topics = settings.topics.map((id) ->
Topics.topics.first((t) ->
t.id is id
)
)
researchedTopics = settings.researchedTopics.map((id) ->
Topics.topics.first((t) ->
t.id is id
)
)
allPlatforms = Platforms.getPlatforms(company, true);
platforms = settings.platforms.map((id) ->
allPlatforms.first((p) ->
p.id is id
)
)
excludes = settings.excludes.slice()
count = Math.max(max - 1, Math.floor(random.random() * max))
if settings.initialSetting then count = Math.max(1, count)
sizes = ['medium']
if company.canDevelopLargeGames() then sizes.addRange(["large", "large", "large"])
audiences = ["young", "everyone", "mature"]
sizeBasePay = { medium: 15e4, large: 15e5 / 2 }
for i in [0..count]
publisher = GDT.Publisher.getAvailable(company).pickRandom(random)
if publisher.generateCard or publisher.card
item = if publisher.generateCard? then publisher.generateCard(company) else publisher.card
if item and (item.size is 'small' or company["canDevelop#{item.size.capitalize()}Games"]?())
topic = item.topic
genre = item.genre
platform = item.platform
name = "#{if topic then topic.name else 'Any Topic'.localize()} / #{if genre then genre.name else 'Any Genre'.localize()}"
results.push contract = {
id: 'publisherContracts'
refNumber: Math.floor(Math.random() * 65535)
type: 'gameContract'
name: name
description: "Publisher: #{publisher.name}"
publisher: publisher.name
publisherObject: publisher
topic: if topic then topic.id else topic
genre: if genre then genre.id else genre
platform: if platform.id then platform.id else platform
gameSize: item.size,
gameAudience: item.audience,
minScore: item.minScore,
payment: item.pay,
penalty: item.penalty,
royaltyRate: item.royaltyRate
complete: if item.complete? then item.complete.bind(contract) else if publisher.complete then publisher.complete.bind(contract) else undefined
}
continue
diffculty = 0
topic = undefined
genre = undefined
if random.random() <= 0.7
genre = General.getAvailableGenres(company).pickRandom(random)
diffculty += 0.1
if random.random() <= 0.7
`do {
if (random.random() <= 0.7)
topic = topics.except(researchedTopics).pickRandom(random);
else
topic = topics.pickRandom(random);
if (topic === undefined)
break
} while (excludes.some(function (e) {
return (genre === undefined || e.genre === genre.id) && e.topic === topic.id
}))`
if topic? then diffculty += 0.1
if genre or topic then excludes.push {
genre: if genre then genre.id else undefined
topic: if topic then topic.id else undefined
}
platform = undefined
if random.random() <= 0.7 then platform = platforms.pickRandom(random)
audience = undefined
if company.canSetTargetAudience() and random.random() <= 0.2 then audience = audiences.pickRandom(random)
difficulty += 0.8 * random.random()
minScore = 4 + Math.floor(5 * difficulty)
size = undefined
`do
size = sizes.pickRandom(random);
while (platform != undefined && !Platforms.doesPlatformSupportGameSize(platform, size))`
basePay = sizeBasePay[size]
pay = Math.max(1, Math.floor((basePay * (minScore / 10))/5e3)) * 5e3
penalty = Math.floor((pay * 1.2 + pay * 1.8 * random.random())/5e3) * 5e3
pubObject = undefined
puName = undefined
if platform and (platform.company and random.random() <= 0.2) then pubName = platform.company
else
pubObject = publishers.pickRandom(random)
pubName = pubObject.name
royaltyRate = Math.floor(7 + 8 * difficulty) / 100
name = "#{if topic then topic.name else 'Any Topic'.localize()} / #{if genre then genre.name else 'Any Genre'.localize()}"
if not platform or Platforms.getPlatformsOnMarket(company).first((p) -> p.id is platform.id)
results.push contract = {
id: "publisherContracts"
refNumber: Math.floor(Math.random() * 65535)
type: "gameContract"
name: name
description: "Publisher: {0}".localize().format(pubName)
publisher: pubName
publisherObject: pubObject
topic: if topic then topic.id else topic
genre: if genre then genre.id else genre
platform: if platform then platform.id else undefined
gameSize: size
gameAudience: audience
minScore: minScore
payment: pay
penalty: penalty
royaltyRate: royaltyRate
complete: if pubObject.complete? then pubObject.complete.bind(contract) else undefined
}
else
count++
results
getById: (id) -> GDT.Publisher.getAll().first((p) -> p.id is id)
}
ProjectContracts.publisherContracts.getContract = (company) ->
GDT.Publisher.generate(company, 5).filter((p) -> not p.skip )
oldPublisherComplete = ProjectContracts.publisherContracts.complete
ProjectContracts.publisherContracts.complete = (company, success, data) ->
data.complete?(company, success, data)
oldPublisherComplete(company, success, data)
)()
( ->
reviewers = ["Star Games", "Informed Gamer", "Game Hero", "All Games"]
GDT.Review = {
reviewers: reviewers.slice()
messages: []
getAll: -> GDT.Review.reviewers.slice()
getAvailable: (company) ->
results = []
for r in GDT.Review.getAll().filter((reviewer) -> not reviewer.isAvailable? or reviewer.isAvailable(company))
results.push(r)
results
getAllMessages: -> GDT.Review.messages.slice()
pickReviewers: (count) ->
results = []
reviewers = GDT.Review.getAvailable()
r = undefined
for i in [0..count]
r = reviewers.pickRandom()
results.push(r)
reviewers.remove()
results
reviewLatestFor: (company) ->
negativeMessages = []
positiveMessages = []
mmoFactor = 1
game = company.currentGame
GDT.fire(GameManager, GDT.eventKeys.gameplay.beforeGameReview, {
company : company,
game : game
})
if game.flags.mmo then mmoFactor = 2
sequelTo = undefined
if game.sequelTo
sequelTo = company.getGameById(game.sequelTo)
if sequelTo.releaseWeek > company.currentWeek - 40 then game.flags.sequelsTooClose = true
tp = game.technologyPoints
dp = game.designPoints
generalModifier = 0
goodDecisions = 0
badDecisions = 0
if dp + tp >= 30
goldenRatio = GameGenre.getGoldenRatio(game.genre, game.secondGenre)
difference = dp * goldenRatio - tp
percentDifference = 0
percentDifference = if (tp > dp) then Math.abs(difference / tp * 100) else percentDifference = Math.abs(difference / dp * 100)
"goldenRatio percentDifference: {0}".format(percentDifference).log()
if Math.abs(percentDifference) <= 25
generalModifier += 0.1
goodDecisions += 1
positiveMessages.push("They achieved a great balance between technology and design.".localize())
else if Math.abs(percentDifference) > 50
generalModifier -= 0.1
if difference < 0 then negativeMessages.push("They should focus more on design.".localize())
else negativeMessages.push("They should focus more on technology.".localize())
executedDevMissions = game.featureLog.filter((m) -> m.missionType is "mission" )
optimalMissionFocus = executedDevMissions.filter((m) ->
percentage = m.duration / General.getGameSizeDurationFactor(game.gameSize) / General.getMultiPlatformDurationFactor(game) / (Missions.BASE_DURATION * 3)
Missions.getGenreWeighting(m, game) >= 0.9 and percentage >= 0.4
)
if optimalMissionFocus.length >= 2
generalModifier += 0.2
goodDecisions += optimalMissionFocus.length
positiveMessages.push("Their focus on {0} served this game very well.".localize().format(optimalMissionFocus.map((m) -> Missions.getMissionWithId(m.id)).pickRandom().name))
else if optimalMissionFocus.length is 1
generalModifier += 0.1
goodDecisions += 1
else
generalModifier -= 0.15 * mmoFactor
nonOptimalMissions = executedDevMissions.filter (m) ->
percentage = m.duration / General.getGameSizeDurationFactor(game.gameSize) / General.getMultiPlatformDurationFactor(game) / (Missions.BASE_DURATION * 3)
Missions.getGenreWeighting(m, game) < 0.8 and percentage >= 0.4
if nonOptimalMissions.length is 2
mission = Missions.getMissionWithId(nonOptimalMissions.pickRandom().id)
generalModifier -= 0.2 * mmoFactor
badDecisions += nonOptimalMissions.length
negativeMessages.push("Their focus on {0} is a bit odd.".localize().format(mission.name))
else if nonOptimalMissions.length is 1
generalModifier -= 0.1 * mmoFactor
badDecisions += 1
underdevelopedMissions = executedDevMissions.filter (m) ->
percentage = m.duration / General.getGameSizeDurationFactor(game.gameSize) / General.getMultiPlatformDurationFactor(game) / (Missions.BASE_DURATION * 3)
Missions.getGenreWeighting(m, game) >= 0.9 and percentage <= 0.2
for m in underdevelopedMissions
mission = Missions.getMissionWithId(m.id)
generalModifier -= 0.15 * mmoFactor
badDecisions += 1
negativeMessages.push("They shouldn't forget about {0}.".localize().format(mission.name))
value = (dp + tp) / 2 / General.getGameSizePointsFactor(game)
topicGenreMatch = GameGenre.getGenreWeighting(game.topic.genreWeightings, game.genre, game.secondGenre)
if topicGenreMatch <= 0.6
negativeMessages.push("{0} and {1} is a terrible combination.".localize().format(game.topic.name, game.getGenreDisplayName()))
else if topicGenreMatch is 1
positiveMessages.push("{0} and {1} is a great combination.".localize().format(game.topic.name, game.getGenreDisplayName()))
genreText = game.genre.name
if game.secondGenre then genreText += "-" + game.secondGenre.name
previousGame = company.gameLog.last()
if previousGame and (not game.flags.isExtensionPack and (previousGame.genre is game.genre and (previousGame.secondGenre is game.secondGenre and previousGame.topic is game.topic)))
penalty = -0.4
badDecisions += 1
sameGenreTopic = "Another {0}/{1} game?".localize().format(genreText, game.topic.name)
negativeMessages.push(sameGenreTopic)
game.flags.sameGenreTopic = true
"repeat genre/topic penalty: {0}:".format(penalty).log()
generalModifier += penalty
platformGenreMatch = Platforms.getGenreWeighting(game.platforms, game.genre, game.secondGenre)
if platformGenreMatch <= 0.6
smallestWeighting = Platforms.getNormGenreWeighting(game.platforms[0].genreWeightings, game.genre, game.secondGenre)
smallestWeightingIndex = 0
for p,i in game.platforms
tempWeighting = Platforms.getNormGenreWeighting(p.genreWeightings, game.genre, game.secondGenre)
if tempWeighting < smallestWeighting then smallestWeightingIndex = i
negativeMessages.push("{0} games don't work well on {1}.".localize().format(genreText, game.platforms[smallestWeightingIndex].name))
else if platformGenreMatch > 1
highestWeighting = Platforms.getNormGenreWeighting(game.platforms[0].genreWeightings, game.genre, game.secondGenre)
highestWeightingIndex = 0
for p,i in game.platforms
tempWeighting = Platforms.getNormGenreWeighting(p.genreWeightings, game.genre, game.secondGenre)
if tempWeighting > highestWeighting then highestWeightingIndex = i
positiveMessages.push("{0} games work well on {1}.".localize().format(genreText, game.platforms[highestWeightingIndex].name))
gameAudienceWeighting = General.getAudienceWeighting(game.topic.audienceWeightings, game.targetAudience)
if gameAudienceWeighting <= 0.6
negativeMessages.push("{0} is a horrible topic for {1} audiences.".localize().format(game.topic.name, General.getAudienceLabel(game.targetAudience)))
if game.flags.sequelsTooClose
generalModifier -= 0.4
badDecisions += 1
if game.flags.isExtensionPack then negativeMessages.push("Already a expansion pack?".localize()) else negativeMessages.push("Didn't we just play {0} recently?".localize().format(sequelTo.title))
if game.flags.usesSameEngineAsSequel and not game.flags.isExtensionPack
generalModifier -= 0.1
badDecisions += 1
else if game.flags.hasBetterEngineThanSequel
generalModifier += 0.2
goodDecisions += 1
if game.flags.mmo
weighting = GameGenre.getGenreWeighting(game.topic.genreWeightings, game.genre, game.secondGenre)
if weighting < 1 then generalModifier -= 0.15
bugModifier = 1
if game.bugs > 0
perc = 100 / (game.technologyPoints + game.designPoints)
bugsPercentage = (game.bugs * perc).clamp(0, 100)
bugModifier = 1 - 0.8 * (bugsPercentage / 100)
if bugModifier <= 0.6 then negativeMessages.push("Riddled with bugs.".localize())
else if bugModifier < 0.9 then negativeMessages.push("Too many bugs.".localize())
techLevelModifier = 1
if game.platforms.length > 1
maxTech = game.platforms[0].techLevel
if game.platforms[0].id is "PC" then maxTech = game.platforms[1].techLevel
minTech = maxTech
for p in game.platforms when p.id isnt "PC"
maxTech = Math.max(maxTech, p.techLevel)
minTech = Math.min(minTech, p.techLevel)
techLevelModifier -= (maxTech - minTech) / 20
value += value * generalModifier
value *= platformGenreMatch
value *= gameAudienceWeighting
value *= bugModifier
value *= techLevelModifier
trendModifier = GameTrends.getCurrentTrendFactor(game)
game.flags.trendModifier = trendModifier
value *= trendModifier
topScore = getCurrentTopScoreBarrier(company)
achievedRatio = value / topScore
if achievedRatio >= 0.6 and (gameAudienceWeighting <= 0.7 or topicGenreMatch <= 0.7)
achievedRatio = 0.6 + (achievedRatio - 0.6) / 2
if achievedRatio > 0.7
for p in game.platforms
if Platforms.getPlatformsAudienceWeighting(p.audienceWeightings, game.targetAudience) <= 0.8
value *= Platforms.getPlatformsAudienceWeighting(p.audienceWeightings, game.targetAudience, true)
achievedRatio = value / topScore
break
"achieved {0} / top game {1} = {2}".format(value, Reviews.topScore, achievedRatio).log()
demote = false
finalScore = (achievedRatio * 10).clamp(1, 10)
game.flags.teamContribution = 0
company.staff.forEach((s) -> if s.flags.gamesContributed < 1 then game.flags.teamContribution elsegame.flags.teamContribution += game.getRatioWorked(s) )
game.flags.teamContribution /= company.staff.length
if company.lastTopScore > 0 and finalScore <= 5.2 - 0.2 * game.platforms.length
if goodDecisions > 0 and (goodDecisions > badDecisions and game.flags.teamContribution >= 0.8)
baseScore = 6
numberWorkedOnGame = 0
for key of game.flags.staffContribution
if not game.flags.staffContribution.hasOwnProperty(key) then continue
numberWorkedOnGame++
optimalSize = General.getOptimalTeamSize(game)
diff = Math.abs(optimalSize - numberWorkedOnGame)
if diff > 1 then baseScore -= diff - 1
newStaff = Reviews.getNewStaff(game)
if newStaff
if newStaff.length > 0 then baseScore -= newStaff.length / 2
baseScore += goodDecisions / 2 - badDecisions / 2
if bugModifier < 0.9 then baseScore -= 0.5
else if bugModifier <= 0.6 then baseScore -= 1
if platformGenreMatch <= 0.8 then baseScore -= 1 - platformGenreMatch
if gameAudienceWeighting <= 0.8 then baseScore -= 1 - gameAudienceWeighting
if game.platforms.length > 1
maxTech = game.platforms[0].techLevel
if game.platforms[0].id is "PC"
maxTech = game.platforms[1].techLevel
minTech = maxTech
for p in game.platforms when p.id isnt "PC"
maxTech = Math.max(maxTech, p.techLevel)
minTech = Math.min(minTech, p.techLevel)
baseScore -= (maxTech - minTech) / 0.5
baseScore -= company.getRandom()
baseScore = Math.min(baseScore, 7.7)
if finalScore < baseScore
game.flags.scoreWithoutBrackets = finalScore
finalScore = baseScore
if company.gameLog.length > 3
topScoreDecrease = true
for i in [1..3]
tempGame = company.gameLog[company.gameLog.length - i]
if tempGame.score > 5.2 - 0.2 * tempGame.platforms.length and not tempGame.flags.scoreWithoutBrackets
topScoreDecrease = false
break
if topScoreDecrease
company.lastTopScore = value
game.flags.topScoreDecreased = true
maxScoreFactor = getMaxScorePossible(company, game) / 10
if game.gameSize isnt "medium" and (game.gameSize isnt "small" and maxScoreFactor < 1)
negativeMessages.push("Technology is not state of the art.".localize())
finalScore *= maxScoreFactor
if finalScore >= 9
if generalModifier < 0.1 and company.getRandom() < 0.8 then demote = true
else
newStaff = Reviews.getNewStaff(game)
if newStaff.length > 0
demote = true
game.flags.newStaffIds = newStaff.map((staff) -> staff.id )
if demote
if game.flags.newStaffIds and game.flags.newStaffIds.length > 0
finalScore = 8.15 + 0.95 / game.flags.newStaffIds.length * company.getRandom()
else
finalScore = 8.45 + 0.65 * company.getRandom()
if company.getRandom() < 0.1
finalScore = 9 + 0.25 * company.getRandom()
updateTopScore(company, value)
if sequelTo
if finalScore <= 4
if game.flags.isExtensionPack then negativeMessages.push("What a horrible expansion pack!".localize()) else negativeMessages.push("What a horrible sequel!".localize())
else if finalScore <= 7
if game.flags.isExtensionPack then negativeMessages.push("Average expansion pack.".localize()) else negativeMessages.push("Average sequel.".localize())
else
if game.flags.isExtensionPack then positiveMessages.push("Great expansion pack.".localize()) else positiveMessages.push("Great sequel!".localize())
if company.topScoreAchievements < 2 and company.getCurrentDate().year < 4
if finalScore == 10
finalScore -= 1.05 + 0.45 * company.getRandom()
setTopScoreAchievement(company, value)
else if finalScore >= 9
finalScore -= 1.05 + 0.2 * company.getRandom()
setTopScoreAchievement(company, value)
else if finalScore > 8.5 then finalScore -= 0.4 + 0.2 * company.getRandom()
if finalScore >= 9 then setTopScoreAchievement(company, value)
if finalScore isnt 10 and (game.flags.topScore and company.topScoreAchievements is 3) then finalScore = 10
game.score = finalScore
"final score: {0}".format(finalScore).log()
if sequelTo
if company.getRandom() <= 0.5 or not company.gameLog.some((g) -> g.sequelTo? )
if game.flags.isExtensionPack then Media.createExtensionPackStory(company, game)
else Media.createSequelStory(company, game)
retVal = Reviews.getReviews(game, finalScore, positiveMessages, negativeMessages)
GDT.fire(GameManager, GDT.eventKeys.gameplay.afterGameReview, {
company : company,
game : game,
reviews : retVal
})
retVal
generate: (game, finalScore, positiveMessages, negativeMessages) ->
intScore = Math.floor(finalScore).clamp(1, 10)
if finalScore >= 9.5 then intScore = 10
reviewers = GDT.Reviewer.pickReviewers(4)
reviews = []
usedMessages = []
scores = []
variation = 1
for reviewer in reviewers
if intScore is 5 or intScore is 6 then (variation = if GameManager.company.getRandom() < 0.05 then 2 else 1)
scoreVariation = if Math.randomSign() is 1 then 0 else variation * Math.randomSign()
score = (intScore + scoreVariation).clamp(1, 10)
if score is 10 and (scores.length is 3 and scores.average() is 10)
if not game.flags.psEnabled
if Math.floor(finalScore) < 10 or GameManager.company.getRandom() < 0.8 then score--
else if Math.floor(finalScore) is 10 and GameManager.company.getRandom() < 0.4 then score++
message = if reviewer.getMessage? then reviewer.getMessage(game, finalScore) else undefined
if message is undefined
`do {
if (GameManager.company.getRandom() <= 0.2)
if (scoreVariation >= 0 && (score > 2 && positiveMessages.length != 0))
message = positiveMessages.pickRandom();
else {
if (scoreVariation < 0 && (score < 6 && negativeMessages != 0))
message = negativeMessages.pickRandom()
}
else
message = undefined;
if (!message)
message = Reviews.getGenericReviewMessage(game, score)
} while (usedMessages.weakIndexOf(message) != -1)`
usedMessages.push(message)
scores.push(score)
reviews.push {
score : score,
message : message,
reviewerName : reviewer.name
}
reviews
getById: (id) -> GDT.Reviewer.getAll().first((r) -> r.id is id)
getMessageById: (id) -> GDT.Reviewer.getAllMessages.first((m) -> m.id is id)
}
GDT.Reviewer.reviewers.forEach((e, i) -> GDT.Reviewer.reviewers[i] = {name: e, id: e.replace(' ', '')})
)()
GDT.Event = {
events: DecisionNotifications.getAllNotificationsObjects()
getAll: -> GDT.Event.slice()
getAvailable: (company) ->
events = GDT.Event.getAll().filter((e) -> not e.isRandom and GDT.Event.isAvailable(e))
getRandom: (company) ->
spawnEvent = company.flags.nextRandomEvent and company.flags.nextRandomEvent <= GameManager.gameTime
unless company.flags.nextRandomEvent
company.flags.nextRandomEvent = (48 + 24 * company.getRandom()) * GameManager.SECONDS_PER_WEEK * 1e3
if spawnEvent
company.flags.nextRandomEvent = GameManager.gameTime + (36 + 48 * company.getRandom()) * GameManager.SECONDS_PER_WEEK * 1e3
candidates = GDT.Event.getAll().filter((e) ->
e.isRandomEvent and (company.flags.lastRandomEventId isnt e.id and GDT.Event.isAvailable(company, e))
)
event = candidates.pickRandom()
unless event then return []
company.flags.lastRandomEventId = event.id
return event
return []
trigger: (company, event) ->
unless company.eventTriggerCounts[event.id] then company.eventTriggerCounts[event.id] = 1
else company.eventTriggerCounts[event.id]++
return if event.notification then event.notification else event.getNotification(company)
isAvailable: (company, event) ->
if event.date
return false if Math.floor(company.currentWeek) < General.getWeekFromDateString(event.date, event.ignoreGameLengthModifier)
if event.maxTriggers or event.date
count = GameManager.company.eventTriggerCounts[event.id]
return false if count and count >= (if event.date then 1 else event.maxTriggers)
event.date or event.trigger and event.trigger(company)
getById: (id) -> GDT.Event.getAll().first((e) -> e.id is id )
}
GDT.Notification = {
queue: []
getNotification: (company, event) -> if event.notification then event.notification else event.getNotification(company)
getNewNotifications: (company) ->
results = GDT.Event.getAvailable(company).map((e) -> GDT.Event.trigger(company, e))
if results.length is 0 then results = [GDT.Event.trigger(company, GDT.Event.getRandom(company))]
results
}
DecisionNotifications.getNewNotifications = GDT.Notification.getNewNotifications
GDT.ModSupport = ( ->
ModSupport = {}
oldLoad = ModSupport.loadMod
ModSupport.loadMod = (enableMods, i) ->
SDP.Util.Logger.formatter = SDP.Util.Logger.printf
oldLoad(enableMods, i)
ModSupport
)()
ModSupport.loadMod = GDT.ModSupport.loadMod
GDT
)()
# Adds a basic wrapper of UltimateLib functionality for easy conversion to the SDP
( ->
SDP.ULWrapper = {}
unless String::endsWith?
String::endsWith = (a) ->
@substr(@length - a.length) is a
unless String::startsWith?
String::startsWith = (a) ->
@substr(0, a.length) is a
unless Number::truncateDecimals?
Number::truncateDecimals = (a) ->
b = @ - Math.pow(10, -a) / 2
b += b / Math.pow(2, 53)
b.toFixed(a)
SDP.ULWrapper.Logger = ( ->
Loggger = { enabled: true }
Logger.log = (e, c) ->
if not Logger.enabled then return
unless c? then SDP.Util.Logger.debug(e) else SDP.Util.Logger.error("#{e}\n#{c.message}")
Logger
)()
SDP.ULWrapper.Contracts = ( ->
Contracts = {}
Contracts.add = (c) ->
isAvailable = (isRand, chance) ->
if isRand is true
if (1 is Math.floor((Math.random() * chance) + 1)) is false then isRand = false
if isRand is false then isRand = true
return isRand
c.isAvailable = (company) ->
c.canTrigger(company) and isAvailable(c.isRandom, c.randomChance)
c.card = {
techPoints: c.requiredT
designPoints: c.requiredD
payment: c.payment
penalty: c.penalty
weeks: c.weeksToFinish
}
SDP.Functional.addContractItem(c)
Contracts.collection = (company) ->
SDP.GDT.Contract.getAvailable(company).filter((c) ->
c.size is 'small' or (company.flags.mediumContractsEnabled and c.size is 'medium') or (company.flags.largeContractsEnabled and c.size is 'large')
)
Contracts
)()
SDP.ULWrapper.Publishers = ( ->
Publishers = {}
# add Publisher modifications here
Publishers
)()
SDP.ULWrapper.Research = ( ->
Research = {}
# add Research modifications here
Research
)()
)()
###
Adds company tracking system
Companies.createCompany = (item) ->
if item.constructor is String then item = {name: item}
if not item.id? and item.name? then item.id = name.replace(/\s/g,"")
item.platforms = []
item.platforms.push(p) for p of Platforms.allPlatforms when p.company is item.name
item.sort = ->
item.platforms.sort (a,b) ->
General.getWeekFromDateString(a.published) - General.getWeekFromDateString(b.published)
item.addPlatform = (platform) ->
return if item.platforms.find((val) -> platform.id is val.id)?
platform.company = item.name
SDP.GDT.addPlatform(platform)
item.platforms.push(platform)
item.sort()
platform
item.sort()
item
Companies.createVanillaCompany = (item) ->
Companies.createCompany(item)
item.isVanilla = true
item
Companies.vanillaCompanies = [
Companies.createVanillaCompany("Micronoft")
Companies.createVanillaCompany("Grapple")
Companies.createVanillaCompany("Govodore")
Companies.createVanillaCompany("Ninvento")
Companies.createVanillaCompany("<NAME>")
Companies.createVanillaCompany("<NAME>")
Companies.createVanillaCompany("KickIT")
]
Companies.moddedCompanies = []
Companies.getAllCompanies = ->
c = Companies.vanillaCompanies.filter (val) -> val.id?
c.addRange(Companies.moddedCompanies.filter (val) -> val.id?)
for comp of c
comp.sort = ->
comp.platforms.sort (a,b) ->
General.getWeekFromDateString(a.published) - General.getWeekFromDateString(b.published)
comp.sort()
c.sort (a,b) ->
General.getWeekFromDateString(a.platforms[0].published) - General.getWeekFromDateString(b.platforms[0].published)
c
Companies.getAvailableCompanies = (company) ->
week = Math.floor(company.currentWeek)
Companies.getAllCompanies().filter (val) ->
General.getWeekFromDateString(val.platforms[0].published) <= week
###
GDT.on(GDT.eventKeys.saves.loaded, ->
GameManager.company.notifications.push(i) for i in SDP.GDT.Notification.queue
SDP.GDT.Notification.queue = [])
GDT.on(GDT.eventKeys.saves.newGame, ->
GameManager.company.notifications.push(i) for i in SDP.GDT.Notification.queue
SDP.GDT.Notification.queue = [])
###
Modifies GDT classes to make all objects indepedent of GameManager.company
###
( ->
oldGameConst = Game
oldGame = oldGameConst::
Game = (company) ->
oldGameConst.call(@, company)
@company = company
return
Game:: = oldGame
)()
( ->
oldCharConst = Character
oldChar = oldCharConst::
Character = (args...) ->
oldCharConst.call(@, args)
@company = args[0].company or SDP.GDT.Company.getAllCompanies()[args[0].uid] or SDP.GDT.Company.getClientCompany()
return
Character:: = oldChar
oldSave = Character::save
Character::save = ->
oldSave.call(@).companyId = @company.uid
)()
( ->
oldCompanyConst = Company
oldCompany = oldCompanyConst::
Company = (args...) ->
oldCompanyConst.call(@, args)
SDP.GDT.Company.addCompany(@)
return
Company:: = oldCompany
)()
###
Allow adding famous people and adding custom applicant algorithims
JobApplicants.moddedFamous = []
JobApplicants.moddedAlgorithims = []
JobApplicants.getRandomMale = (random) ->
results = []
JobApplicants.moddedAlgorithims.forEach (val) ->
results.push(val.apply(random)) if val.forMale
results.pickRandom(random)
JobApplicants.getRandomFemale = (random) ->
results = []
JobApplicants.moddedAlgorithims.forEach (val) ->
results.push(val.apply(random)) if not val.forMale
results.pickRandom(random)
JobApplicants.getFamousMale = (tech, design, random) ->
results = []
JobApplicants.moddedFamous.forEach (val) ->
results.push(val.apply(random, tech, design)) if val.forMale
results.pickRandom(random)
JobApplicants.getFamousFemale = (tech, design, random) ->
results = []
JobApplicants.moddedFamous.forEach (val) ->
results.push(val.apply(random, tech, design)) if not val.forMale
results.pickRandom(random)
JobApplicants.searchTests =
[
{
id : "ComplexAlgorithms"
name : "Complex Algorithms".localize()
minT : 0.6
}
{
id : "GameDemo"
name : "Game Demo".localize()
minD : 0.3,
minT : 0.3
}
{
id : "Showreel"
name : "Showreel".localize()
minD : 0.6
}
]
UI.__olgGenerateJobApplicants = UI._generateJobApplicants
UI._generateJobApplicants = ->
oldApplicants = UI.__olgGenerateJobApplicants()
settings = GameManager.uiSettings["findStaffData"]
settings = {ratio : 0.1, tests : []} if not settings
settings.seed = Math.floor(GameManager.company.getRandom() * 65535) if not settings.seed
ratio = settings.ratio
test = JobApplicants.searchTests.first (t) -> t.id is settings.tests.first()
company = GameManager.company
random = new MersenneTwister(settings.seed)
newApplicants = []
count = Math.floor(2 + 3 * (ratio + 0.2).clamp(0, 1))
rerolls = 0
maxRerolls = 2
maxBonus = if company.currentLevel is 4 then 4 / 5 else 2 / 5
takenNames = GameManager.company.staff.map (s) -> s.name
for i in [0...count]
qBonusFactor = ratio / 3 + (1 - ratio / 3) * random.random()
maxBonus += 1 / 5 if random.random() >= 0.95
q = 1 / 5 + maxBonus * qBonusFactor
level = Math.floor(q * 5).clamp(1,5)
maxD = 1
minD = 0
if test
maxD -= test.minT if test.minT
if test.minD
minD = test.minD
maxD -= minD
baseValue = 200 * level
d = baseValue * minD + baseValue * maxD * random.random()
t = baseValue - d
rBonusFactor = random.random()
r = 1 / 5 + maxBonus * rBonusFactor
sBonusFactor = random.random()
s = 1 / 5 + maxBonus * sBonusFactor
goodRoll = sBonusFactor > 0.5 and (qBonusFactor > 0.5 and rBonusFactor > 0.5)
if not goodRoll and (rerolls < maxRerolls and random.random() <= (ratio + 0.1).clamp(0, 0.7))
i--
rerolls++
continue
rerolls = 0
isFamous = false
sex = "male"
loop
sex = "male"
if goodRoll
name = JobApplicants.getFamousMale(t, d, random) if (random.random() > 0.15)
else
name = JobApplicants.getFamousFemale(t, d, random)
sex = "female"
isFamous = true
else
name = JobApplicants.getRandomMale(random) if random.random() > 0.25
else
name = JobApplicants.getRandomFemale(random)
sex = "female"
isFamous = false
break unless takenNames.indexOf(name) != -1
takenNames.push(<NAME>)
salary = Character.BASE_SALARY_PER_LEVEL * level
salary += salary * 0.2 * random.random() * random.randomSign()
salary = Math.floor(salary/1e3) * 1e3
newApplicants.push {
name : <NAME>,
qualityFactor : q,
technologyFactor : t / 500,
designFactor : d / 500,
researchFactor : r,
speedFactor : s,
salary : salary,
isFamous : isFamous,
sex : sex
}
GDT.fire GameManager, GDT.eventKeys.gameplay.staffApplicantsGenerated, {
newApplicants : newApplicants
settings : settings
rng : random
}
applicants = []
for i in [0...count]
if random.random() >= 0.5
a = newApplicants.pickRandom(random)
applicants.push(a)
newApplicants.remove(a)
else
a = oldApplicants.pickRandom(random)
applicants.push(a)
oldApplicants.remove(a)
return applicants
### | true | ### Definitions for the devised SpartaDoc
All types can either contain the name of the types as found here or the vanilla API as analogs, this is corrected by the SDP
---
@customType ResearchItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [String] type The SDP.GDT.Research.types string this represents
@instruction('optional' if 'v')
@attribute [Integer] pointsCost The cost of the research in research points
@attribute [Integer] duration The time it takes to complete the research in milliseconds
@attribute [Integer] researchCost The cost this research will take to research, without devCost, small scale devCost = researchCost * 4
@instruction('optional' if 'researchCost') @attribute [Integer] devCost The cost to develop with this research on in small scale
@attribute [Integer] engineCost The cost to put this into an engine
@defaults(pointsCost) @attribute [Integer] enginePoints The amount of points this will cost to put in an engine
@attribute [String] category May be SDP.Constants.ResearchCategory of the object, or maybe something else
@attribute [String] categoryDisplayName Similar to category, human readable version
@optional
@attribute [Integer] v A basic value to scale the research by
@attribute [String] group The group to assign this research to, prevents more then one group being selected on games
@attribute [Boolean] consolePart Whether this research applies to console creation as well
@attribute [Boolean] engineStart Whether the research is available to all engines without research, overrides canResearch to always return false
@attribute [Function(Game)] canUse Determines whether this research can be used
@fparam [Game] game The game to test use against
@freturn [Boolean] Whether the research can be used
@attribute [Function(CompanyItem)] canResearch Determines whether this research is allowed to be researched
@fparam [CompanyItem] company The company to check whether its researchable for
@freturn [Boolean] Whether the research can be researched
---
@customType PlatformItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [String] company The company name this platform belongs to
@attribute [Float] startAmount The starting amount of units sold on release (multiplied by 5000000)
@attribute [Float] unitsSold The resulting units sold by the end (multiplied by 5000000)
@attribute [Integer] licensePrice The one time license price to develop on the platform
@attribute [String] publishDate The release date of the platform
@attribute [String] retireDate The retire date of the platform
@attribute [Integer] devCost The dev cost for developing on the platform
@attribute [Integer] techLevel The tech level of the platform (1-9, determines how ingenious the platform and the games for it will be)
@attribute [String] iconUri The icon refered to for the icon of the platform (or base uri if contains imageDates)
@attribute [Array {String date, Float amount}] marketPoints The key date points of the market in which the units sold change to the amount
@attribute [Array [6 Float]] genreWeight The weightings per genre based on SDP.Constants.Genre
@attribute [Array [3 Float]] audienceWeight The weightings per audience based on SDP.Constants.Audience
@optional @attribute [Array [String]] imageDates The dates for the platform image to change
---
@customType TopicItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [Array [6 Float]] genreWeight The weightings per genre based on SDP.Constants.Genre
@attribute [Array [3 Float]] audienceWeight The weightings per audience based on SDP.Constants.Audience
@attribute [Array [6 Array [9 Float]]] overrides The mission overrides as described on the [wiki](https://github.com/greenheartgames/gdt-modAPI/wiki/missionOverrides)
---
@customType ResearchProjectItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [String] description The description of the project
@attribute [Integer] pointsCost The cost to make in research points
@attribute [String] iconUri The uri of the icon to display for the project
@attribute [Integer] targetZone The zone for the project to take place in (0 for Hardware Lab, 2 for Research Lab, Effects of 1 unknown)
@optional @attribute [Boolean] repeatable Determiners whether the project can be repeated
@optional @attribute [Function(CompanyItem)] canResearch Determines whether research can be done
@fparam [CompanyItem] company The company being tested
@freturn [Boolean] Whether research can be done on the project
@optional @attribute [Function(CompanyItem)] complete A function to perform on completion
@fparam [CompanyItem] company The company responsible for completing the project
@optional @attribute [Function(CompanyItem)] cancel Activates on cancelation of the project
@fparam [CompanyItem] company The company canceling the project
---
@customType TrainingItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [Integer] pointsCost The cost in research points
@attribute [Integer] duration How long it will take to complete the training
@attribute [String] category The category of the object
@attribute [String] categoryDisplayName Similar to category, human readable version
@optional
@attribute [Integer] cost The cost in money
@attribute [Function(CharacterObject, CompanyItem)] canSee Determines whether the staff can see this training
@fparam [CharacterObject] staff The staff that should be able to see the training
@fparam [CompanyItem] company The company the training is taken place in
@freturn [Boolean] Whether the training can be seen
@attribute [Function(CharacterObject, CompanyItem)] canUse Determines whether the staff can use this training
@fparam [CharacterObject] staff The staff that should be able to use the training
@fparam [CompanyItem] company The company the training is taken place in
@freturn [Boolean] Whether the training can be used
@attribute [Function(CharacterObject, Integer)] tick Triggers every game tick this training is active
@fparam [CharacterObject] staff The staff that is performing the training
@fparam [Integer] delta The amount of milliseconds passed from the last tick
@attribute [Function(CharacterObject)] complete Triggers on training completion
@fparam [CharacterObject] staff The staff to complete the training
---
@customType ContractItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
@attribute [String] description The description of the contract
@attribute [String] size The size of the contract, either small, medium, or large
@attribute [Float] tF The tech factor of the contract
@attribute [Float] dF The design factor of the contract
@optional
@attribute [Function(CompanyItem, MersenneTwister)] generateCard Generates a contract card depending on the company and random
@fparam [CompanyItem] company The company to generate the card for
@fparam [MersenneTwister] random The random object used for generating the contract
@freturn [ContractCardItem] The card item representing the contract generated
@attribute [ContractCardItem] card The card item to repsent the contract definitely (generateCard takes priority)
@attribute [Function(CompanyItem)] complete A function to perform on completion
@fparam [CompanyItem] company The company responsible for completing the contract
@note generateCard and card can be ignored if tF and dF are supplied and vice versa
@optional
@attribute [Float] rF The research factor generated
---
@customType PublisherItem
@attribute [String] id The unique id of the item
@attribute [String] name The name of the item
---
@customType ReviewerItem
---
@customType NotificationItem
@attribute [String] header The header of the notification
@attribute [String] text The text to display upon notifcation being tiggered
@instruction('optional' if 'options')
@attribute [String] buttonTxt The text for the button to display
@instruction('optional' if 'buttonTxt')
@attribute [Array [1-3 String]] options A collection of possible button options to choose from
@optional
@attribute [String] image The image uri for the notification
@attribute [String] sourceId The id of the corresponding event object
@attribute [Integer] weeksUntilFire The amount of weeks that must pass before this notification is fired
---
@customType EventItem
@attribute [String] id The id of the event
@attribute [Function(CompanyItem)] trigger Determines whether the event can trigger
@fparam [CompanyItem] company The company to test this trigger by
@instruction('optional' if 'getNotification') @attribute [NotificationItem] notification The notification for this event (overrides getNotification)
@instruction('optional' if 'notification') @attribute [Function(CompanyItem)] Retrieves a notification for this event
@fparam [CompanyItem] company The company to retrieve the notification for
@freturn [NotificationItem] The notification that was produced
@optional
@attribute [Boolean] isRandomEvent Determines whether this event is random
@attribute [Function(Integer)] complete Determines what happens upon completion (this.runningCompany refers to the active company for this event)
@fparam [Integer] decision The decision chosen in the notification from 0 to 2
---
@customType ContractCardItem
@optional
@attribute [Integer] techPoints The tech points to generate for the contract (overrides tF)
@attribute [Integer] designPoints The design points to generate for the contract (overrides dF)
@attribute [Float] tF The tech factor generated for the card
@attribute [Float] dF The design factor generated for the card
@attribute [Integer] minPoints The minimum points to generate based on factors (ignored if techPoints and designPoints supplied)
@attribute [Integer] pay The pay available upon the contract's completion
@attribute [Integer] penalty The penalty for job failure
@attribute [Integer] weeks The amount of weeks determined to finish the contracts
###
style = require('./lib-js/style')
# @namespace Spartan Dev Project
#
# The primary namespace holding all of the SDP
SDP = {}
Companies = {}
JobApplicants = {}
###
jSTORAGE
###
`(function(){function C(){var a="{}";if("userDataBehavior"==f){g.load("jStorage");try{a=g.getAttribute("jStorage")}catch(b){}try{r=g.getAttribute("jStorage_update")}catch(c){}h.jStorage=a}D();x();E()}function u(){var a;clearTimeout(F);F=setTimeout(function(){if("localStorage"==f||"globalStorage"==f)a=h.jStorage_update;else if("userDataBehavior"==f){g.load("jStorage");try{a=g.getAttribute("jStorage_update")}catch(b){}}if(a&&a!=r){r=a;var l=p.parse(p.stringify(c.__jstorage_meta.CRC32)),k;C();k=p.parse(p.stringify(c.__jstorage_meta.CRC32));
var d,n=[],e=[];for(d in l)l.hasOwnProperty(d)&&(k[d]?l[d]!=k[d]&&"2."==String(l[d]).substr(0,2)&&n.push(d):e.push(d));for(d in k)k.hasOwnProperty(d)&&(l[d]||n.push(d));s(n,"updated");s(e,"deleted")}},25)}function s(a,b){a=[].concat(a||[]);var c,k,d,n;if("flushed"==b){a=[];for(c in m)m.hasOwnProperty(c)&&a.push(c);b="deleted"}c=0;for(d=a.length;c<d;c++){if(m[a[c]])for(k=0,n=m[a[c]].length;k<n;k++)m[a[c]][k](a[c],b);if(m["*"])for(k=0,n=m["*"].length;k<n;k++)m["*"][k](a[c],b)}}function v(){var a=(+new Date).toString();
if("localStorage"==f||"globalStorage"==f)try{h.jStorage_update=a}catch(b){f=!1}else"userDataBehavior"==f&&(g.setAttribute("jStorage_update",a),g.save("jStorage"));u()}function D(){if(h.jStorage)try{c=p.parse(String(h.jStorage))}catch(a){h.jStorage="{}"}else h.jStorage="{}";z=h.jStorage?String(h.jStorage).length:0;c.__jstorage_meta||(c.__jstorage_meta={});c.__jstorage_meta.CRC32||(c.__jstorage_meta.CRC32={})}function w(){if(c.__jstorage_meta.PubSub){for(var a=+new Date-2E3,b=0,l=c.__jstorage_meta.PubSub.length;b<
l;b++)if(c.__jstorage_meta.PubSub[b][0]<=a){c.__jstorage_meta.PubSub.splice(b,c.__jstorage_meta.PubSub.length-b);break}c.__jstorage_meta.PubSub.length||delete c.__jstorage_meta.PubSub}try{h.jStorage=p.stringify(c),g&&(g.setAttribute("jStorage",h.jStorage),g.save("jStorage")),z=h.jStorage?String(h.jStorage).length:0}catch(k){}}function q(a){if("string"!=typeof a&&"number"!=typeof a)throw new TypeError("Key name must be string or numeric");if("__jstorage_meta"==a)throw new TypeError("Reserved key name");
return!0}function x(){var a,b,l,k,d=Infinity,n=!1,e=[];clearTimeout(G);if(c.__jstorage_meta&&"object"==typeof c.__jstorage_meta.TTL){a=+new Date;l=c.__jstorage_meta.TTL;k=c.__jstorage_meta.CRC32;for(b in l)l.hasOwnProperty(b)&&(l[b]<=a?(delete l[b],delete k[b],delete c[b],n=!0,e.push(b)):l[b]<d&&(d=l[b]));Infinity!=d&&(G=setTimeout(x,Math.min(d-a,2147483647)));n&&(w(),v(),s(e,"deleted"))}}function E(){var a;if(c.__jstorage_meta.PubSub){var b,l=A,k=[];for(a=c.__jstorage_meta.PubSub.length-1;0<=a;a--)b=
c.__jstorage_meta.PubSub[a],b[0]>A&&(l=b[0],k.unshift(b));for(a=k.length-1;0<=a;a--){b=k[a][1];var d=k[a][2];if(t[b])for(var n=0,e=t[b].length;n<e;n++)try{t[b][n](b,p.parse(p.stringify(d)))}catch(g){}}A=l}}var y=window.jQuery||window.$||(window.$={}),p={parse:window.JSON&&(window.JSON.parse||window.JSON.decode)||String.prototype.evalJSON&&function(a){return String(a).evalJSON()}||y.parseJSON||y.evalJSON,stringify:Object.toJSON||window.JSON&&(window.JSON.stringify||window.JSON.encode)||y.toJSON};if("function"!==
typeof p.parse||"function"!==typeof p.stringify)throw Error("No JSON support found, include //cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js to page");var c={__jstorage_meta:{CRC32:{}}},h={jStorage:"{}"},g=null,z=0,f=!1,m={},F=!1,r=0,t={},A=+new Date,G,B={isXML:function(a){return(a=(a?a.ownerDocument||a:0).documentElement)?"HTML"!==a.nodeName:!1},encode:function(a){if(!this.isXML(a))return!1;try{return(new XMLSerializer).serializeToString(a)}catch(b){try{return a.xml}catch(c){}}return!1},
decode:function(a){var b="DOMParser"in window&&(new DOMParser).parseFromString||window.ActiveXObject&&function(a){var b=new ActiveXObject("Microsoft.XMLDOM");b.async="false";b.loadXML(a);return b};if(!b)return!1;a=b.call("DOMParser"in window&&new DOMParser||window,a,"text/xml");return this.isXML(a)?a:!1}};y.jStorage={version:"0.4.12",set:function(a,b,l){q(a);l=l||{};if("undefined"==typeof b)return this.deleteKey(a),b;if(B.isXML(b))b={_is_xml:!0,xml:B.encode(b)};else{if("function"==typeof b)return;
b&&"object"==typeof b&&(b=p.parse(p.stringify(b)))}c[a]=b;for(var k=c.__jstorage_meta.CRC32,d=p.stringify(b),g=d.length,e=2538058380^g,h=0,f;4<=g;)f=d.charCodeAt(h)&255|(d.charCodeAt(++h)&255)<<8|(d.charCodeAt(++h)&255)<<16|(d.charCodeAt(++h)&255)<<24,f=1540483477*(f&65535)+((1540483477*(f>>>16)&65535)<<16),f^=f>>>24,f=1540483477*(f&65535)+((1540483477*(f>>>16)&65535)<<16),e=1540483477*(e&65535)+((1540483477*(e>>>16)&65535)<<16)^f,g-=4,++h;switch(g){case 3:e^=(d.charCodeAt(h+2)&255)<<16;case 2:e^=
(d.charCodeAt(h+1)&255)<<8;case 1:e^=d.charCodeAt(h)&255,e=1540483477*(e&65535)+((1540483477*(e>>>16)&65535)<<16)}e^=e>>>13;e=1540483477*(e&65535)+((1540483477*(e>>>16)&65535)<<16);k[a]="2."+((e^e>>>15)>>>0);this.setTTL(a,l.TTL||0);s(a,"updated");return b},get:function(a,b){q(a);return a in c?c[a]&&"object"==typeof c[a]&&c[a]._is_xml?B.decode(c[a].xml):c[a]:"undefined"==typeof b?null:b},deleteKey:function(a){q(a);return a in c?(delete c[a],"object"==typeof c.__jstorage_meta.TTL&&a in c.__jstorage_meta.TTL&&
delete c.__jstorage_meta.TTL[a],delete c.__jstorage_meta.CRC32[a],w(),v(),s(a,"deleted"),!0):!1},setTTL:function(a,b){var l=+new Date;q(a);b=Number(b)||0;return a in c?(c.__jstorage_meta.TTL||(c.__jstorage_meta.TTL={}),0<b?c.__jstorage_meta.TTL[a]=l+b:delete c.__jstorage_meta.TTL[a],w(),x(),v(),!0):!1},getTTL:function(a){var b=+new Date;q(a);return a in c&&c.__jstorage_meta.TTL&&c.__jstorage_meta.TTL[a]?(a=c.__jstorage_meta.TTL[a]-b)||0:0},flush:function(){c={__jstorage_meta:{CRC32:{}}};w();v();s(null,
"flushed");return!0},storageObj:function(){function a(){}a.prototype=c;return new a},index:function(){var a=[],b;for(b in c)c.hasOwnProperty(b)&&"__jstorage_meta"!=b&&a.push(b);return a},storageSize:function(){return z},currentBackend:function(){return f},storageAvailable:function(){return!!f},listenKeyChange:function(a,b){q(a);m[a]||(m[a]=[]);m[a].push(b)},stopListening:function(a,b){q(a);if(m[a])if(b)for(var c=m[a].length-1;0<=c;c--)m[a][c]==b&&m[a].splice(c,1);else delete m[a]},subscribe:function(a,
b){a=(a||"").toString();if(!a)throw new TypeError("Channel not defined");t[a]||(t[a]=[]);t[a].push(b)},publish:function(a,b){a=(a||"").toString();if(!a)throw new TypeError("Channel not defined");c.__jstorage_meta||(c.__jstorage_meta={});c.__jstorage_meta.PubSub||(c.__jstorage_meta.PubSub=[]);c.__jstorage_meta.PubSub.unshift([+new Date,a,b]);w();v()},reInit:function(){C()},noConflict:function(a){delete window.$.jStorage;a&&(window.jStorage=this);return this}};(function(){var a=!1;if("localStorage"in
window)try{window.localStorage.setItem("_tmptest","tmpval"),a=!0,window.localStorage.removeItem("_tmptest")}catch(b){}if(a)try{window.localStorage&&(h=window.localStorage,f="localStorage",r=h.jStorage_update)}catch(c){}else if("globalStorage"in window)try{window.globalStorage&&(h="localhost"==window.location.hostname?window.globalStorage["localhost.localdomain"]:window.globalStorage[window.location.hostname],f="globalStorage",r=h.jStorage_update)}catch(k){}else if(g=document.createElement("link"),
g.addBehavior){g.style.behavior="url(#default#userData)";document.getElementsByTagName("head")[0].appendChild(g);try{g.load("jStorage")}catch(d){g.setAttribute("jStorage","{}"),g.save("jStorage"),g.load("jStorage")}a="{}";try{a=g.getAttribute("jStorage")}catch(m){}try{r=g.getAttribute("jStorage_update")}catch(e){}h.jStorage=a;f="userDataBehavior"}else{g=null;return}D();x();"localStorage"==f||"globalStorage"==f?"addEventListener"in window?window.addEventListener("storage",u,!1):document.attachEvent("onstorage",
u):"userDataBehavior"==f&&setInterval(u,1E3);E();"addEventListener"in window&&window.addEventListener("pageshow",function(a){a.persisted&&u()},!1)})()})()`
###
jSTORAGE End
###
"use strict"
SDP.Util = ( ->
util = {}
fs = require('fs')
path = require('path')
normalizeStringPosix = (path, allowAboveRoot) ->
res = ''
lastSlash = -1
dots = 0
code = undefined
for i in [0..path.length]
if i < path.length then code = path.charCodeAt(i)
else if code is 47 then break
else code = 47
if code is 47
if lastSlash is i - 1 or dots is 1
#NOOP
else if lastSlash isnt i - 1 and dots is 2
if res.length < 2 or res.charCodeAt(res.length - 1) isnt 46 or res.charCodeAt(res.length - 2) isnt 46
if res.length > 2
start = res.length - 1
j = start
for j in [start..0]
if res.charCodeAt(j) is 47 then break
if j isnt start
if j is -1 then res = ''
else res = res.slice(0, j)
lastSlash = i
dots = 0
continue
else if res.length is 2 or res.length is 1
res = ''
lastSlash = i
dots = 0
continue
if allowAboveRoot
if res.length > 0 then res += '/..'
else res = '..'
else
if res.length > 0 then res += '/' + path.slice(lastSlash + 1, i)
else res = path.slice(lastSlash + 1, i)
lastSlash = i
dots = 0
else if code is 46 and dots isnt -1 then ++dots else dots = -1
return res
# Define very useful, efficent (as much as possible), basic utility functions
util.GLOBAL = (Function("return this"))()
util.kindOf = (obj) -> Object.prototype.toString.call(obj).slice(8, -1)
util.hasOwn = (obj, key) -> Object.prototype.hasOwnProperty.call(obj, key)
util.isKind = (obj, kind) -> util.kindOf(obj) is kind
util.isUndefined = (obj) -> obj is undefined
util.isNull = (obj) -> obj is null
util.isString = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is String
util.isArray = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is Array
util.isNumber = (obj) ->
if obj is undefined or obj is null or obj isnt obj then return false
return obj.constructor is Number
util.isInteger = (obj) -> util.isNumber(obj) and (obj % 1 is 0)
util.isFloat = (obj) -> util.isNumber(obj) and (obj % 1 isnt 0)
util.isObject = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is Object
util.isBoolean = (obj) -> obj is true or obj is false
util.isFunction = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is Function
util.isDate = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is Date
util.isRegExp = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is RegExp
util.isPlainObject = (obj) -> not not value and typeof value is 'object' and value.constructor is Object
util.isArguments = (obj) -> not (util.isUndefined(obj) or util.isNull(obj)) and obj.constructor is Arguments
util.isEmpty = (obj) ->
if util.isNull(obj) then return true
else if util.isString(obj) or util.isArray(obj) then return not obj.length
return false for key of obj when util.hasOwn(obj, key)
return true
util.isFinite = (obj) -> util.isNumber(obj) and obj isnt Infinity and obj isnt -Infinity
util.isNaN = (obj) -> obj isnt obj or not util.isNumber(obj)
util.toArray = (obj) ->
if not obj then return []
if obj.length is null or util.isString(obj) or util.isFunction(obj) or util.isRegExp(obj) or obj is util.GLOBAL then return [obj]
else
n = obj.length
result = []
result[n] = obj[n] while(--n)
return result
util.toNumber = (obj) ->
if util.isNumber(obj) then return obj
if not obj then return 0
if util.isString(obj) then return parseFloat(obj)
if util.isArray(obj) or util.isNaN(obj) then return NaN
Number(obj)
util.toString = (obj) ->
return if obj is null then '' else obj.toString()
String::capitalize = (index = 0) ->
halfResult = @charAt(index).toUpperCase() + @slice(index+1)
if halfResult.length is @length then return halfResult
@slice(0, index) + halfResult
util.Filesystem = ( ->
fsys = {}
inspect = require('util').inspect
assertPath = (path) -> if typeof path isnt 'string' then throw new TypeError('Path must be a string. Received ' + inspect(path))
_format = (sep, pathObject) ->
dir = pathObject.dir or pathObject.root
base = pathObject.base or ((pathObject.name or '') + (pathObject.ext or ''))
if not dir then return base
if dir is pathObject.root then return dir + base
return dir + sep + base
# Provides for path.posix not found in nodejs version 0.10
# Allows posix standard path management, which is prefered in this project
fsys.path = {
resolve: (args...) ->
resolvedPath = ''
resolvedAbsolute = false
cwd = undefined
`for (var i = args.length - 1 i >= -1 && !resolvedAbsolute i--) {
var path;
if(i>=0) path = args[i];
else {
if (cwd === undefined) cwd = process.cwd();
path = cwd;
}
assertPath(path);
if(path.length === 0) continue;
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charCodeAt(0) is 47/*/*/);
}`
resolvedPath = normalizeStringPosix(resolvedPath, not resolvedAbsolute)
if resolvedAbsolute
if resolvedPath.length > 0 then return "/#{resolvedPath}" else return '/'
else if resolvedPath.length > 0 then return resolvedPath else return '.'
normalize: (path) ->
assertPath(path)
if path.length is 0 then return '.'
`const isAbsolute = path.charCodeAt(0) is 47/*/*/;
const trailingSeparator = path.charCodeAt(path.length - 1) is 47/*/*/`
path = normalizeStringPosix(path, !isAbsolute)
if path.length is 0 and not isAbsolute then path = '.'
if path.length is 0 and trailingSeparator then path += '/'
if isAbsolute then return "/#{path}"
return path
isAbsolute: (path) ->
assertPath(path)
return path.length > 0 and path.charCodeAt(0) is 47
join: (args...) ->
if args.length is 0 then return '.'
joined = undefined
for i, arg in args
assertPath(arg)
if joined is undefined then joined = arg else joined += "#{joined}/#{arg}"
if joined is undefined then return '.'
return fsys.path.normalize(joined)
relative: (from, to) ->
assertPath(from)
assertPath(to)
if from is to then return ''
from = fsys.path.resolve(from)
to = fsys.path.resolve(to)
if from is to then return ''
fromStart = 1
break for fromStart in [fromStart..from.length] when from.charCodeAt(fromStart) isnt 47
fromEnd = from.length
fromLen = (fromEnd-fromStart)
toStart = 1
break for toStart in [toStart..to.length] when to.charCodeAt(toStart) isnt 47
toEnd = to.length
toLen = (toEnd-toStart)
length = if fromLen < toLen then fromLen else toLen
lastCommonSep = -1
i = 0
for i in [i..length]
if i is length
if toLen > length
if to.charCodeAt(toStart + i) is 47 then return to.slice(toStart+i+1)
else if i is 0 then to.slice(toStart+i)
else if fromLen > length
if from.charCodeAt(fromStart + i) is 47 then lastCommonSep = i
else if i is 0 then lastCommonSep = 0
break
fromCode = from.charCodeAt(fromStart + i)
toCode = to.charCodeAt(toStart + i)
if fromCode isnt toCode then break
else if fromCode is 47 then lastCommonSep = i
out = ''
for i in [fromStart+lastCommonSep+1..fromEnd]
if i is fromEnd or from.charCodeAt(i) is 47
if out.length is 0 then out += '..' else out += '/..'
if out.length > 0 then return out+to.slice(toStart+lastCommonSep)
else
toStart += lastCommonSep
if to.charCodeAt(toStart) is 47 then ++toStart
return to.slice(toStart)
dirname: (path) ->
assertPath(path)
if path.length is 0 then return '.'
code = path.charCodeAt(0)
hasRoot = code is 47
end = -1
matchedSlash = true
for i in [path.length-1..1]
code = path.charCodeAt(i)
if code is 47
if not matchedSlash
end = i
break
else matchedSlash = false
if end is -1 then return if hasRoot then '/' else '.'
if hasRoot and end is 1 then return '//'
return path.slice(0, end)
basename: (path, ext) ->
if ext isnt undefined and typeof ext isnt 'string' then throw new TypeError('"ext" argument must be a string')
assertPath(path)
start = 0
end = -1
matchedSlash = true
i = undefined
if ext isnt undefined and ext.length > 0 and ext.length <= path.length
if ext.length is path.length and ext is path then return ''
extIdx = ext.length - 1
firstNonSlashEnd = -1
for i in [path.length-1..0]
code = path.charCodeAt(i)
if code is 47
if not matchedSlash
start = i + 1
break
else
if firstNonSlashEnd is -1
matchedSlash = false
firstNonSlashEnd = i + 1
if extIdx >= 0
if code is ext.charCodeAt(extIdx)
if --extIdx is -1 then end = i
else
extIdx = -1
end = firstNonSlashEnd
if start is end then end = firstNonSlashEnd
else if end is -1 then end = path.length
return path.slice(start, end)
else
for i in [path.length-1..0]
if path.charCodeAt(i) is 47
if not matchedSlash
start = i + 1
break
else if end is -1
matchedSlash = false
end = i + 1
if end is -1 then return ''
return path.slice(start, end)
extname: (path) ->
assertPath(path)
startDot = -1
startPart = 0
end = -1
matchedSlash = true
preDotState = 0
for i in [path.length-1..0]
code = path.charCodeAt(i)
if code is 47
if not matchedSlash
startPart = i + 1
break
continue
if end is -1
matchedSlash = false
end = i + 1
if code is 46#.
if startDot is -1 then startDot = i
else if preDotState isnt 1 then preDotState = 1
else if startDot isnt -1 then preDotState = -1
if startDot is -1 or end is -1 or preDotState is 0 or (preDotState is 1 and startDot is end - 1 and startDot is startPart + 1) then return ''
return path.slice(startDot, end)
format: (pathObject) ->
if pathObject is null or typeof pathObject isnt 'object' then throw new TypeError("Parameter 'pathObject' must be an object, not #{typeof pathObject}")
return _format('/', pathObject)
parse: (path) ->
assertPath(path)
ret = { root: '', dir: '', base: '', ext: '', name: '' }
if path.length is 0 then return ret
code = path.charCodeAt(0)
isAbsolute = code is 47
start = undefined
if isAbsolute
ret.root = '/'
start = 1
else start = 0
startDot = -1
startPart = 0
end = -1
matchedSlash = true
i = path.length - 1
preDotState = 0
for i in [path.length-1..start]
code = path.charCodeAt(i)
if code is 47
if not matchedSlash
startPart = i + 1
break
continue
if end is -1
matchedSlash = false
end = i + 1
if code is 46#.
if startDot is -1 then startDot = i
else if preDotState isnt 1 then preDotState = 1
else if startDot isnt -1 then preDotState = -1
if startDot is -1 or end is -1 or (preDotState is 1 and startDot is end - 1 and startDot is startPart + 1)
if end isnt -1
if startPart is 0 and isAbsolute then ret.base = ret.name = path.slice(1, end)
else ret.base = ret.name = path.slice(startPart, end)
else
if startPart is 0 and isAbsolute
ret.name = path.slice(1, startDot)
ret.base = path.slice(1, end)
else
ret.name = path.slice(startPart, startDot)
ret.base = path.slice(startPart, end)
ret.ext = path.slice(startDot, end)
if startPart > 0 then ret.dir = path.slice(0, startPart - 1)
else if isAbsolute then ret.dir = '/'
return ret
sep: '/'
delimiter: ':'
win32: null
posix: null
}
fsys.cwd = -> PlatformShim.getScriptPath(true)
fsys.walk = (dir, finish) ->
results = []
fs.readdir(p.get(), (err, files) ->
if err then return finsh(err)
pending = files.length
if not pending then return finish(null, results)
files.forEach((file) ->
file = fsys.path.resolve(dir, file)
fs.stat(file, (err, stat) ->
if stat and stat.isDirectory() then walk(file, (err, res) ->
results = results.concat(res)
if not --pending then finish(null, results)
)
else
results.push(file)
if not --pending then return finish(null, results)
)
)
)
fsys.readJSONFile = (p) ->
if p.constructor isnt util.Path then p = new fsys.Path(path)
if p.isDirectory() then throw new TypeError("SDP.Util.Filesystem.readJSONFile can not operate on directories")
if p.extname() isnt '.json' then throw new TypeError("SDP.Util.Filesystem.readJSONFile only operates on JSON files")
result = null
fs.readFile(p.get(), (err, data) ->
if err then util.Logger.alert(err)
result = JSON.parse(data)
)
result
fsys.readJSONDirectory = (p, callback) ->
if p.constructor isnt util.Path then p = new fsys.Path(path)
if not p.isDirectory() then throw new TypeError("SDP.Util.Filesystem.readJSONDirectory can not operate on just files")
return fsys.walk(p.get(), (err, files) ->
if err then util.Logger.alert(err)
results = []
files.forEach((file) ->
pa = new fsys.Path(file)
json = fsys.readJSONFile(pa)
if pa.extname() is '.json' then results.push(json)
if util.isFunction(callback) then callback(json)
)
results
)
fsys.registerJSONFile = (p) ->
if p.constructor isnt util.Path then p = new fsys.Path(path)
if p.isDirectory() then throw new TypeError("SDP.Util.Filesystem.registerJSONFile can not operate on directories")
if p.extname() isnt '.json' then throw new TypeError("SDP.Util.Filesystem.registerJSONFile only operates on JSON files")
return util.registerJSONObject(fsys.readJSONFile(p))
fsys.registerJSONDirectory = (p) ->
if p.constructor isnt util.Path then p = new fsys.Path(path)
if not p.isDirectory() then throw new TypeError("SDP.Util.Filesystem.registerJSONDirectory can only operate on directories")
fsys.readJSONDirectory(p, (json) -> util.registerJSONObject(json))
class fsys.Path
constructor: (uri) ->
if util.isObject(uri) then uri = fsys.path.format(uri)
if uri is undefined then uri = fsys.cwd()
fsys.Path.check(uri)
@get = ->
fsys.Path.check(uri)
uri
@check: (uri) ->
if fsys.path.isAbsolute(uri) then throw new TypeError("SDP's Path may not store absolute paths")
if not fsys.path.resolve(uri).startsWith(fsys.cwd()) then throw new TypeError("SDP's Path may not leave the current working directory")
cd: (to) ->
uri = fsys.path.resolve(@get(), to)
fsys.Path.check(uri)
@get = ->
fsys.Path.check(uri)
uri
basename: (ext) ->
fsys.path.basename(@get(), ext)
dirname: ->
fsys.path.dirname(@get())
extname: ->
fsys.path.extname(@get())
parse: ->
fsys.path.parse(@get())
isFile: ->
fs.lstatSync(@get()).isFile()
isDirectory: ->
fs.lstatSync(@get()).isDirectory()
convert: ->
@get()
fsys
)()
util.registerJSONObject = (item) ->
if not util.isString(item.objectType) then throw new TypeError("SDP.Util.registerJSONObject can not work on items that don't contain an objectType field")
func = SDP.Functional["add#{item.objectType.capitalize()}Item"]
if not func
util.Logger.alert("SDP.Util.registerJSONObject could not find the function for objectType #{item.objectType}")
return
func(item)
util.getOverridePositions = (genre, category) ->
genre = genre.replace(/\s/g, "")
category = category.replace(/\s/g, "")
for g, i in SDP.Constants.Genre
if genre is g
if category is null then return [i]
for c, ci in SDP.Constants.ResearchCategory
if c is category then return [i, ci]
break
return undefined
util.fixItemNaming = (item, originalName, fixName) ->
if item[originalName]?
item[fixName] = item[originalName]
item[originalName] = undefined
item
class util.Image
constructor: (@uri) ->
@uri = null if not util.isString(@uri)
exists: ->
if @uri is null then return false
doesExist = true
fs.access(@uri, fs.constants.F_OK, (err) ->
if err then doesExist = false
)
doesExist
class util.Weight
constructor: (w1 = 0.8, w2 = w1, w3 = w2, w4, w5 = w4, w6 = w5) ->
if w1 is true or (not util.isNumber(w1) and not util.isArray(w1)) then @arr = [0.8,0.8,0.8]
else if w1 is false then @arr = [0.8,0.8,0.8,0.8,0.8,0.8]
else
if util.isArray(w1)
if w1.length > 3
w1.push(w1.last()) while w1.length < 6
else
w1.push(w1.last()) while w1.length < 3
@arr = w1
else
@arr = [w1,w2,w3]
if w4 then @arr.push(w4,w5,w6)
@arr[i] = num/100 for num, i in @arr when num > 1
@isGenre = -> @arr.length is 6
@isAudience = -> @arr.length is 3
get: (index) ->
if index is null then return @arr
@arr[index]
convert: ->
new Array(@arr)
class util.Date
START = '1/1/1'
END = '260/12/4'
constructor: (y = 1, m, w) ->
if util.isString(y)
[y,m,w] = m.split('/')
if util.isString(y) then [y,m,w] = m.split(' ')
if y is true then [y,m,w] = END.split('/')
if y is false then [y,m,w] = START.split('/')
if m is undefined then m = y
if w is undefined then w = m
@string = "#{y}/#{m}/#{w}"
convert: ->
new String(@string)
util.Error = ( ->
Error = {
logs: []
}
( ->
update = false
saving = false
Error.save = ->
if not saving
json = JSON.stringify(Error.logs)
saving = true
DataStore.saveToSlotAsync("SDP.Util.Error.logs", json, ->
saving = false
if update
update = false
Error.save()
, (m) -> saving = false )
else update = true
)()
Error.addErrorLog = (level, message, error) ->
if not error then error = {}
Error.logs.push {
date: (new Date()).toISOString()
level: level
msg: message
errorMsg: error.message
stacktrace: e.stack
number: e.number
}
if Error.logs.length > 100 then Error.logs.splice(0, errorLogs.length - 100)
Error.save()
Error
)()
util.Logger = ( ->
utilRequire = require('util')
logger = {
enabled: true
enableAlerts: true
formatter: logger.printf
show: 200
levels: {}
addLevel: (level, weight, sty, prefix = level) ->
if sty.constructor is style.FormattedStyle then sty = sty.getStyle()
logger.levels[level] = {
level: level
prefix: prefix
style: sty
weight: weight
format: (msg...) -> logger.format(level, msg...)
formatWithTime: (msg...) -> logger.formatWithTime(level, msg...)
log: (msg...) -> logger.log(level, msg...)
alert: (msg...) -> logger.alert(level, msg...)
}
if logger[level] is undefined then logger[level] = logger.levels[level].log
if logger["#{level}Alert"] is undefined then logger["#{level}Alert"] = logger.levels[level].alert
setShow: (level) ->
if level.constructor is Object then logger.show = level.weight
else if level.constructor is String then logger.show = logger.levels[level].weight
else logger.show = level
}
logger.addLevel('verbose', 0, { fg: 'blue', bg: 'black' }, 'VERBOSE')
logger.addLevel('debug', 100, { fg: 'blue'}, 'DEBUG')
logger.addLevel('info', 200, { fg: 'green'}, 'INFO')
logger.addLevel('warn', 300, { fg: 'black', bg: 'yellow' }, 'WARN')
logger.addLevel('error', 400, { fg: 'red', bg: 'black' }, 'ERROR')
logger.addLevel('fatal', 500, { fg: 'red', bg: 'black' }, 'FATAL')
stream = process.stderr
Object.defineProperty(logger, 'stream',
set: (newStream) ->
stream = newStream
style.stream = stream
get: -> stream
)
createTimestamp = (d) ->
formatNumbers = (n) -> if (n >= 0 and n < 10) then "0" + n else n + ""
[
[
formatNumbers(d.getFullYear())
formatNumbers(d.getMonth() + 1)
d.getDate()
].join("-")
[
formatNumbers(d.getHours())
formatNumbers(d.getMinutes())
formatNumbers(d.getHours())
].join(":")
].join("|")
logger.printf = {
formatWithTime: (level, msg...) ->
if logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
style.format(level.style, "[#{createTimestamp(new Date())}]#{level.prefix}: #{str.shift().format(msg...)}")
format: (level, msg...) ->
if logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
style.format(level.style, "#{level.prefix}: #{str.shift().format(msg...)}")
log: (level, msg...) ->
if not logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
if logger.enabled and logger.stream and logger.levels[level]?.weight >= logger.show
logger.stream.write(logger.printf.formatWithTime(level, msg))
alert: (level, msg...) ->
if not logger.levels[level]? then return "Level #{level} does not exist"
if logger.enabled and logger.enableAlerts and logger.levels[level]?.weight >= logger.show
string = if msg.length is 1 then msg[0] else str.shift().format(msg...)
PlatformShim.alert(string, logger.levels[level].prefix)
}
logger.format = {
formatWithTime: (level, msg...) ->
if logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
style.format(level.style, "[#{createTimestamp(new Date())}]#{level.prefix}: #{utilRequire.format(msg...)}")
format: (level, msg...) ->
if logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
style.format(level.style, "#{level.prefix}: #{utilRequire.format(msg...)}")
log: (level, msg...) ->
if not logger.levels[level]? then level = logger.levels[level]
if logger.levels.indexOf(level) is -1 then return "Level #{level} does not exist"
if logger.enabled and logger.stream and logger.levels[level]?.weight >= logger.show
logger.stream.write(logger.format.formatWithTime(level, msg))
alert: (level, msg...) ->
if not logger.levels[level]? then return "Level #{level} does not exist"
if logger.enabled and logger.enableAlerts and logger.levels[level]?.weight >= logger.show
string = if msg.length is 1 then msg[0] else utilRequire.format(msg...)
PlatformShim.alert(string, logger.levels[level].prefix)
}
logger.formatWithTime = (level, msg...) ->
logger.formatter.formatWithTime(level, msg...)
logger.format = (level, msg...) ->
logger.formatter.format(level, msg...)
logger.log = (level, msg...) ->
logger.formatter.log(level, msg...)
logger.alert = (level, msg...) ->
logger.formatter.alert(level, msg...)
logger
)()
util.Check = ( ->
Check = {
usePopups: true
}
Check.error = (msg) ->
try throw new Error(msg)
catch e
if Checks.usePopups then util.Logger.errorAlert(msg, e) else util.Logger.error(msg, e)
Error.addErrorLog("MODERROR", msg, e)
Check.audienceWeightings = (w) ->
if not w or w.length < 3 or w.some((v) -> return v < 0 or v > 1)
Check.error('audience weigthing is invalid: %s', w)
return false
return true
Check.genreWeightings = (w) ->
if not w or w.length < 6 or w.some((v) -> return v < 0 or v > 1)
Check.error('genre weigthing is invalid: %s', w)
return false
return true
Check.missionOverrides = (overrides) ->
if overrides.length < 6 or overrides.some((o) -> o.length < 6 or o.some((w) -> w > 1 or w < 0))
Check.error('invalid missionOverrides: %s', w)
return false
return true
Check.date = (date) ->
if date and date.split
v = date.split('/')
if v and v.length is 3 and not v.some((t) -> t < 1) and v[1] <= 12 and v[2] <= 4 then return true
Check.error('date invalid: %s', date)
return false
Check.propertiesPresent = (obj, props) ->
if not obj then return false
if not props then return true
for p in props
if not p or p.length < 1 then continue
if not obj.hasOwnProperty(p)
Check.error('property not set on object: %s', p)
return false
return true
Check.uniqueness = (obj, prop, values, ignoreErr) ->
if values.some((v) -> v[prop] is obj[prop])
if not ignoreErr then Check.error('duplicate value for %s found: %s', prop, obj[prop])
return false
return true
Check
)()
util
)()
# @namespace Constants
#
# The constants of the SPD
SDP.Constants = {
# Categories of development
ResearchCategory: [
'Engine'
'Gameplay'
'Story/Quests'
'Dialogs'
'Level Design'
'AI'
'World Design'
'Graphic'
'Sound'
]
# Audiences to target
Audience: [
'young'
'everyone'
'mature'
]
# Genres to choose for games
Genre: [
'Action'
'Adventure'
'RPG'
'Simulation'
'Strategy'
'Casual'
]
}
# @namespace Functional
#
# Contains the function interface for the SDP
SDP.Functional = {}
# Registers a Research item
#
# @param [ResearchItem] item The item to register
SDP.Functional.addResearchItem = (item) ->
Checks = SDP.Util.Check
unless item.type? then item.type = 'engine'
if item.type is 'engine' and item.engineStart then item.canResearch = -> false
requirments = ['id', 'name', 'category', 'categoryDisplayName']
if item.v? then requirements.push('pointsCost','duration','researchCost','engineCost') else requirements.push('v')
if Checks.propertiesPresent(item, requirements) and Checks.uniqueness(item, 'id', SDP.GDT.Research.getAll())
SDP.GDT.Research.researches.push(item)
Research.engineItems.push(item)
return
SDP.Functional.addStartResearch = (item) ->
item.type = 'start'
SDP.Functional.addResearchItem(item)
SDP.Functional.addBasicResearch = (item) ->
item.type = 'basic'
SDP.Functional.addResearchItem(item)
SDP.Functional.addEngineResearch = (item) ->
item.type = 'engine'
SDP.Functional.addResearchItem(item)
SDP.Functional.addSpecialResearch = (item) ->
item.type = 'special'
SDP.Functional.addResearchItem(item)
# Registers a Platform item
#
# @param [PlatformItem] item The item to register
SDP.Functional.addPlatformItem = (item) ->
Checks = SDP.Util.Check
fix = SDP.Util.fixItemNaming
fix(item, 'licensePrice','licencePrize')
fix(item, 'publishDate', 'published')
fix(item, 'retireDate', 'platformRetireDate')
fix(item, 'devCosts', 'developmentCosts')
fix(item, 'genreWeight', 'genreWeightings')
fix(item, 'audienceWeight', 'audienceWeightings')
fix(item, 'marketPoints', 'marketKeyPoints')
if Checks.propertiesPresent(item, ['id', 'name', 'company', 'startAmount', 'unitsSold', 'licencePrize', 'published', 'platformRetireDate', 'developmentCosts', 'genreWeightings', 'audienceWeightings', 'techLevel', 'baseIconUri', 'imageDates']) and Checks.uniqueness(item, 'id', SDP.GDT.Platform.getAll()) and Checks.audienceWeightings(item.audienceWeightings) and Checks.genreWeightings(item.genreWeightings) and Checks.date(item.published) and Checks.date(item.platformRetireDate)
if item.marketKeyPoints then for point in item.marketKeyPoints
return unless Checks.date(point.date)
###
if Checks.checkUniqueness(item.name, 'name', Companies.getAllCompanies())
SDP.GDT.addCompany(item.name).addPlatform(item)
else
###
SDP.GDT.Platform.platforms.push(item)
if item.events then for event of item.events
GDT.addEvent(event)
return
# Registers a Topic item
#
# @param [TopicItem] item The item to register
SDP.Functional.addTopicItem = (item) ->
Checks = SDP.Util.Check
fix = SDP.Util.fixItemNaming
fix(item, 'genreWeight', 'genreWeightings')
fix(item, 'audienceWeight', 'audienceWeightings')
fix(item, 'overrides', 'missionOverrides')
if Checks.propertiesPresent(t, ['name', 'id', 'genreWeightings', 'audienceWeightings']) and Checks.audienceWeightings(t.audienceWeightings) and Checks.genreWeightings(t.genreWeightings) and Checks.uniqueness(t, 'id', SDP.GDT.Topic.getAll(), true)
SDP.GDT.Topic.topics.push(item)
return
SDP.Functional.addTopicItems = (list...) ->
if list.length is 1
list = list[0]
if not SDP.Util.isArray(list) then return SDP.Functional.addTopicItem(list)
SDP.Functional.addTopicItem(item) for item in list
# Registers a Research Project item
#
# @param [ResearchProjectItem] item The item to register
SDP.Functional.addResearchProjectItem = (item) ->
Checks = SDP.Util.Check
unless item.canResearch? then item.canResearch = ((company)->true)
if Checks.propertiesPresent(item, ['id', 'name', 'pointsCost', 'iconUri', 'description', 'targetZone']) and Checks.uniqueness(item, 'id', SDP.GDT.ResearchProject.getAll())
SDP.GDT.ResearchProject.projects.push(item)
return
SDP.Functional.addResearchProject = (item) -> SDP.Functional.addResearchProjectItem(item)
# Registers a Training item
#
# @param [TrainingItem] item The item to register
SDP.Functional.addTrainingItem = (item) ->
Checks = SDP.Util.Check
unless item.canSee? and item.canUse? then item.canSee = (staff, company) -> true
if Checks.propertiesPresent(item, ['id', 'name', 'pointsCost', 'duration', 'category', 'categoryDisplayName']) and Checks.uniqueness(item, 'id', SDP.GDT.Training.getAll())
SDP.GDT.Training.trainings.push(item)
return
# Registers a Contract item
#
# @param [ContractItem] item The item to register
SDP.Functional.addContractItem = (item) ->
Checks = SDP.Util.Check
if Checks.propertiesPresent(item, ['id', 'name', 'description', 'tF', 'dF']) and Checks.uniqueness(item, 'id', SDP.GDT.Contract.getAll())
SDP.GDT.Contract.contracts.push(item)
return
# Registers a Publisher item
#
# @param [PublisherItem] item The item to register
SDP.Functional.addPublisherItem = (item) ->
Checks = SDP.Util.Check
if Checks.propertiesPresent(item, ['id', 'name']) and Checks.uniqueness(item, 'id', SDP.GDT.Publisher.getAll())
SDP.GDT.Publisher.publishers.push(item)
return
# Registers a Reviewer item
#
# @param [ReviewerItem] item The item to register
###
SDP.Functional.addReviewerItem = (item) ->
Checks = SDP.Util.Check
if Checks.propertiesPresent(item, ['id', 'name']) and Checks.uniqueness(item, 'id', SDP.GDT.Review.getAll())
SDP.GDT.Review.reviewer.push(item)
return
###
SDP.Functional.addEvent = (event) ->
Checks = SDP.Util.Check
unless Checks.propertiesPresent(event, ['id']) and (event.notification or event.getNotification) then return
unless Checks.checkUniqueness(event, 'id', GDT.Event.getAll()) then return
# hacks in runningCompany to events because event.complete does not supply one, and overriding the UI system is a bit much for now
oldTrigger = event.trigger
event.trigger = (company) ->
result = oldTrigger(company)
@runningCompany = company if result and event.complete?
result
GDT.Event.events.push(event)
# Adds a notification to the triggering queue
#
# @param [NotificationItem] item The item to queue
SDP.Functional.addNotificationToQueue = (item) ->
if SDP.Util.isString(item)
item = item.split('\n')
if item.length is 1 then item = item[0].split(':')
if item.length is 1 then item = item[0].split(';')
item.forEach((e, i) -> item[i] = e.trim())
item = {
header: item[0]
text: item[1]
buttonText: item[2]
}
item.header = '?' unless item.header?
item.text = '?' unless item.text?
if not item instanceof Notification
item = new Notification {
header: item.header
text: item.text
buttonText: item.buttonText
weeksUntilFired: item.weeksUntilFired
image: item.image
options: item.options.slice(0, 3)
sourceId: item.sourceId
}
if GameManager?.company?.notifications? then GameManager.company.notifications.push(item) else SDP.GDT.Notification.queue.push(item)
SDP.Class = (
classes = {}
convertClasses = (classObj) ->
switch classObj.constructor
when SDP.Util.Date, SDP.Util.Weight, SDP.Util.Filesystem.Path then return classObj.convert()
when Array
classObj[i] = convertClasses(classObj[i]) for i of classObj
return classObj
else return classObj
class Base
constructor: (args...) ->
if SDP.Util.isObject(args[0])
@[arg] = args[0][arg] for arg in args[0] when args[0].hasOwnProperty(arg)
@wasNativeObject = true
else @wasNativeObject = false
@id ?= @name
class classes.Research extends Base
constructor: (@name, @type, @category, @categoryDisplayName = @category, @id) ->
super
convert: ->
item = {
name: @name
id: @id
type: @type
v: @v
pointsCost: @pointsCost
duration: @duration
researchCost: @researchCost
devCost: @devCost
engineCost: @engineCost
enginePoints: @enginePoints
category: @category
categoryDisplayName: @categoryDisplayName
group: @group
consolePart: @consolePart
engineStart: @engineStart
canUse: if @canUse? then @canUse.bind(item) else undefined
canResearch: if @canResearch? then @canResearch.bind(item) else undefined
}
class classes.Platform extends Base
constructor: (@name, @company, @id = @name) ->
super
@startAmount ?= 0
@unitsSold ?= 0
@audienceWeight ?= new SDP.Util.Weight(true)
@genreWeight ?= new SDP.Util.Weight(false)
@licensePrice ?= 0
@publishDate ?= new SDP.Util.Date(false)
@retireDate ?= new SDP.Util.Date(true)
@devCost ?= 0
@techLevel ?= 0
@iconUri ?= new SDP.Util.Filesystem.Path()
convert: ->
{
name:PI:NAME:<NAME>END_PI @PI:NAME:<NAME>END_PI
id: @id
company: @company
startAmount: @startAmount
unitsSold: @unitsSold
licensePrice: @licensePrice
publishDate: convertClasses(@publishDate)
retireDate: convertClasses(@retireDate)
genreWeight: convertClasses(@genreWeight)
audienceWeight: convertClasses(@audienceWeight)
techLevel: @techLevel
iconUri: convertClasses(@iconUri)
imageDates: convertClasses(@imageDates)
marketPoints: convertClasses(@marketPoints)
}
class classes.Topic extends Base
BASE_OVERRIDE = [0,0,0,0,0,0,0,0,0]
constructor: (@name, @id) ->
super
@audienceWeight ?= new SDP.Util.Weight(true)
@genreWeight ?= new SDP.Util.Weight(false)
if not @overrides? or not SDP.Util.isArray(@overrides)
@overrides = [BASE_OVERRIDE,BASE_OVERRIDE,BASE_OVERRIDE,BASE_OVERRIDE,BASE_OVERRIDE,BASE_OVERRIDE]
@overrides.push(BASE_OVERRIDE) while @overrides.length < 6
o.push(0) for o in @overrides when o.length < 9
setOverride: (genreName, catName, value) ->
if SDP.Util.isArray(genreName)
@overrides = genreName
return @
if SDP.Util.isArray(catName) then value = catName
catOrNull = if value isnt catName and (SDP.Util.isString(catName) or SDP.Util.isInteger(catName)) then catName else null
positions = SDP.Util.getOverridePositions(genreName, catOrNull)
if value is catName
@overrides[positions[0]] = value
else
@overrides[positions[0]][positions[1]] = value
@
convert: ->
{
name:PI:NAME:<NAME>END_PI @PI:NAME:<NAME>END_PI
id: @id
genreWeight: convertClasses(@genreWeight)
audienceWeight: convertClasses(@audienceWeight)
overrides: @overrides
}
class classes.ResearchProject extends Base
constructor: (@name, @description, @id) ->
super
@pointsCost ?= 0
@iconUri ?= new SDP.Util.Filesystem.Path()
@targetZone ?= 2
convert: ->
item = {
name:PI:NAME:<NAME>END_PI @PI:NAME:<NAME>END_PI
id: @id
description: @description
pointsCost: @pointsCost
iconUri: convertClasses(@iconUri)
targetZone: @targetZone
repeatable: @repeatable
canResearch: if @canResearch? then @canResearch.bind(item) else undefined
complete: if @complete? then @complete.bind(item) else undefined
cancel: if @cancel? then @cancel.bind(item) else undefined
}
class classes.Training extends Base
constructor: (@name, @category, @categoryDisplayName = @category, @id) ->
super
@pointsCost ?= 0
@duration ?= 0
convert: ->
item = {
name:PI:NAME:<NAME>END_PI @PI:NAME:<NAME>END_PI
id: @id
cost: @cost
pointsCost: @pointsCost
category: @category
categoryDisplayName: @categoryDisplayName
canSee: if @canSee? then @canSee.bind(item) else undefined
canUse: if @canUse? then @canUse.bind(item) else undefined
tick: if @tick? then @tick.bind(item) else undefined
complete: if @complete? then @complete.bind(item) else undefined
}
class classes.Contract extends Base
constructor: (@name, @size, @description, @id) ->
super
@tF ?= 0
@dF ?= 0
convert:
item = {
name:PI:NAME:<NAME>END_PI @PI:NAME:<NAME>END_PI
id: @id
size: @size
description: @description
tF: @tF
dF: @dF
card: @card
generateCard: if @generateCard? then @generateCard.bind(item) else undefined
rF: @rF
}
class classes.Publisher extends Base
constructor: (@PI:NAME:<NAME>END_PI, @id) ->
super
convert: ->
item = {
name:PI:NAME:<NAME>END_PI @PI:NAME:<NAME>END_PI
id: @id
card: @card
generateCard: if @generateCard? then @generateCard.bind(item) else undefined
}
class classes.Event extends Base
constructor: (@id, @isRandomEvent) ->
super
@trigger ?= (company) -> false
convert: ->
item = {
id: @id
isRandomEvent: @isRandomEvent
notification: @notification
trigger: @tigger.bind(item)
getNotification: if @getNotification? then @getNotification.bind(item) else undefined
complete: if @complete? then @complete.bind(item) else undefined
}
)()
SDP.GDT = ( ->
GDT = {}
GDT.Company = {
companies: {}
clientUid: undefined
addCompany: (company) ->
if not company.uid then company.uid = GameManager.getGUID()
GDT.Company.companies[company.uid] = company
if company is GameManager.company then clientUid = company.uid
containsCompany: (company) -> companies[company.uid or company]?
getCompanies: -> GDT.Company.companies.slice()
getClientCompany: -> GDT.Company.companies[GDT.Company.clientUid]
getPlatformsFor: (company, includeInactive) ->
if includeInactive then return GDT.Platform.getAll().concat(company.licencedPlatforms)
company.availablePlatforms.concat(company.licencedPlatforms)
getByUid: (uid) -> GDT.Company.companes[uid]
}
Platforms.getPlatforms = GDT.Company.getPlatformsFor
oldResearchGetAll = Research.getAllItems
GDT.Research = {
researches: oldResearchGetAll().forEach((r) ->
switch r.category
when 'General' then r.type = 'basic'
when 'Game Design', 'Project Management', 'Technology', 'Publishing' then r.type = 'special'
else r.type = 'engine'
if r.id is 'Text Based' or r.id is '2D Graphics V1' or r.id is 'Basic Sound' then r.type = 'start'
if r.id is '2D Graphics V2' or r.id is 'Linear story' or r.id is 'Savegame' then r.engineStart = true
)
# start research is accessible without an engine
# basic research are researches that do not pertain specifically to engines
# engine research are researches that do pertain to engines
# special research is basically the misc, where it would fit nowhere else, for example Marketing
types: ['start', 'basic', 'engine', 'special']
getAll: -> GDT.Research.researches.concat(oldResearchGetAll().except(GDT.Research.researches))
getAvailable: (company, engine) -> GDT.Research.getAll().filter((r) ->
if r.type is 'start' then return true
if engine and engine.parts.first((e) -> e.id is r.id)? then return true
if r.enginePoints is 0 and company.researchCompleted.indexOf(r) isnt -1 then return true
if company.specialItems.indexOf(r) isnt -1 then return true
false
)
getAvailableEngineParts: (company) ->
if company.canDevelopEngine() then return GDT.Research.getAll().filter((r) ->
if r.engineStart then return true
if r.type is 'start' or r.type is 'basic' then return false
Research.getEnginePoints(r) isnt 0 and (Research.getEngineCost(r) isnt 0 and company.researchCompleted.indexOf(r) isnt -1)
)
[]
addSpecialItem: (company, idOrObj) -> company.specialItems.push(if SDP.Util.isString(idOrObj) then GDT.Researches.getAll().first((r) -> r.id is idOrObj) else idOrObj)
removeSpecialItem: (company, idOrObj) -> company.specialItems.remove(if SDP.Util.isString(idOrObj) then GDT.Researches.getAll().first((r) -> r.id is idOrObj) else idOrObj)
getById: (id) -> GDT.Research.getAll().first((r) -> r.id is id)
}
Research.getAllItems = GDT.Research.getAll
( ->
oldResearchPointsCost = Research.getPointsCost
Research.getPointsCost = (r) ->
if r.pointsCost then return r.pointsCost
return oldResearchPointsCost(r)
oldResearchDuration = Research.getDuration
Research.getDuration = (r) ->
if r.duration then return r.duration
return oldResearchDuration(r)
oldResearchDevCost = Research.getDevCost
Research.getDevCost = (r, game) ->
if r.devCost
value = r.devCost
if game
value *= General.getGameSizeDurationFactor(game.gameSize) * General.getMultiPlatformCostFactor(game)
value = Math.floor(value / 1e3) * 1e3
return value
return oldResearchDevCost(r, game)
oldResearchResearchCost = Research.getResearchCost
Research.getResearchCost = (r) ->
if r.researchCost then r.researchCost
return oldResearchResearchCost(r)
oldResearchEngineCost = Research.getEngineCost
Research.getEngineCost = (r) ->
if r.engineCost then return r.engineCost
return oldResearchEngineCost(r)
)()
GameManager.getAvailableGameFeatures = GDT.Research.getAvailable
General.getAvailableEngineParts = GDT.Research.getAvailableEngineParts
( ->
oldPlatformImage = Platforms.getPlatformImage
GDT.Platform = {
platforms: Platforms.allPlatforms
getAll: -> GDT.Platform.platforms.slice()
getAvailable: (company) ->
GDT.Company.getPlatformsFor(company).filter((p) ->
Platforms.getRetireDate(p) > Math.floor(company.currentWeek) and not p.isCustom or p.isCustom is true and (company.currentWeek > General.getWeekFromDateString(p.published) and not p.soldOut)
)
getImage: (platform, week) ->
if platform.id is 'PC' then return oldPlatformImage(platform, week)
if not platform.imageDates then return platform.iconUri
else if week
image = "{0}/{1}-{2}.png".format(baseUri, platform.id, String(i+1)) for date, i in platform.imageDates when General.getWeekFromDateString(date) <= week and i isnt 0
if not image then return "{0}/{1}.png".format(baseUri, platform.id) else return image
getById: (id) -> GDT.Platform.getAll().first((p) -> p.id is id)
}
Platforms.getPlatformsOnMarket = GDT.Platform.getAvailable
Platforms.getPlatformImage = GDT.Platform.getImage
)()
GDT.Topic = {
topics: Topics.topics
_topicBackup: JSON.parse(JSON.stringify(GDT.Topic.topics))
getAll: -> GDT.Topic.topics.slice()
getById: (id) -> GDT.Topic.getAll().first((t) -> t.id is id )
reset: (id) ->
index = GDT.Topic.topics.indexOf(GDT.Topic.getById(id))
if index isnt -1 then GDT.Topic.topics[index] = JSON.parse(JSON.stringify(GDT.Topic._topicBackup[index]))
}
GDT.ResearchProject = {
projects: Research.bigProjects
getAll: -> GDT.ResearchProject.projects.slice()
getAvailable: (company, zone) ->
GDT.ResearchProject.getAll().filter((p) ->
p.targetZone is zone and p.canResearch(company)
)
getById: (id) -> GDT.ResearchProject.getAll().first((r) -> r.id is id)
}
General.getAvailableProjects = GDT.ResearchProject.getAvailable
GDT.Training = {
trainings: Training.getAllTrainings()
getAll: ->
results = []
for item in GDT.Training.trainings.slice()
if item.id? and (item.pointsCost? and item.duration?)
item.isTraining = true
results.push(item)
results
getAvailable: (staff) ->
results = []
for t in GDT.Training.getAll()
results.push(t) if (t.canSee and t.canSee(staff, staff.company) or not t.canUse?) or (not t.canSee and t.canUse(staff, staff.company))
results
getById: (id) -> GDT.Training.getAll().first((t) -> t.id is id)
}
Training.getAllTrainings = GDT.Training.getAll
Training.getAvailableTraining = GDT.Training.getAvailable
# To prevent namespace clutter, stuck the contract stuff in a seperate function block
( ->
`var smallContracts = [{
name: "Logo Animation".localize("heading"),
description: "Create an animation for an existing logo.".localize(),
tF: 1,
dF: 2.5,
rF: 1.5
}, {
name: "Character Design".localize("heading"),
description: "Design some game characters.".localize(),
tF: 1,
dF: 4.5,
rF: 1.5
}, {
name: "Playtest".localize("heading"),
description: "Help to playtest a game.".localize(),
tF: 1,
dF: 1,
rF: 1.5
}, {
name: "Game Backdrops".localize("heading"),
description: "Design some simple background graphics for a game.".localize(),
tF: 1,
dF: 2,
rF: 1.5
}, {
name: "Setup Computers".localize("heading"),
description: "Install Mirconoft BOSS on computers".localize(),
tF: 2,
dF: 0.4
}, {
name: "Debug program".localize("heading"),
description: "Help debugging a convoluted BASE program.".localize(),
tF: 2,
dF: 0.2
}, {
name: "Spritesheet Software".localize("heading"),
description: "Our staff needs to be taught how to use these modern technologies.".localize(),
tF: 3,
dF: 2
}, {
name: "Library Software".localize("heading"),
description: "Develop a simple library management system".localize(),
tF: 5,
dF: 1
}];
var mediumContracts = [{
name: "Usability Study".localize("heading"),
description: "Perform a detailed usability study.".localize(),
tF: 5,
dF: 6.5
}, {
name: "Review Game Concept".localize("heading"),
description: "Review a game concept using your expertise.".localize(),
tF: 3,
dF: 8,
rF: 1.5
}, {
name: "Game Art".localize("heading"),
description: "Help out on a project with some game art".localize(),
tF: 5,
dF: 6,
rF: 1.5
}, {
name: "Clean up database".localize("heading"),
description: "Should one table really have 200 columns? Probably not.".localize(),
tF: 5,
dF: 1
}, {
name: "Accounting Software".localize("heading"),
description: "Develop a simple accounting software. Are those ever simple?".localize(),
tF: 5,
dF: 1
}, {
name: "Time Tracking".localize("heading"),
description: "Design and develop a time tracking system.".localize(),
tF: 3,
dF: 1
}, {
name: "Design a board game".localize("heading"),
description: "Let's see how your skills translate to traditional games.".localize(),
dF: 5,
tF: 0.2,
rF: 2
}, {
name: "Horoscope Generator".localize("heading"),
description: "Making up horoscopes is hard work. We want it automated.".localize(),
dF: 5,
tF: 1
}, {
name: "Character Dialogues".localize("heading"),
description: "Improve our character dialogues.".localize(),
dF: 5,
tF: 1,
rF: 1.4
}, {
name: "Futuristic Application".localize("heading"),
description: "We need an application that looks futuristic for a movie.".localize(),
dF: 3,
tF: 2,
rF: 1.5
}, {
name: "Vacuum Robot".localize("heading"),
description: "Create a revolutionary AI for a vacuum robot".localize(),
tF: 2,
dF: 1.4
}, {
name: "Website".localize("heading"),
description: "We just heard of this thing called internet. We want to have one.".localize(),
tF: 2,
dF: 1.3
}];
var largeContracts = [{
name: "Game Port".localize("heading"),
description: "Port a game to a different platform.".localize(),
tF: 3.2,
dF: 1.7,
rF: 1.2
}, {
name: "Cut Scenes".localize("heading"),
description: "Deliver professional cut scenes for a game.".localize(),
tF: 1,
dF: 1,
rF: 1.5
}, {
name: "Space Shuttle".localize("heading"),
description: "Deliver part of the space shuttle control software.".localize(),
tF: 3,
dF: 2
}, {
name: "Alien Search".localize("heading"),
description: "Optimize our search for alien life forms using advanced AI techniques.".localize(),
tF: 3,
dF: 1.8,
rF: 1.3
}, {
name: "Movies".localize("heading"),
description: "We need your skills in our latest blockbuster production.".localize(),
tF: 1,
dF: 1,
rF: 1.5
}]`
GDT.Contract = {
contracts: []
getAll: -> GDT.Contract.contracts.slice()
getAvailable: (company) ->
results = []
for c in GDT.Contract.getAll().filter((contract) -> not contract.isAvailable? or contract.isAvailable(company))
results.push(c)
results
getSettings: (company, size) ->
key = "PI:KEY:<KEY>END_PI
settings = company.flags[key]
if not settings
settings = {id:key}
company.flags[key] = settings
settings
getSeed: (settings) ->
newSeed = ->
settings.seed = Math.floor(Math.random() * 65535);
settings.expireBy = GameManager.gameTime + 24 * GameManager.SECONDS_PER_WEEK * 1e3;
settings.contractsDone = []
if not settings.seed
newSeed()
settings.intialSettings = true
else if settings.expireBy <= GameManager.gameTime
newSeed()
settings.intialSettings = false
settings.seed
createFromTemplate: (company, template, random) ->
item = if template.generateCard? then template.generateCard(company, random) else template.card
r = random.random()
if random.random > 0.8 then r+= random.random()
t = undefined
d = undefined
pay = undefined
weeks = undefined
penalty = undefined
if item.techPoints then t = item.techPoints
if item.designPoints then d = item.designPoints
if item.payment then pay = item.payment
if item.weeks then weeks = item.weeks
if item.penalty then penalty = item.penalty
unless t and d and pay and weeks and penalty
minPoints = undefined
tF = template.tF or item.tF
dF = template.dF or item.dF
unless t and d and not item.minPoints then minPoints = item.minPoints else
minPoints = switch template.size
when 'small' then 11
when 'medium' then 30
when 'large' then 100
minPoints += 6 if minPoints is 12 and company.staff.length > 2
minPoints += minPoints * (company.getCurrentDate().year / 25)
points = minPoints + minPoints * r
pointPart = points / (dF + tF)
unless d
d = pointPart * dF
d += d * 0.2 * random.random() * random.randomSign()
d = Math.floor(d)
unless t
t = pointPart * tF
t += t * 0.2 * random.random() * random.randomSign()
t = Math.floor(t)
unless pay then pay = Math.floor(points*1e3/1e3) * 1e3
unless weeks then (weeks = if template.size is small then Math.floor(3 + 3 * random.random()) else Math.floor(3 + 7 * random.random()))
unless penalty then penalty = Math.floor((pay * 0.2 + pay * 0.3 * random.random())/1e3) * 1e3
contractObject = {
name: template.name
description: template.description
id: 'genericContracts'
requiredD: d
requiredT: t
spawnedD: 0
spawnedT: 0
payment: pay
penalty: -penalty
weeksToFinish: weeks
rF: template.rF
isGeneric: true
size: template.size
complete: if template.complete? then template.complete.bind(contractObject) else undefined
}
generate: (company, size, max) ->
settings = GDT.Contract.getSettings(company, size)
random = new MersenneTwister(GDT.Contract.getSeed(settings))
count = Math.max(max - 1, Math.floor(random.random() * max))
results = []
set = GDT.Contract.getAvailable(company).filter((e) -> e.size is size)
if settings.initialSettings then count = Math.max(1, count)
i = 0
while i < count and set.length > 0
item = set.pickRandom(random)
set.remove(item)
contractInstance = GDT.Contract.createFromTemplate(company, item, random)
contractInstance.index = i
if settings.contractsDone and settings.contractsDone.indexOf(i) isnt -1
contract.skip = true
contracts.push(contract)
i++
contracts
getList: (company) ->
settings = GDT.Contract.getSettings(company, 'small')
results = GDT.Contract.generate(company, 'small', 4)
if company.flags.mediumContractsEnabled then results.addRange(GDT.Contract.generate(company, 'medium', 3))
if company.flags.largeContractsEnabled then results.addRange(GDT.Contract.generate(company, 'large', 2))
results.shuffle(new MersenneTwister(GDT.Contract.getSeed(settings))).filter((c) -> not c.skip)
getById: (id) -> GDT.Contract.getAll().first((c) -> c.id is id)
}
generateConvertContracts = (type) ->
(e) ->
e.size = type
e.id = e.name.replace(' ', '')
smallContracts.forEach(generateConvertContracts('small'))
mediumContracts.forEach(generateConvertContracts('medium'))
largeContracts.forEach(generateConvertContracts('large'))
GDT.Contract.contracts.addRange(smallContracts)
GDT.Contract.contracts.addRange(mediumContracts)
GDT.Contract.contracts.addRange(largeContracts)
ProjectContracts.generateContracts.getContract = GDT.Contract.getList
oldContractsComplete = ProjectContracts.genericContracts.complete
ProjectContracts.genericContracts.complete = (company, success, data) ->
contract.complete?()
oldContractsComplete(company, success, data)
)()
( ->
`var publishers = [{
id: "ActiveVisionaries",
name: "Active Visionaries"
}, {
id: "ea",
name: "Electronic Mass Productions"
}, {
id: "RockvilleSoftworks",
name: "Rockville Softworks"
}, {
id: "BlueBitGames",
name: "Blue Bit Games"
}, {
id: "CapeCom",
name: "CapeCom"
}, {
id: "Codemeisters",
name: "Codemeisters"
}, {
id: "DeepPlatinum",
name: "Deep Platinum"
}, {
id: "InfroGames",
name: "InfroGames"
}, {
id: "LoWoodProductions",
name: "LoWood Productions"
}, {
id: "TGQ",
name: "TGQ"
}, {
id: "\u00dcberSoft",
name: "\u00dcberSoft"
}]`
GDT.Publisher = {
publishers: publishers.slice()
getAll: -> GDT.Publisher.publishers.slice()
getAvailable: (company) ->
results = []
for p in GDT.Publisher.getAll().filter((publisher) -> not publisher.isAvailable? or publisher.isAvailable(company))
results.push(p)
results
generate: (company, max) ->
settings = GDT.Contract.getSettings(company, 'publisher')
seed = GDT.Contract.getSeed(settings)
random = new MersenneTwister(seed)
count = Math.max(max - 1, Math.floor(random.random() * max))
results = []
if settings.seed isnt seed
settings.topics = undefined
settings.researchedTopics = undefined
settings.excludes = undefined
settings.platforms = undefined
if not settings.topics or (not settings.researchedTopics or not settings.platforms)
topics = company.topics.slice()
topics.addRange(General.getTopicsAvailableForResearch(company))
settings.topics = topics.map((t) ->
t.id
)
researchedTopics = company.topics.map((t) ->
t.id
)
settings.researchedTopics = researchedTopics
platforms =
Platforms.getPlatformsOnMarket(company).filter((p) ->
not p.isCustom and Platforms.doesPlatformSupportGameSize(p, "medium")
)
settings.platforms = platforms.map((p) ->
p.id
)
settings.excludes = []
lastGame = company.gameLog.last()
if lastGame
settings.excludes.push {
genre: lastGame.genre.id
topic: lastGame.topic.id
}
else
topics = settings.topics.map((id) ->
Topics.topics.first((t) ->
t.id is id
)
)
researchedTopics = settings.researchedTopics.map((id) ->
Topics.topics.first((t) ->
t.id is id
)
)
allPlatforms = Platforms.getPlatforms(company, true);
platforms = settings.platforms.map((id) ->
allPlatforms.first((p) ->
p.id is id
)
)
excludes = settings.excludes.slice()
count = Math.max(max - 1, Math.floor(random.random() * max))
if settings.initialSetting then count = Math.max(1, count)
sizes = ['medium']
if company.canDevelopLargeGames() then sizes.addRange(["large", "large", "large"])
audiences = ["young", "everyone", "mature"]
sizeBasePay = { medium: 15e4, large: 15e5 / 2 }
for i in [0..count]
publisher = GDT.Publisher.getAvailable(company).pickRandom(random)
if publisher.generateCard or publisher.card
item = if publisher.generateCard? then publisher.generateCard(company) else publisher.card
if item and (item.size is 'small' or company["canDevelop#{item.size.capitalize()}Games"]?())
topic = item.topic
genre = item.genre
platform = item.platform
name = "#{if topic then topic.name else 'Any Topic'.localize()} / #{if genre then genre.name else 'Any Genre'.localize()}"
results.push contract = {
id: 'publisherContracts'
refNumber: Math.floor(Math.random() * 65535)
type: 'gameContract'
name: name
description: "Publisher: #{publisher.name}"
publisher: publisher.name
publisherObject: publisher
topic: if topic then topic.id else topic
genre: if genre then genre.id else genre
platform: if platform.id then platform.id else platform
gameSize: item.size,
gameAudience: item.audience,
minScore: item.minScore,
payment: item.pay,
penalty: item.penalty,
royaltyRate: item.royaltyRate
complete: if item.complete? then item.complete.bind(contract) else if publisher.complete then publisher.complete.bind(contract) else undefined
}
continue
diffculty = 0
topic = undefined
genre = undefined
if random.random() <= 0.7
genre = General.getAvailableGenres(company).pickRandom(random)
diffculty += 0.1
if random.random() <= 0.7
`do {
if (random.random() <= 0.7)
topic = topics.except(researchedTopics).pickRandom(random);
else
topic = topics.pickRandom(random);
if (topic === undefined)
break
} while (excludes.some(function (e) {
return (genre === undefined || e.genre === genre.id) && e.topic === topic.id
}))`
if topic? then diffculty += 0.1
if genre or topic then excludes.push {
genre: if genre then genre.id else undefined
topic: if topic then topic.id else undefined
}
platform = undefined
if random.random() <= 0.7 then platform = platforms.pickRandom(random)
audience = undefined
if company.canSetTargetAudience() and random.random() <= 0.2 then audience = audiences.pickRandom(random)
difficulty += 0.8 * random.random()
minScore = 4 + Math.floor(5 * difficulty)
size = undefined
`do
size = sizes.pickRandom(random);
while (platform != undefined && !Platforms.doesPlatformSupportGameSize(platform, size))`
basePay = sizeBasePay[size]
pay = Math.max(1, Math.floor((basePay * (minScore / 10))/5e3)) * 5e3
penalty = Math.floor((pay * 1.2 + pay * 1.8 * random.random())/5e3) * 5e3
pubObject = undefined
puName = undefined
if platform and (platform.company and random.random() <= 0.2) then pubName = platform.company
else
pubObject = publishers.pickRandom(random)
pubName = pubObject.name
royaltyRate = Math.floor(7 + 8 * difficulty) / 100
name = "#{if topic then topic.name else 'Any Topic'.localize()} / #{if genre then genre.name else 'Any Genre'.localize()}"
if not platform or Platforms.getPlatformsOnMarket(company).first((p) -> p.id is platform.id)
results.push contract = {
id: "publisherContracts"
refNumber: Math.floor(Math.random() * 65535)
type: "gameContract"
name: name
description: "Publisher: {0}".localize().format(pubName)
publisher: pubName
publisherObject: pubObject
topic: if topic then topic.id else topic
genre: if genre then genre.id else genre
platform: if platform then platform.id else undefined
gameSize: size
gameAudience: audience
minScore: minScore
payment: pay
penalty: penalty
royaltyRate: royaltyRate
complete: if pubObject.complete? then pubObject.complete.bind(contract) else undefined
}
else
count++
results
getById: (id) -> GDT.Publisher.getAll().first((p) -> p.id is id)
}
ProjectContracts.publisherContracts.getContract = (company) ->
GDT.Publisher.generate(company, 5).filter((p) -> not p.skip )
oldPublisherComplete = ProjectContracts.publisherContracts.complete
ProjectContracts.publisherContracts.complete = (company, success, data) ->
data.complete?(company, success, data)
oldPublisherComplete(company, success, data)
)()
( ->
reviewers = ["Star Games", "Informed Gamer", "Game Hero", "All Games"]
GDT.Review = {
reviewers: reviewers.slice()
messages: []
getAll: -> GDT.Review.reviewers.slice()
getAvailable: (company) ->
results = []
for r in GDT.Review.getAll().filter((reviewer) -> not reviewer.isAvailable? or reviewer.isAvailable(company))
results.push(r)
results
getAllMessages: -> GDT.Review.messages.slice()
pickReviewers: (count) ->
results = []
reviewers = GDT.Review.getAvailable()
r = undefined
for i in [0..count]
r = reviewers.pickRandom()
results.push(r)
reviewers.remove()
results
reviewLatestFor: (company) ->
negativeMessages = []
positiveMessages = []
mmoFactor = 1
game = company.currentGame
GDT.fire(GameManager, GDT.eventKeys.gameplay.beforeGameReview, {
company : company,
game : game
})
if game.flags.mmo then mmoFactor = 2
sequelTo = undefined
if game.sequelTo
sequelTo = company.getGameById(game.sequelTo)
if sequelTo.releaseWeek > company.currentWeek - 40 then game.flags.sequelsTooClose = true
tp = game.technologyPoints
dp = game.designPoints
generalModifier = 0
goodDecisions = 0
badDecisions = 0
if dp + tp >= 30
goldenRatio = GameGenre.getGoldenRatio(game.genre, game.secondGenre)
difference = dp * goldenRatio - tp
percentDifference = 0
percentDifference = if (tp > dp) then Math.abs(difference / tp * 100) else percentDifference = Math.abs(difference / dp * 100)
"goldenRatio percentDifference: {0}".format(percentDifference).log()
if Math.abs(percentDifference) <= 25
generalModifier += 0.1
goodDecisions += 1
positiveMessages.push("They achieved a great balance between technology and design.".localize())
else if Math.abs(percentDifference) > 50
generalModifier -= 0.1
if difference < 0 then negativeMessages.push("They should focus more on design.".localize())
else negativeMessages.push("They should focus more on technology.".localize())
executedDevMissions = game.featureLog.filter((m) -> m.missionType is "mission" )
optimalMissionFocus = executedDevMissions.filter((m) ->
percentage = m.duration / General.getGameSizeDurationFactor(game.gameSize) / General.getMultiPlatformDurationFactor(game) / (Missions.BASE_DURATION * 3)
Missions.getGenreWeighting(m, game) >= 0.9 and percentage >= 0.4
)
if optimalMissionFocus.length >= 2
generalModifier += 0.2
goodDecisions += optimalMissionFocus.length
positiveMessages.push("Their focus on {0} served this game very well.".localize().format(optimalMissionFocus.map((m) -> Missions.getMissionWithId(m.id)).pickRandom().name))
else if optimalMissionFocus.length is 1
generalModifier += 0.1
goodDecisions += 1
else
generalModifier -= 0.15 * mmoFactor
nonOptimalMissions = executedDevMissions.filter (m) ->
percentage = m.duration / General.getGameSizeDurationFactor(game.gameSize) / General.getMultiPlatformDurationFactor(game) / (Missions.BASE_DURATION * 3)
Missions.getGenreWeighting(m, game) < 0.8 and percentage >= 0.4
if nonOptimalMissions.length is 2
mission = Missions.getMissionWithId(nonOptimalMissions.pickRandom().id)
generalModifier -= 0.2 * mmoFactor
badDecisions += nonOptimalMissions.length
negativeMessages.push("Their focus on {0} is a bit odd.".localize().format(mission.name))
else if nonOptimalMissions.length is 1
generalModifier -= 0.1 * mmoFactor
badDecisions += 1
underdevelopedMissions = executedDevMissions.filter (m) ->
percentage = m.duration / General.getGameSizeDurationFactor(game.gameSize) / General.getMultiPlatformDurationFactor(game) / (Missions.BASE_DURATION * 3)
Missions.getGenreWeighting(m, game) >= 0.9 and percentage <= 0.2
for m in underdevelopedMissions
mission = Missions.getMissionWithId(m.id)
generalModifier -= 0.15 * mmoFactor
badDecisions += 1
negativeMessages.push("They shouldn't forget about {0}.".localize().format(mission.name))
value = (dp + tp) / 2 / General.getGameSizePointsFactor(game)
topicGenreMatch = GameGenre.getGenreWeighting(game.topic.genreWeightings, game.genre, game.secondGenre)
if topicGenreMatch <= 0.6
negativeMessages.push("{0} and {1} is a terrible combination.".localize().format(game.topic.name, game.getGenreDisplayName()))
else if topicGenreMatch is 1
positiveMessages.push("{0} and {1} is a great combination.".localize().format(game.topic.name, game.getGenreDisplayName()))
genreText = game.genre.name
if game.secondGenre then genreText += "-" + game.secondGenre.name
previousGame = company.gameLog.last()
if previousGame and (not game.flags.isExtensionPack and (previousGame.genre is game.genre and (previousGame.secondGenre is game.secondGenre and previousGame.topic is game.topic)))
penalty = -0.4
badDecisions += 1
sameGenreTopic = "Another {0}/{1} game?".localize().format(genreText, game.topic.name)
negativeMessages.push(sameGenreTopic)
game.flags.sameGenreTopic = true
"repeat genre/topic penalty: {0}:".format(penalty).log()
generalModifier += penalty
platformGenreMatch = Platforms.getGenreWeighting(game.platforms, game.genre, game.secondGenre)
if platformGenreMatch <= 0.6
smallestWeighting = Platforms.getNormGenreWeighting(game.platforms[0].genreWeightings, game.genre, game.secondGenre)
smallestWeightingIndex = 0
for p,i in game.platforms
tempWeighting = Platforms.getNormGenreWeighting(p.genreWeightings, game.genre, game.secondGenre)
if tempWeighting < smallestWeighting then smallestWeightingIndex = i
negativeMessages.push("{0} games don't work well on {1}.".localize().format(genreText, game.platforms[smallestWeightingIndex].name))
else if platformGenreMatch > 1
highestWeighting = Platforms.getNormGenreWeighting(game.platforms[0].genreWeightings, game.genre, game.secondGenre)
highestWeightingIndex = 0
for p,i in game.platforms
tempWeighting = Platforms.getNormGenreWeighting(p.genreWeightings, game.genre, game.secondGenre)
if tempWeighting > highestWeighting then highestWeightingIndex = i
positiveMessages.push("{0} games work well on {1}.".localize().format(genreText, game.platforms[highestWeightingIndex].name))
gameAudienceWeighting = General.getAudienceWeighting(game.topic.audienceWeightings, game.targetAudience)
if gameAudienceWeighting <= 0.6
negativeMessages.push("{0} is a horrible topic for {1} audiences.".localize().format(game.topic.name, General.getAudienceLabel(game.targetAudience)))
if game.flags.sequelsTooClose
generalModifier -= 0.4
badDecisions += 1
if game.flags.isExtensionPack then negativeMessages.push("Already a expansion pack?".localize()) else negativeMessages.push("Didn't we just play {0} recently?".localize().format(sequelTo.title))
if game.flags.usesSameEngineAsSequel and not game.flags.isExtensionPack
generalModifier -= 0.1
badDecisions += 1
else if game.flags.hasBetterEngineThanSequel
generalModifier += 0.2
goodDecisions += 1
if game.flags.mmo
weighting = GameGenre.getGenreWeighting(game.topic.genreWeightings, game.genre, game.secondGenre)
if weighting < 1 then generalModifier -= 0.15
bugModifier = 1
if game.bugs > 0
perc = 100 / (game.technologyPoints + game.designPoints)
bugsPercentage = (game.bugs * perc).clamp(0, 100)
bugModifier = 1 - 0.8 * (bugsPercentage / 100)
if bugModifier <= 0.6 then negativeMessages.push("Riddled with bugs.".localize())
else if bugModifier < 0.9 then negativeMessages.push("Too many bugs.".localize())
techLevelModifier = 1
if game.platforms.length > 1
maxTech = game.platforms[0].techLevel
if game.platforms[0].id is "PC" then maxTech = game.platforms[1].techLevel
minTech = maxTech
for p in game.platforms when p.id isnt "PC"
maxTech = Math.max(maxTech, p.techLevel)
minTech = Math.min(minTech, p.techLevel)
techLevelModifier -= (maxTech - minTech) / 20
value += value * generalModifier
value *= platformGenreMatch
value *= gameAudienceWeighting
value *= bugModifier
value *= techLevelModifier
trendModifier = GameTrends.getCurrentTrendFactor(game)
game.flags.trendModifier = trendModifier
value *= trendModifier
topScore = getCurrentTopScoreBarrier(company)
achievedRatio = value / topScore
if achievedRatio >= 0.6 and (gameAudienceWeighting <= 0.7 or topicGenreMatch <= 0.7)
achievedRatio = 0.6 + (achievedRatio - 0.6) / 2
if achievedRatio > 0.7
for p in game.platforms
if Platforms.getPlatformsAudienceWeighting(p.audienceWeightings, game.targetAudience) <= 0.8
value *= Platforms.getPlatformsAudienceWeighting(p.audienceWeightings, game.targetAudience, true)
achievedRatio = value / topScore
break
"achieved {0} / top game {1} = {2}".format(value, Reviews.topScore, achievedRatio).log()
demote = false
finalScore = (achievedRatio * 10).clamp(1, 10)
game.flags.teamContribution = 0
company.staff.forEach((s) -> if s.flags.gamesContributed < 1 then game.flags.teamContribution elsegame.flags.teamContribution += game.getRatioWorked(s) )
game.flags.teamContribution /= company.staff.length
if company.lastTopScore > 0 and finalScore <= 5.2 - 0.2 * game.platforms.length
if goodDecisions > 0 and (goodDecisions > badDecisions and game.flags.teamContribution >= 0.8)
baseScore = 6
numberWorkedOnGame = 0
for key of game.flags.staffContribution
if not game.flags.staffContribution.hasOwnProperty(key) then continue
numberWorkedOnGame++
optimalSize = General.getOptimalTeamSize(game)
diff = Math.abs(optimalSize - numberWorkedOnGame)
if diff > 1 then baseScore -= diff - 1
newStaff = Reviews.getNewStaff(game)
if newStaff
if newStaff.length > 0 then baseScore -= newStaff.length / 2
baseScore += goodDecisions / 2 - badDecisions / 2
if bugModifier < 0.9 then baseScore -= 0.5
else if bugModifier <= 0.6 then baseScore -= 1
if platformGenreMatch <= 0.8 then baseScore -= 1 - platformGenreMatch
if gameAudienceWeighting <= 0.8 then baseScore -= 1 - gameAudienceWeighting
if game.platforms.length > 1
maxTech = game.platforms[0].techLevel
if game.platforms[0].id is "PC"
maxTech = game.platforms[1].techLevel
minTech = maxTech
for p in game.platforms when p.id isnt "PC"
maxTech = Math.max(maxTech, p.techLevel)
minTech = Math.min(minTech, p.techLevel)
baseScore -= (maxTech - minTech) / 0.5
baseScore -= company.getRandom()
baseScore = Math.min(baseScore, 7.7)
if finalScore < baseScore
game.flags.scoreWithoutBrackets = finalScore
finalScore = baseScore
if company.gameLog.length > 3
topScoreDecrease = true
for i in [1..3]
tempGame = company.gameLog[company.gameLog.length - i]
if tempGame.score > 5.2 - 0.2 * tempGame.platforms.length and not tempGame.flags.scoreWithoutBrackets
topScoreDecrease = false
break
if topScoreDecrease
company.lastTopScore = value
game.flags.topScoreDecreased = true
maxScoreFactor = getMaxScorePossible(company, game) / 10
if game.gameSize isnt "medium" and (game.gameSize isnt "small" and maxScoreFactor < 1)
negativeMessages.push("Technology is not state of the art.".localize())
finalScore *= maxScoreFactor
if finalScore >= 9
if generalModifier < 0.1 and company.getRandom() < 0.8 then demote = true
else
newStaff = Reviews.getNewStaff(game)
if newStaff.length > 0
demote = true
game.flags.newStaffIds = newStaff.map((staff) -> staff.id )
if demote
if game.flags.newStaffIds and game.flags.newStaffIds.length > 0
finalScore = 8.15 + 0.95 / game.flags.newStaffIds.length * company.getRandom()
else
finalScore = 8.45 + 0.65 * company.getRandom()
if company.getRandom() < 0.1
finalScore = 9 + 0.25 * company.getRandom()
updateTopScore(company, value)
if sequelTo
if finalScore <= 4
if game.flags.isExtensionPack then negativeMessages.push("What a horrible expansion pack!".localize()) else negativeMessages.push("What a horrible sequel!".localize())
else if finalScore <= 7
if game.flags.isExtensionPack then negativeMessages.push("Average expansion pack.".localize()) else negativeMessages.push("Average sequel.".localize())
else
if game.flags.isExtensionPack then positiveMessages.push("Great expansion pack.".localize()) else positiveMessages.push("Great sequel!".localize())
if company.topScoreAchievements < 2 and company.getCurrentDate().year < 4
if finalScore == 10
finalScore -= 1.05 + 0.45 * company.getRandom()
setTopScoreAchievement(company, value)
else if finalScore >= 9
finalScore -= 1.05 + 0.2 * company.getRandom()
setTopScoreAchievement(company, value)
else if finalScore > 8.5 then finalScore -= 0.4 + 0.2 * company.getRandom()
if finalScore >= 9 then setTopScoreAchievement(company, value)
if finalScore isnt 10 and (game.flags.topScore and company.topScoreAchievements is 3) then finalScore = 10
game.score = finalScore
"final score: {0}".format(finalScore).log()
if sequelTo
if company.getRandom() <= 0.5 or not company.gameLog.some((g) -> g.sequelTo? )
if game.flags.isExtensionPack then Media.createExtensionPackStory(company, game)
else Media.createSequelStory(company, game)
retVal = Reviews.getReviews(game, finalScore, positiveMessages, negativeMessages)
GDT.fire(GameManager, GDT.eventKeys.gameplay.afterGameReview, {
company : company,
game : game,
reviews : retVal
})
retVal
generate: (game, finalScore, positiveMessages, negativeMessages) ->
intScore = Math.floor(finalScore).clamp(1, 10)
if finalScore >= 9.5 then intScore = 10
reviewers = GDT.Reviewer.pickReviewers(4)
reviews = []
usedMessages = []
scores = []
variation = 1
for reviewer in reviewers
if intScore is 5 or intScore is 6 then (variation = if GameManager.company.getRandom() < 0.05 then 2 else 1)
scoreVariation = if Math.randomSign() is 1 then 0 else variation * Math.randomSign()
score = (intScore + scoreVariation).clamp(1, 10)
if score is 10 and (scores.length is 3 and scores.average() is 10)
if not game.flags.psEnabled
if Math.floor(finalScore) < 10 or GameManager.company.getRandom() < 0.8 then score--
else if Math.floor(finalScore) is 10 and GameManager.company.getRandom() < 0.4 then score++
message = if reviewer.getMessage? then reviewer.getMessage(game, finalScore) else undefined
if message is undefined
`do {
if (GameManager.company.getRandom() <= 0.2)
if (scoreVariation >= 0 && (score > 2 && positiveMessages.length != 0))
message = positiveMessages.pickRandom();
else {
if (scoreVariation < 0 && (score < 6 && negativeMessages != 0))
message = negativeMessages.pickRandom()
}
else
message = undefined;
if (!message)
message = Reviews.getGenericReviewMessage(game, score)
} while (usedMessages.weakIndexOf(message) != -1)`
usedMessages.push(message)
scores.push(score)
reviews.push {
score : score,
message : message,
reviewerName : reviewer.name
}
reviews
getById: (id) -> GDT.Reviewer.getAll().first((r) -> r.id is id)
getMessageById: (id) -> GDT.Reviewer.getAllMessages.first((m) -> m.id is id)
}
GDT.Reviewer.reviewers.forEach((e, i) -> GDT.Reviewer.reviewers[i] = {name: e, id: e.replace(' ', '')})
)()
GDT.Event = {
events: DecisionNotifications.getAllNotificationsObjects()
getAll: -> GDT.Event.slice()
getAvailable: (company) ->
events = GDT.Event.getAll().filter((e) -> not e.isRandom and GDT.Event.isAvailable(e))
getRandom: (company) ->
spawnEvent = company.flags.nextRandomEvent and company.flags.nextRandomEvent <= GameManager.gameTime
unless company.flags.nextRandomEvent
company.flags.nextRandomEvent = (48 + 24 * company.getRandom()) * GameManager.SECONDS_PER_WEEK * 1e3
if spawnEvent
company.flags.nextRandomEvent = GameManager.gameTime + (36 + 48 * company.getRandom()) * GameManager.SECONDS_PER_WEEK * 1e3
candidates = GDT.Event.getAll().filter((e) ->
e.isRandomEvent and (company.flags.lastRandomEventId isnt e.id and GDT.Event.isAvailable(company, e))
)
event = candidates.pickRandom()
unless event then return []
company.flags.lastRandomEventId = event.id
return event
return []
trigger: (company, event) ->
unless company.eventTriggerCounts[event.id] then company.eventTriggerCounts[event.id] = 1
else company.eventTriggerCounts[event.id]++
return if event.notification then event.notification else event.getNotification(company)
isAvailable: (company, event) ->
if event.date
return false if Math.floor(company.currentWeek) < General.getWeekFromDateString(event.date, event.ignoreGameLengthModifier)
if event.maxTriggers or event.date
count = GameManager.company.eventTriggerCounts[event.id]
return false if count and count >= (if event.date then 1 else event.maxTriggers)
event.date or event.trigger and event.trigger(company)
getById: (id) -> GDT.Event.getAll().first((e) -> e.id is id )
}
GDT.Notification = {
queue: []
getNotification: (company, event) -> if event.notification then event.notification else event.getNotification(company)
getNewNotifications: (company) ->
results = GDT.Event.getAvailable(company).map((e) -> GDT.Event.trigger(company, e))
if results.length is 0 then results = [GDT.Event.trigger(company, GDT.Event.getRandom(company))]
results
}
DecisionNotifications.getNewNotifications = GDT.Notification.getNewNotifications
GDT.ModSupport = ( ->
ModSupport = {}
oldLoad = ModSupport.loadMod
ModSupport.loadMod = (enableMods, i) ->
SDP.Util.Logger.formatter = SDP.Util.Logger.printf
oldLoad(enableMods, i)
ModSupport
)()
ModSupport.loadMod = GDT.ModSupport.loadMod
GDT
)()
# Adds a basic wrapper of UltimateLib functionality for easy conversion to the SDP
( ->
SDP.ULWrapper = {}
unless String::endsWith?
String::endsWith = (a) ->
@substr(@length - a.length) is a
unless String::startsWith?
String::startsWith = (a) ->
@substr(0, a.length) is a
unless Number::truncateDecimals?
Number::truncateDecimals = (a) ->
b = @ - Math.pow(10, -a) / 2
b += b / Math.pow(2, 53)
b.toFixed(a)
SDP.ULWrapper.Logger = ( ->
Loggger = { enabled: true }
Logger.log = (e, c) ->
if not Logger.enabled then return
unless c? then SDP.Util.Logger.debug(e) else SDP.Util.Logger.error("#{e}\n#{c.message}")
Logger
)()
SDP.ULWrapper.Contracts = ( ->
Contracts = {}
Contracts.add = (c) ->
isAvailable = (isRand, chance) ->
if isRand is true
if (1 is Math.floor((Math.random() * chance) + 1)) is false then isRand = false
if isRand is false then isRand = true
return isRand
c.isAvailable = (company) ->
c.canTrigger(company) and isAvailable(c.isRandom, c.randomChance)
c.card = {
techPoints: c.requiredT
designPoints: c.requiredD
payment: c.payment
penalty: c.penalty
weeks: c.weeksToFinish
}
SDP.Functional.addContractItem(c)
Contracts.collection = (company) ->
SDP.GDT.Contract.getAvailable(company).filter((c) ->
c.size is 'small' or (company.flags.mediumContractsEnabled and c.size is 'medium') or (company.flags.largeContractsEnabled and c.size is 'large')
)
Contracts
)()
SDP.ULWrapper.Publishers = ( ->
Publishers = {}
# add Publisher modifications here
Publishers
)()
SDP.ULWrapper.Research = ( ->
Research = {}
# add Research modifications here
Research
)()
)()
###
Adds company tracking system
Companies.createCompany = (item) ->
if item.constructor is String then item = {name: item}
if not item.id? and item.name? then item.id = name.replace(/\s/g,"")
item.platforms = []
item.platforms.push(p) for p of Platforms.allPlatforms when p.company is item.name
item.sort = ->
item.platforms.sort (a,b) ->
General.getWeekFromDateString(a.published) - General.getWeekFromDateString(b.published)
item.addPlatform = (platform) ->
return if item.platforms.find((val) -> platform.id is val.id)?
platform.company = item.name
SDP.GDT.addPlatform(platform)
item.platforms.push(platform)
item.sort()
platform
item.sort()
item
Companies.createVanillaCompany = (item) ->
Companies.createCompany(item)
item.isVanilla = true
item
Companies.vanillaCompanies = [
Companies.createVanillaCompany("Micronoft")
Companies.createVanillaCompany("Grapple")
Companies.createVanillaCompany("Govodore")
Companies.createVanillaCompany("Ninvento")
Companies.createVanillaCompany("PI:NAME:<NAME>END_PI")
Companies.createVanillaCompany("PI:NAME:<NAME>END_PI")
Companies.createVanillaCompany("KickIT")
]
Companies.moddedCompanies = []
Companies.getAllCompanies = ->
c = Companies.vanillaCompanies.filter (val) -> val.id?
c.addRange(Companies.moddedCompanies.filter (val) -> val.id?)
for comp of c
comp.sort = ->
comp.platforms.sort (a,b) ->
General.getWeekFromDateString(a.published) - General.getWeekFromDateString(b.published)
comp.sort()
c.sort (a,b) ->
General.getWeekFromDateString(a.platforms[0].published) - General.getWeekFromDateString(b.platforms[0].published)
c
Companies.getAvailableCompanies = (company) ->
week = Math.floor(company.currentWeek)
Companies.getAllCompanies().filter (val) ->
General.getWeekFromDateString(val.platforms[0].published) <= week
###
GDT.on(GDT.eventKeys.saves.loaded, ->
GameManager.company.notifications.push(i) for i in SDP.GDT.Notification.queue
SDP.GDT.Notification.queue = [])
GDT.on(GDT.eventKeys.saves.newGame, ->
GameManager.company.notifications.push(i) for i in SDP.GDT.Notification.queue
SDP.GDT.Notification.queue = [])
###
Modifies GDT classes to make all objects indepedent of GameManager.company
###
( ->
oldGameConst = Game
oldGame = oldGameConst::
Game = (company) ->
oldGameConst.call(@, company)
@company = company
return
Game:: = oldGame
)()
( ->
oldCharConst = Character
oldChar = oldCharConst::
Character = (args...) ->
oldCharConst.call(@, args)
@company = args[0].company or SDP.GDT.Company.getAllCompanies()[args[0].uid] or SDP.GDT.Company.getClientCompany()
return
Character:: = oldChar
oldSave = Character::save
Character::save = ->
oldSave.call(@).companyId = @company.uid
)()
( ->
oldCompanyConst = Company
oldCompany = oldCompanyConst::
Company = (args...) ->
oldCompanyConst.call(@, args)
SDP.GDT.Company.addCompany(@)
return
Company:: = oldCompany
)()
###
Allow adding famous people and adding custom applicant algorithims
JobApplicants.moddedFamous = []
JobApplicants.moddedAlgorithims = []
JobApplicants.getRandomMale = (random) ->
results = []
JobApplicants.moddedAlgorithims.forEach (val) ->
results.push(val.apply(random)) if val.forMale
results.pickRandom(random)
JobApplicants.getRandomFemale = (random) ->
results = []
JobApplicants.moddedAlgorithims.forEach (val) ->
results.push(val.apply(random)) if not val.forMale
results.pickRandom(random)
JobApplicants.getFamousMale = (tech, design, random) ->
results = []
JobApplicants.moddedFamous.forEach (val) ->
results.push(val.apply(random, tech, design)) if val.forMale
results.pickRandom(random)
JobApplicants.getFamousFemale = (tech, design, random) ->
results = []
JobApplicants.moddedFamous.forEach (val) ->
results.push(val.apply(random, tech, design)) if not val.forMale
results.pickRandom(random)
JobApplicants.searchTests =
[
{
id : "ComplexAlgorithms"
name : "Complex Algorithms".localize()
minT : 0.6
}
{
id : "GameDemo"
name : "Game Demo".localize()
minD : 0.3,
minT : 0.3
}
{
id : "Showreel"
name : "Showreel".localize()
minD : 0.6
}
]
UI.__olgGenerateJobApplicants = UI._generateJobApplicants
UI._generateJobApplicants = ->
oldApplicants = UI.__olgGenerateJobApplicants()
settings = GameManager.uiSettings["findStaffData"]
settings = {ratio : 0.1, tests : []} if not settings
settings.seed = Math.floor(GameManager.company.getRandom() * 65535) if not settings.seed
ratio = settings.ratio
test = JobApplicants.searchTests.first (t) -> t.id is settings.tests.first()
company = GameManager.company
random = new MersenneTwister(settings.seed)
newApplicants = []
count = Math.floor(2 + 3 * (ratio + 0.2).clamp(0, 1))
rerolls = 0
maxRerolls = 2
maxBonus = if company.currentLevel is 4 then 4 / 5 else 2 / 5
takenNames = GameManager.company.staff.map (s) -> s.name
for i in [0...count]
qBonusFactor = ratio / 3 + (1 - ratio / 3) * random.random()
maxBonus += 1 / 5 if random.random() >= 0.95
q = 1 / 5 + maxBonus * qBonusFactor
level = Math.floor(q * 5).clamp(1,5)
maxD = 1
minD = 0
if test
maxD -= test.minT if test.minT
if test.minD
minD = test.minD
maxD -= minD
baseValue = 200 * level
d = baseValue * minD + baseValue * maxD * random.random()
t = baseValue - d
rBonusFactor = random.random()
r = 1 / 5 + maxBonus * rBonusFactor
sBonusFactor = random.random()
s = 1 / 5 + maxBonus * sBonusFactor
goodRoll = sBonusFactor > 0.5 and (qBonusFactor > 0.5 and rBonusFactor > 0.5)
if not goodRoll and (rerolls < maxRerolls and random.random() <= (ratio + 0.1).clamp(0, 0.7))
i--
rerolls++
continue
rerolls = 0
isFamous = false
sex = "male"
loop
sex = "male"
if goodRoll
name = JobApplicants.getFamousMale(t, d, random) if (random.random() > 0.15)
else
name = JobApplicants.getFamousFemale(t, d, random)
sex = "female"
isFamous = true
else
name = JobApplicants.getRandomMale(random) if random.random() > 0.25
else
name = JobApplicants.getRandomFemale(random)
sex = "female"
isFamous = false
break unless takenNames.indexOf(name) != -1
takenNames.push(PI:NAME:<NAME>END_PI)
salary = Character.BASE_SALARY_PER_LEVEL * level
salary += salary * 0.2 * random.random() * random.randomSign()
salary = Math.floor(salary/1e3) * 1e3
newApplicants.push {
name : PI:NAME:<NAME>END_PI,
qualityFactor : q,
technologyFactor : t / 500,
designFactor : d / 500,
researchFactor : r,
speedFactor : s,
salary : salary,
isFamous : isFamous,
sex : sex
}
GDT.fire GameManager, GDT.eventKeys.gameplay.staffApplicantsGenerated, {
newApplicants : newApplicants
settings : settings
rng : random
}
applicants = []
for i in [0...count]
if random.random() >= 0.5
a = newApplicants.pickRandom(random)
applicants.push(a)
newApplicants.remove(a)
else
a = oldApplicants.pickRandom(random)
applicants.push(a)
oldApplicants.remove(a)
return applicants
### |
[
{
"context": "ce the location of arrow function bodies\n# @author Sharmila Jesupaul\n###\n'use strict'\n\n#------------------------------",
"end": 94,
"score": 0.9998559355735779,
"start": 77,
"tag": "NAME",
"value": "Sharmila Jesupaul"
}
] | src/rules/implicit-arrow-linebreak.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview enforce the location of arrow function bodies
# @author Sharmila Jesupaul
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'enforce the location of arrow function bodies'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/implicit-arrow-linebreak'
fixable: 'whitespace'
schema: [enum: ['beside', 'below']]
create: (context) ->
sourceCode = context.getSourceCode()
#----------------------------------------------------------------------
# Helpers
#----------------------------------------------------------------------
###*
# Gets the applicable preference for a particular keyword
# @returns {string} The applicable option for the keyword, e.g. 'beside'
###
getOption = -> context.options[0] or 'beside'
###*
# Validates the location of an arrow function body
# @param {ASTNode} node The arrow function body
# @param {string} keywordName The applicable keyword name for the arrow function body
# @returns {void}
###
validateExpression = (node) ->
return unless (
node.body.type isnt 'BlockStatement' or
(node.body.body.length is 1 and
node.body.body[0].type is 'ExpressionStatement')
)
{body} = node
body = body.body[0] if body.type is 'BlockStatement'
option = getOption()
tokenBefore = sourceCode.getTokenBefore body
hasParens = tokenBefore.value is '('
# return if node.type is 'BlockStatement'
fixerTarget = body
if hasParens
# Gets the first token before the function body that is not an open paren
tokenBefore = sourceCode.getTokenBefore body, (token) ->
token.value isnt '('
fixerTarget = sourceCode.getTokenAfter tokenBefore
if (
tokenBefore.loc.end.line is fixerTarget.loc.start.line and
option is 'below'
)
context.report
node: fixerTarget
message: 'Expected a linebreak before this expression.'
fix: (fixer) -> fixer.insertTextBefore fixerTarget, '\n'
else if (
tokenBefore.loc.end.line isnt fixerTarget.loc.start.line and
option is 'beside'
)
context.report
node: fixerTarget
message: 'Expected no linebreak before this expression.'
fix: (fixer) ->
fixer.replaceTextRange(
[tokenBefore.range[1], fixerTarget.range[0]]
' '
)
#----------------------------------------------------------------------
# Public
#----------------------------------------------------------------------
FunctionExpression: validateExpression
ArrowFunctionExpression: validateExpression
| 157670 | ###*
# @fileoverview enforce the location of arrow function bodies
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'enforce the location of arrow function bodies'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/implicit-arrow-linebreak'
fixable: 'whitespace'
schema: [enum: ['beside', 'below']]
create: (context) ->
sourceCode = context.getSourceCode()
#----------------------------------------------------------------------
# Helpers
#----------------------------------------------------------------------
###*
# Gets the applicable preference for a particular keyword
# @returns {string} The applicable option for the keyword, e.g. 'beside'
###
getOption = -> context.options[0] or 'beside'
###*
# Validates the location of an arrow function body
# @param {ASTNode} node The arrow function body
# @param {string} keywordName The applicable keyword name for the arrow function body
# @returns {void}
###
validateExpression = (node) ->
return unless (
node.body.type isnt 'BlockStatement' or
(node.body.body.length is 1 and
node.body.body[0].type is 'ExpressionStatement')
)
{body} = node
body = body.body[0] if body.type is 'BlockStatement'
option = getOption()
tokenBefore = sourceCode.getTokenBefore body
hasParens = tokenBefore.value is '('
# return if node.type is 'BlockStatement'
fixerTarget = body
if hasParens
# Gets the first token before the function body that is not an open paren
tokenBefore = sourceCode.getTokenBefore body, (token) ->
token.value isnt '('
fixerTarget = sourceCode.getTokenAfter tokenBefore
if (
tokenBefore.loc.end.line is fixerTarget.loc.start.line and
option is 'below'
)
context.report
node: fixerTarget
message: 'Expected a linebreak before this expression.'
fix: (fixer) -> fixer.insertTextBefore fixerTarget, '\n'
else if (
tokenBefore.loc.end.line isnt fixerTarget.loc.start.line and
option is 'beside'
)
context.report
node: fixerTarget
message: 'Expected no linebreak before this expression.'
fix: (fixer) ->
fixer.replaceTextRange(
[tokenBefore.range[1], fixerTarget.range[0]]
' '
)
#----------------------------------------------------------------------
# Public
#----------------------------------------------------------------------
FunctionExpression: validateExpression
ArrowFunctionExpression: validateExpression
| true | ###*
# @fileoverview enforce the location of arrow function bodies
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'enforce the location of arrow function bodies'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/implicit-arrow-linebreak'
fixable: 'whitespace'
schema: [enum: ['beside', 'below']]
create: (context) ->
sourceCode = context.getSourceCode()
#----------------------------------------------------------------------
# Helpers
#----------------------------------------------------------------------
###*
# Gets the applicable preference for a particular keyword
# @returns {string} The applicable option for the keyword, e.g. 'beside'
###
getOption = -> context.options[0] or 'beside'
###*
# Validates the location of an arrow function body
# @param {ASTNode} node The arrow function body
# @param {string} keywordName The applicable keyword name for the arrow function body
# @returns {void}
###
validateExpression = (node) ->
return unless (
node.body.type isnt 'BlockStatement' or
(node.body.body.length is 1 and
node.body.body[0].type is 'ExpressionStatement')
)
{body} = node
body = body.body[0] if body.type is 'BlockStatement'
option = getOption()
tokenBefore = sourceCode.getTokenBefore body
hasParens = tokenBefore.value is '('
# return if node.type is 'BlockStatement'
fixerTarget = body
if hasParens
# Gets the first token before the function body that is not an open paren
tokenBefore = sourceCode.getTokenBefore body, (token) ->
token.value isnt '('
fixerTarget = sourceCode.getTokenAfter tokenBefore
if (
tokenBefore.loc.end.line is fixerTarget.loc.start.line and
option is 'below'
)
context.report
node: fixerTarget
message: 'Expected a linebreak before this expression.'
fix: (fixer) -> fixer.insertTextBefore fixerTarget, '\n'
else if (
tokenBefore.loc.end.line isnt fixerTarget.loc.start.line and
option is 'beside'
)
context.report
node: fixerTarget
message: 'Expected no linebreak before this expression.'
fix: (fixer) ->
fixer.replaceTextRange(
[tokenBefore.range[1], fixerTarget.range[0]]
' '
)
#----------------------------------------------------------------------
# Public
#----------------------------------------------------------------------
FunctionExpression: validateExpression
ArrowFunctionExpression: validateExpression
|
[
{
"context": "s file is part of the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyrig",
"end": 74,
"score": 0.9998812675476074,
"start": 61,
"tag": "NAME",
"value": "Jessym Reziga"
},
{
"context": "f the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyright and license informa",
"end": 96,
"score": 0.9999337196350098,
"start": 76,
"tag": "EMAIL",
"value": "jessym@konsserto.com"
},
{
"context": "ler/Controller')\n\n#\n# SocketController\n#\n# @author Jessym Reziga <jessym@konsserto.com>\n#\nclass SocketController e",
"end": 356,
"score": 0.999886691570282,
"start": 343,
"tag": "NAME",
"value": "Jessym Reziga"
},
{
"context": "\n\n#\n# SocketController\n#\n# @author Jessym Reziga <jessym@konsserto.com>\n#\nclass SocketController extends Controller\n\n\n\tc",
"end": 378,
"score": 0.9999338388442993,
"start": 358,
"tag": "EMAIL",
"value": "jessym@konsserto.com"
}
] | node_modules/konsserto/lib/src/Konsserto/Bundle/FrameworkBundle/Controller/SocketController.coffee | konsserto/konsserto | 2 | ###
* This file is part of the Konsserto package.
*
* (c) Jessym Reziga <jessym@konsserto.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
Controller = use('@Konsserto/Bundle/FrameworkBundle/Controller/Controller')
#
# SocketController
#
# @author Jessym Reziga <jessym@konsserto.com>
#
class SocketController extends Controller
constructor:() ->
super
ioRoomJoin:(room) ->
@request.io.join(room)
ioRoomBroadcast:(room,event,data = {}) ->
@request.io.room(room).broadcast(event,data )
ioRoomBroadcastAll:(room,event,data = {}) ->
@app.io.room(room).broadcast(event,data)
ioSession:() ->
return @request.session
ioBroadcast:(event,data = {}) ->
@request.io.broadcast(event,data)
ioBroadcastAll:(event,data = {}) ->
@app.io.broadcast(event,data)
ioForward:(event) ->
@request.io.route(event)
ioEmit:(event,data = {}) ->
@request.io.emit(event,data)
ioRespond:(data = {}) ->
@request.io.respond(data)
ioSet:(key,value) ->
@app.io.set(key,value)
ioData:() ->
return @request.data
module.exports = SocketController; | 61329 | ###
* This file is part of the Konsserto package.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
Controller = use('@Konsserto/Bundle/FrameworkBundle/Controller/Controller')
#
# SocketController
#
# @author <NAME> <<EMAIL>>
#
class SocketController extends Controller
constructor:() ->
super
ioRoomJoin:(room) ->
@request.io.join(room)
ioRoomBroadcast:(room,event,data = {}) ->
@request.io.room(room).broadcast(event,data )
ioRoomBroadcastAll:(room,event,data = {}) ->
@app.io.room(room).broadcast(event,data)
ioSession:() ->
return @request.session
ioBroadcast:(event,data = {}) ->
@request.io.broadcast(event,data)
ioBroadcastAll:(event,data = {}) ->
@app.io.broadcast(event,data)
ioForward:(event) ->
@request.io.route(event)
ioEmit:(event,data = {}) ->
@request.io.emit(event,data)
ioRespond:(data = {}) ->
@request.io.respond(data)
ioSet:(key,value) ->
@app.io.set(key,value)
ioData:() ->
return @request.data
module.exports = SocketController; | true | ###
* This file is part of the Konsserto package.
*
* (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
Controller = use('@Konsserto/Bundle/FrameworkBundle/Controller/Controller')
#
# SocketController
#
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
class SocketController extends Controller
constructor:() ->
super
ioRoomJoin:(room) ->
@request.io.join(room)
ioRoomBroadcast:(room,event,data = {}) ->
@request.io.room(room).broadcast(event,data )
ioRoomBroadcastAll:(room,event,data = {}) ->
@app.io.room(room).broadcast(event,data)
ioSession:() ->
return @request.session
ioBroadcast:(event,data = {}) ->
@request.io.broadcast(event,data)
ioBroadcastAll:(event,data = {}) ->
@app.io.broadcast(event,data)
ioForward:(event) ->
@request.io.route(event)
ioEmit:(event,data = {}) ->
@request.io.emit(event,data)
ioRespond:(data = {}) ->
@request.io.respond(data)
ioSet:(key,value) ->
@app.io.set(key,value)
ioData:() ->
return @request.data
module.exports = SocketController; |
[
{
"context": "@fileoverview Tests for jsx-quotes rule.\n# @author Mathias Schreck <https://github.com/lo1tuma>\n###\n\n'use strict'\n\n#",
"end": 73,
"score": 0.999839186668396,
"start": 58,
"tag": "NAME",
"value": "Mathias Schreck"
},
{
"context": "le.\n# @author Mathias Schreck <https://github.com/lo1tuma>\n###\n\n'use strict'\n\n#----------------------------",
"end": 101,
"score": 0.9992741346359253,
"start": 94,
"tag": "USERNAME",
"value": "lo1tuma"
}
] | src/tests/rules/jsx-quotes.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for jsx-quotes rule.
# @author Mathias Schreck <https://github.com/lo1tuma>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/jsx-quotes'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'jsx-quotes', rule,
valid: [
code: '<foo bar="baz" />'
,
code: "<foo bar='\"' />"
,
code: '<foo bar="\'" />'
options: ['prefer-single']
,
code: "<foo bar='baz' />"
options: ['prefer-single']
,
code: '<foo bar="baz">"</foo>'
,
code: "<foo bar='baz'>'</foo>"
options: ['prefer-single']
,
code: "<foo bar={'baz'} />"
,
code: '<foo bar={"baz"} />'
options: ['prefer-single']
,
code: '<foo bar={baz} />'
,
code: '<foo bar />'
,
code: "<foo bar='"' />"
options: ['prefer-single']
,
code: '<foo bar=""" />'
,
code: "<foo bar=''' />"
options: ['prefer-single']
,
code: '<foo bar="'" />'
]
invalid: [
code: "<foo bar='baz' />"
output: '<foo bar="baz" />'
errors: [
message: 'Unexpected usage of singlequote.'
line: 1
column: 10
type: 'Literal'
]
,
code: '<foo bar="baz" />'
output: "<foo bar='baz' />"
options: ['prefer-single']
errors: [
message: 'Unexpected usage of doublequote.'
line: 1
column: 10
type: 'Literal'
]
,
code: '<foo bar=""" />'
output: "<foo bar='"' />"
options: ['prefer-single']
errors: [
message: 'Unexpected usage of doublequote.'
line: 1
column: 10
type: 'Literal'
]
,
code: "<foo bar=''' />"
output: '<foo bar="'" />'
errors: [
message: 'Unexpected usage of singlequote.'
line: 1
column: 10
type: 'Literal'
]
]
| 100202 | ###*
# @fileoverview Tests for jsx-quotes rule.
# @author <NAME> <https://github.com/lo1tuma>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/jsx-quotes'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'jsx-quotes', rule,
valid: [
code: '<foo bar="baz" />'
,
code: "<foo bar='\"' />"
,
code: '<foo bar="\'" />'
options: ['prefer-single']
,
code: "<foo bar='baz' />"
options: ['prefer-single']
,
code: '<foo bar="baz">"</foo>'
,
code: "<foo bar='baz'>'</foo>"
options: ['prefer-single']
,
code: "<foo bar={'baz'} />"
,
code: '<foo bar={"baz"} />'
options: ['prefer-single']
,
code: '<foo bar={baz} />'
,
code: '<foo bar />'
,
code: "<foo bar='"' />"
options: ['prefer-single']
,
code: '<foo bar=""" />'
,
code: "<foo bar=''' />"
options: ['prefer-single']
,
code: '<foo bar="'" />'
]
invalid: [
code: "<foo bar='baz' />"
output: '<foo bar="baz" />'
errors: [
message: 'Unexpected usage of singlequote.'
line: 1
column: 10
type: 'Literal'
]
,
code: '<foo bar="baz" />'
output: "<foo bar='baz' />"
options: ['prefer-single']
errors: [
message: 'Unexpected usage of doublequote.'
line: 1
column: 10
type: 'Literal'
]
,
code: '<foo bar=""" />'
output: "<foo bar='"' />"
options: ['prefer-single']
errors: [
message: 'Unexpected usage of doublequote.'
line: 1
column: 10
type: 'Literal'
]
,
code: "<foo bar=''' />"
output: '<foo bar="'" />'
errors: [
message: 'Unexpected usage of singlequote.'
line: 1
column: 10
type: 'Literal'
]
]
| true | ###*
# @fileoverview Tests for jsx-quotes rule.
# @author PI:NAME:<NAME>END_PI <https://github.com/lo1tuma>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/jsx-quotes'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'jsx-quotes', rule,
valid: [
code: '<foo bar="baz" />'
,
code: "<foo bar='\"' />"
,
code: '<foo bar="\'" />'
options: ['prefer-single']
,
code: "<foo bar='baz' />"
options: ['prefer-single']
,
code: '<foo bar="baz">"</foo>'
,
code: "<foo bar='baz'>'</foo>"
options: ['prefer-single']
,
code: "<foo bar={'baz'} />"
,
code: '<foo bar={"baz"} />'
options: ['prefer-single']
,
code: '<foo bar={baz} />'
,
code: '<foo bar />'
,
code: "<foo bar='"' />"
options: ['prefer-single']
,
code: '<foo bar=""" />'
,
code: "<foo bar=''' />"
options: ['prefer-single']
,
code: '<foo bar="'" />'
]
invalid: [
code: "<foo bar='baz' />"
output: '<foo bar="baz" />'
errors: [
message: 'Unexpected usage of singlequote.'
line: 1
column: 10
type: 'Literal'
]
,
code: '<foo bar="baz" />'
output: "<foo bar='baz' />"
options: ['prefer-single']
errors: [
message: 'Unexpected usage of doublequote.'
line: 1
column: 10
type: 'Literal'
]
,
code: '<foo bar=""" />'
output: "<foo bar='"' />"
options: ['prefer-single']
errors: [
message: 'Unexpected usage of doublequote.'
line: 1
column: 10
type: 'Literal'
]
,
code: "<foo bar=''' />"
output: '<foo bar="'" />'
errors: [
message: 'Unexpected usage of singlequote.'
line: 1
column: 10
type: 'Literal'
]
]
|
[
{
"context": " expect(creds.secretAccessKey).toEqual(secret || 'secret')\n expect(creds.sessionToken).toEqual(session ||",
"end": 213,
"score": 0.9478848576545715,
"start": 207,
"tag": "KEY",
"value": "secret"
},
{
"context": " config = new AWS.Config(\n accessKeyId: 'akid'\n secretAccessKey: 'secret'\n sessio",
"end": 452,
"score": 0.9726507663726807,
"start": 448,
"tag": "KEY",
"value": "akid"
},
{
"context": " accessKeyId: 'akid'\n secretAccessKey: 'secret'\n sessionToken: 'session'\n )\n va",
"end": 486,
"score": 0.9976070523262024,
"start": 480,
"tag": "KEY",
"value": "secret"
},
{
"context": " secretAccessKey: 'secret'\n sessionToken: 'session'\n )\n validateCredentials(config.credent",
"end": 518,
"score": 0.5105931758880615,
"start": 511,
"tag": "PASSWORD",
"value": "session"
},
{
"context": "s object', ->\n creds =\n accessKeyId: 'akid'\n secretAccessKey: 'secret'\n sessio",
"end": 674,
"score": 0.9692065715789795,
"start": 670,
"tag": "KEY",
"value": "akid"
},
{
"context": " accessKeyId: 'akid'\n secretAccessKey: 'secret'\n sessionToken: 'session'\n validateCr",
"end": 708,
"score": 0.9978379607200623,
"start": 702,
"tag": "KEY",
"value": "secret"
},
{
"context": "fix', ->\n process.env.AWS_ACCESS_KEY_ID = 'akid'\n process.env.AWS_SECRET_ACCESS_KEY = 'sec",
"end": 3554,
"score": 0.8498402833938599,
"start": 3550,
"tag": "KEY",
"value": "akid"
},
{
"context": "kid'\n process.env.AWS_SECRET_ACCESS_KEY = 'secret'\n process.env.AWS_SESSION_TOKEN = 'session",
"end": 3607,
"score": 0.9774362444877625,
"start": 3601,
"tag": "KEY",
"value": "secret"
},
{
"context": " prefix', ->\n process.env.ACCESS_KEY_ID = 'akid'\n process.env.SECRET_ACCESS_KEY = 'secret'",
"end": 3866,
"score": 0.8959155082702637,
"start": 3862,
"tag": "KEY",
"value": "akid"
},
{
"context": "= 'akid'\n process.env.SECRET_ACCESS_KEY = 'secret'\n process.env.SESSION_TOKEN = 'session'\n ",
"end": 3915,
"score": 0.9456269145011902,
"start": 3909,
"tag": "KEY",
"value": "secret"
},
{
"context": "als', ->\n process.env.AWS_ACCESS_KEY_ID = 'akid'\n process.env.AWS_SECRET_ACCESS_KEY = 'sec",
"end": 4159,
"score": 0.9973422884941101,
"start": 4155,
"tag": "KEY",
"value": "akid"
},
{
"context": "kid'\n process.env.AWS_SECRET_ACCESS_KEY = 'secret'\n creds = new AWS.EnvironmentCredentials('",
"end": 4212,
"score": 0.9945195913314819,
"start": 4206,
"tag": "KEY",
"value": "secret"
},
{
"context": "'AWS')\n expect(creds.accessKeyId).toEqual('akid')\n creds.accessKeyId = 'not_akid'\n ",
"end": 4315,
"score": 0.9782193899154663,
"start": 4311,
"tag": "KEY",
"value": "akid"
},
{
"context": "yId).toEqual('akid')\n creds.accessKeyId = 'not_akid'\n expect(creds.accessKeyId).not.toEqual('a",
"end": 4355,
"score": 0.9900474548339844,
"start": 4347,
"tag": "KEY",
"value": "not_akid"
},
{
"context": "d'\n expect(creds.accessKeyId).not.toEqual('akid')\n creds.refresh()\n expect(creds.ac",
"end": 4408,
"score": 0.9447568655014038,
"start": 4404,
"tag": "KEY",
"value": "akid"
},
{
"context": "resh()\n expect(creds.accessKeyId).toEqual('akid')\n\n describe 'AWS.FileSystemCredentials', ->\n ",
"end": 4482,
"score": 0.9220942258834839,
"start": 4478,
"tag": "KEY",
"value": "akid"
},
{
"context": "rom root doc', ->\n mock = '{\"accessKeyId\":\"akid\", \"secretAccessKey\":\"secret\",\"sessionToken\":\"sess",
"end": 4669,
"score": 0.9867026805877686,
"start": 4665,
"tag": "KEY",
"value": "akid"
},
{
"context": "mock = '{\"accessKeyId\":\"akid\", \"secretAccessKey\":\"secret\",\"sessionToken\":\"session\"}'\n spyOn(AWS.uti",
"end": 4697,
"score": 0.9936222434043884,
"start": 4691,
"tag": "KEY",
"value": "secret"
},
{
"context": "->\n mock = '{\"credentials\":{\"accessKeyId\":\"akid\", \"secretAccessKey\":\"secret\",\"sessionToken\":\"sess",
"end": 5005,
"score": 0.988457202911377,
"start": 5001,
"tag": "KEY",
"value": "akid"
},
{
"context": "ntials\":{\"accessKeyId\":\"akid\", \"secretAccessKey\":\"secret\",\"sessionToken\":\"session\"}}'\n spy = spyOn(",
"end": 5033,
"score": 0.9951936602592468,
"start": 5027,
"tag": "KEY",
"value": "secret"
},
{
"context": " '''\n [default]\n aws_access_key_id = akid\n aws_secret_access_key = secret\n aw",
"end": 7290,
"score": 0.9755796194076538,
"start": 7286,
"tag": "KEY",
"value": "akid"
},
{
"context": " '''\n [default]\n aws_access_key_id = akid\n aws_secret_access_key = secret\n aw",
"end": 7787,
"score": 0.9568469524383545,
"start": 7783,
"tag": "KEY",
"value": "akid"
},
{
"context": "ck = '''\n [foo]\n aws_access_key_id = akid\n aws_secret_access_key = secret\n aw",
"end": 8132,
"score": 0.9677197933197021,
"start": 8128,
"tag": "KEY",
"value": "akid"
},
{
"context": "ck = '''\n [foo]\n aws_access_key_id = akid\n aws_secret_access_key = secret\n aw",
"end": 8530,
"score": 0.9608260989189148,
"start": 8526,
"tag": "KEY",
"value": "akid"
},
{
"context": " AccessKeyId: 'KEY'\n SecretAccessKey: 'SECRET'\n Token: 'TOKEN'\n Expiratio",
"end": 10068,
"score": 0.9924240112304688,
"start": 10062,
"tag": "KEY",
"value": "SECRET"
},
{
"context": " SecretAccessKey: 'SECRET'\n Token: 'TOKEN'\n Expiration: expireTime.toISOString()",
"end": 10095,
"score": 0.834372878074646,
"start": 10090,
"tag": "KEY",
"value": "TOKEN"
},
{
"context": "')\n expect(creds.secretAccessKey).toEqual('SECRET')\n expect(creds.sessionToken).toEqual('TOK",
"end": 10878,
"score": 0.6104351282119751,
"start": 10872,
"tag": "KEY",
"value": "SECRET"
},
{
"context": "RET')\n expect(creds.sessionToken).toEqual('TOKEN')\n expect(creds.needsRefresh()).toEqual(fa",
"end": 10930,
"score": 0.5213415622711182,
"start": 10925,
"tag": "PASSWORD",
"value": "TOKEN"
},
{
"context": ")\n cb null, Credentials:\n AccessKeyId: 'KEY'\n SecretAccessKey: 'SECRET'\n SessionT",
"end": 11893,
"score": 0.712502658367157,
"start": 11890,
"tag": "KEY",
"value": "KEY"
},
{
"context": " AccessKeyId: 'KEY'\n SecretAccessKey: 'SECRET'\n SessionToken: 'TOKEN'\n Expiration: ",
"end": 11926,
"score": 0.8491526246070862,
"start": 11920,
"tag": "KEY",
"value": "SECRET"
},
{
"context": "ect(creds.masterCredentials.accessKeyId).toEqual('AKID')\n expect(creds.masterCredentials.secretAcce",
"end": 12302,
"score": 0.7182881832122803,
"start": 12298,
"tag": "KEY",
"value": "AKID"
},
{
"context": "ect(creds.masterCredentials.accessKeyId).toEqual('AKID')\n expect(creds.masterCredentials.secretAc",
"end": 12727,
"score": 0.9011265635490417,
"start": 12723,
"tag": "KEY",
"value": "AKID"
},
{
"context": "creds.masterCredentials.secretAccessKey).toEqual('SECRET')\n AWS.config.credentials = origCreds\n\n\n de",
"end": 12801,
"score": 0.6100767254829407,
"start": 12795,
"tag": "KEY",
"value": "SECRET"
},
{
"context": "EY')\n expect(creds.secretAccessKey).toEqual('SECRET')\n expect(creds.sessionToken).toEqual('TOKEN",
"end": 13332,
"score": 0.5676300525665283,
"start": 13326,
"tag": "KEY",
"value": "SECRET"
},
{
"context": " AccessKeyId: 'KEY'\n SecretAccessKey: 'SECRET'\n SessionToken: 'TOKEN'\n Expirati",
"end": 14819,
"score": 0.9284001588821411,
"start": 14813,
"tag": "KEY",
"value": "SECRET"
},
{
"context": " AccessKeyId: 'KEY'\n SecretAccessKey: 'SECRET'\n SessionToken: 'TOKEN'\n Expiration: ",
"end": 16189,
"score": 0.5000826120376587,
"start": 16183,
"tag": "KEY",
"value": "SECRET"
}
] | back-api/node_modules/aws-sdk/test/credentials.spec.coffee | rannysan/trabwebt02 | 31 | helpers = require('./helpers')
AWS = helpers.AWS
validateCredentials = (creds, key, secret, session) ->
expect(creds.accessKeyId).toEqual(key || 'akid')
expect(creds.secretAccessKey).toEqual(secret || 'secret')
expect(creds.sessionToken).toEqual(session || 'session')
describe 'AWS.Credentials', ->
describe 'constructor', ->
it 'should allow setting of credentials with keys', ->
config = new AWS.Config(
accessKeyId: 'akid'
secretAccessKey: 'secret'
sessionToken: 'session'
)
validateCredentials(config.credentials)
it 'should allow setting of credentials as object', ->
creds =
accessKeyId: 'akid'
secretAccessKey: 'secret'
sessionToken: 'session'
validateCredentials(new AWS.Credentials(creds))
it 'defaults credentials to undefined when not passed', ->
creds = new AWS.Credentials()
expect(creds.accessKeyId).toBe(undefined)
expect(creds.secretAccessKey).toBe(undefined)
expect(creds.sessionToken).toBe(undefined)
describe 'needsRefresh', ->
it 'needs refresh if credentials are not set', ->
creds = new AWS.Credentials()
expect(creds.needsRefresh()).toEqual(true)
creds = new AWS.Credentials('akid')
expect(creds.needsRefresh()).toEqual(true)
it 'does not need refresh if credentials are set', ->
creds = new AWS.Credentials('akid', 'secret')
expect(creds.needsRefresh()).toEqual(false)
it 'needs refresh if creds are expired', ->
creds = new AWS.Credentials('akid', 'secret')
creds.expired = true
expect(creds.needsRefresh()).toEqual(true)
it 'can be expired based on expireTime', ->
creds = new AWS.Credentials('akid', 'secret')
creds.expired = false
creds.expireTime = new Date(0)
expect(creds.needsRefresh()).toEqual(true)
it 'needs refresh if expireTime is within expiryWindow secs from now', ->
creds = new AWS.Credentials('akid', 'secret')
creds.expired = false
creds.expireTime = new Date(AWS.util.date.getDate().getTime() + 1000)
expect(creds.needsRefresh()).toEqual(true)
it 'does not need refresh if expireTime outside expiryWindow', ->
creds = new AWS.Credentials('akid', 'secret')
creds.expired = false
ms = AWS.util.date.getDate().getTime() + (creds.expiryWindow + 5) * 1000
creds.expireTime = new Date(ms)
expect(creds.needsRefresh()).toEqual(false)
describe 'get', ->
it 'does not call refresh if not needsRefresh', ->
spy = jasmine.createSpy('done callback')
creds = new AWS.Credentials('akid', 'secret')
refresh = spyOn(creds, 'refresh')
creds.get(spy)
expect(refresh).not.toHaveBeenCalled()
expect(spy).toHaveBeenCalled()
expect(spy.argsForCall[0][0]).toEqual(null)
expect(creds.expired).toEqual(false)
it 'calls refresh only if needsRefresh', ->
spy = jasmine.createSpy('done callback')
creds = new AWS.Credentials('akid', 'secret')
creds.expired = true
refresh = spyOn(creds, 'refresh').andCallThrough()
creds.get(spy)
expect(refresh).toHaveBeenCalled()
expect(spy).toHaveBeenCalled()
expect(spy.argsForCall[0][0]).toEqual(null)
expect(creds.expired).toEqual(false)
if AWS.util.isNode()
describe 'AWS.EnvironmentCredentials', ->
beforeEach ->
process.env = {}
describe 'constructor', ->
it 'should be able to read credentials from env with a prefix', ->
process.env.AWS_ACCESS_KEY_ID = 'akid'
process.env.AWS_SECRET_ACCESS_KEY = 'secret'
process.env.AWS_SESSION_TOKEN = 'session'
creds = new AWS.EnvironmentCredentials('AWS')
validateCredentials(creds)
it 'should be able to read credentials from env without a prefix', ->
process.env.ACCESS_KEY_ID = 'akid'
process.env.SECRET_ACCESS_KEY = 'secret'
process.env.SESSION_TOKEN = 'session'
creds = new AWS.EnvironmentCredentials()
validateCredentials(creds)
describe 'refresh', ->
it 'can refresh credentials', ->
process.env.AWS_ACCESS_KEY_ID = 'akid'
process.env.AWS_SECRET_ACCESS_KEY = 'secret'
creds = new AWS.EnvironmentCredentials('AWS')
expect(creds.accessKeyId).toEqual('akid')
creds.accessKeyId = 'not_akid'
expect(creds.accessKeyId).not.toEqual('akid')
creds.refresh()
expect(creds.accessKeyId).toEqual('akid')
describe 'AWS.FileSystemCredentials', ->
describe 'constructor', ->
it 'should accept filename and load credentials from root doc', ->
mock = '{"accessKeyId":"akid", "secretAccessKey":"secret","sessionToken":"session"}'
spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.FileSystemCredentials('foo')
validateCredentials(creds)
it 'should accept filename and load credentials from credentials block', ->
mock = '{"credentials":{"accessKeyId":"akid", "secretAccessKey":"secret","sessionToken":"session"}}'
spy = spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.FileSystemCredentials('foo')
validateCredentials(creds)
describe 'refresh', ->
it 'should refresh from given filename', ->
mock = '{"credentials":{"accessKeyId":"RELOADED", "secretAccessKey":"RELOADED","sessionToken":"RELOADED"}}'
spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.FileSystemCredentials('foo')
validateCredentials(creds, 'RELOADED', 'RELOADED', 'RELOADED')
it 'fails if credentials are not in the file', ->
mock = '{"credentials":{}}'
spyOn(AWS.util, 'readFileSync').andReturn(mock)
new AWS.FileSystemCredentials('foo').refresh (err) ->
expect(err.message).toEqual('Credentials not set in foo')
expect(-> new AWS.FileSystemCredentials('foo').refresh()).
toThrow('Credentials not set in foo')
describe 'AWS.SharedIniFileCredentials', ->
beforeEach ->
delete process.env.AWS_PROFILE
delete process.env.HOME
delete process.env.HOMEPATH
delete process.env.USERPROFILE
describe 'constructor', ->
it 'throws an error if HOME/HOMEPATH/USERPROFILE are not set', ->
expect(-> new AWS.SharedIniFileCredentials().refresh()).
toThrow('Cannot load credentials, HOME path not set')
it 'uses HOMEPATH if HOME is not set', ->
process.env.HOMEPATH = '/homepath'
creds = new AWS.SharedIniFileCredentials()
expect(creds.filename).toEqual('/homepath/.aws/credentials')
it 'uses USERPROFILE if HOME and HOMEPATH are not set', ->
process.env.USERPROFILE = '/userprofile'
creds = new AWS.SharedIniFileCredentials()
expect(creds.filename).toEqual('/userprofile/.aws/credentials')
it 'can override filename as a constructor argument', ->
creds = new AWS.SharedIniFileCredentials(filename: '/etc/creds')
expect(creds.filename).toEqual('/etc/creds')
describe 'loading', ->
beforeEach -> process.env.HOME = '/home/user'
it 'loads credentials from ~/.aws/credentials using default profile', ->
mock = '''
[default]
aws_access_key_id = akid
aws_secret_access_key = secret
aws_session_token = session
'''
spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.SharedIniFileCredentials()
validateCredentials(creds)
expect(AWS.util.readFileSync.calls[0].args[0]).toEqual('/home/user/.aws/credentials')
it 'loads the default profile if AWS_PROFILE is empty', ->
process.env.AWS_PROFILE = ''
mock = '''
[default]
aws_access_key_id = akid
aws_secret_access_key = secret
aws_session_token = session
'''
spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.SharedIniFileCredentials()
validateCredentials(creds)
it 'accepts a profile name parameter', ->
mock = '''
[foo]
aws_access_key_id = akid
aws_secret_access_key = secret
aws_session_token = session
'''
spy = spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.SharedIniFileCredentials(profile: 'foo')
validateCredentials(creds)
it 'sets profile based on ENV', ->
process.env.AWS_PROFILE = 'foo'
mock = '''
[foo]
aws_access_key_id = akid
aws_secret_access_key = secret
aws_session_token = session
'''
spy = spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.SharedIniFileCredentials()
validateCredentials(creds)
describe 'refresh', ->
beforeEach -> process.env.HOME = '/home/user'
it 'should refresh from disk', ->
mock = '''
[default]
aws_access_key_id = RELOADED
aws_secret_access_key = RELOADED
aws_session_token = RELOADED
'''
spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.SharedIniFileCredentials()
validateCredentials(creds, 'RELOADED', 'RELOADED', 'RELOADED')
it 'fails if credentials are not in the file', ->
mock = ''
spyOn(AWS.util, 'readFileSync').andReturn(mock)
new AWS.SharedIniFileCredentials().refresh (err) ->
expect(err.message).toEqual('Credentials not set in /home/user/.aws/credentials using profile default')
expect(-> new AWS.SharedIniFileCredentials().refresh()).
toThrow('Credentials not set in /home/user/.aws/credentials using profile default')
describe 'AWS.EC2MetadataCredentials', ->
creds = null
beforeEach ->
creds = new AWS.EC2MetadataCredentials(host: 'host')
mockMetadataService = (expireTime) ->
spyOn(creds.metadataService, 'loadCredentials').andCallFake (cb) ->
cb null,
Code: 'Success'
AccessKeyId: 'KEY'
SecretAccessKey: 'SECRET'
Token: 'TOKEN'
Expiration: expireTime.toISOString()
describe 'constructor', ->
it 'allows passing of AWS.MetadataService options', ->
expect(creds.metadataService.host).toEqual('host')
describe 'needsRefresh', ->
it 'can be expired based on expire time from EC2 Metadata service', ->
mockMetadataService(new Date(0))
creds.refresh(->)
expect(creds.needsRefresh()).toEqual(true)
describe 'refresh', ->
it 'loads credentials from EC2 Metadata service', ->
mockMetadataService(new Date(AWS.util.date.getDate().getTime() + 100000))
creds.refresh(->)
expect(creds.metadata.Code).toEqual('Success')
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.needsRefresh()).toEqual(false)
it 'does try to load creds second time if Metadata service failed', ->
spy = spyOn(creds.metadataService, 'loadCredentials').andCallFake (cb) ->
cb(new Error('INVALID SERVICE'))
creds.refresh (err) ->
expect(err.message).toEqual('INVALID SERVICE')
creds.refresh ->
creds.refresh ->
creds.refresh ->
expect(spy.calls.length).toEqual(4)
describe 'AWS.TemporaryCredentials', ->
creds = null
beforeEach ->
creds = new AWS.TemporaryCredentials(DurationSeconds: 1200)
mockSTS = (expireTime, inParams) ->
if !inParams
inParams = DurationSeconds: 1200
if inParams.RoleArn
operation = 'assumeRole'
else
operation = 'getSessionToken'
spyOn(creds.service, operation).andCallFake (params, cb) ->
expect(params).toEqual(inParams)
cb null, Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: 'SECRET'
SessionToken: 'TOKEN'
Expiration: expireTime
describe 'masterCredentials', ->
it 'seeds masterCredentials from global credentials', ->
origCreds = AWS.config.credentials
AWS.config.credentials = new AWS.Credentials('AKID', 'SECRET')
creds = new AWS.TemporaryCredentials()
expect(creds.masterCredentials.accessKeyId).toEqual('AKID')
expect(creds.masterCredentials.secretAccessKey).toEqual('SECRET')
AWS.config.credentials = origCreds
it 'seeds masterCredentials from temporary credentials', ->
origCreds = AWS.config.credentials
AWS.config.credentials = new AWS.Credentials('AKID', 'SECRET')
for i in [0..3]
creds = new AWS.TemporaryCredentials()
expect(creds.masterCredentials.accessKeyId).toEqual('AKID')
expect(creds.masterCredentials.secretAccessKey).toEqual('SECRET')
AWS.config.credentials = origCreds
describe 'needsRefresh', ->
it 'can be expired based on expire time from STS response', ->
mockSTS(new Date(0))
creds.refresh(->)
expect(creds.needsRefresh()).toEqual(true)
describe 'refresh', ->
it 'loads temporary credentials from STS using getSessionToken', ->
mockSTS(new Date(AWS.util.date.getDate().getTime() + 100000))
creds.refresh(->)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.needsRefresh()).toEqual(false)
it 'loads temporary credentials from STS using assumeRole if RoleArn is provided', ->
creds = new AWS.TemporaryCredentials(RoleArn: 'ARN')
mockSTS(new Date(AWS.util.date.getDate().getTime() + 100000),
RoleArn: 'ARN', RoleSessionName: 'temporary-credentials')
creds.refresh(->)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.needsRefresh()).toEqual(false)
it 'does try to load creds second time if service request failed', ->
spy = spyOn(creds.service, 'getSessionToken').andCallFake (params, cb) ->
cb(new Error('INVALID SERVICE'))
creds.refresh (err) ->
expect(err.message).toEqual('INVALID SERVICE')
creds.refresh ->
creds.refresh ->
creds.refresh ->
expect(spy.calls.length).toEqual(4)
describe 'AWS.WebIdentityCredentials', ->
creds = null
beforeEach ->
creds = new AWS.WebIdentityCredentials(WebIdentityToken: 'token', RoleArn: 'arn')
mockSTS = (expireTime) ->
spyOn(creds.service, 'assumeRoleWithWebIdentity').andCallFake (params, cb) ->
expect(params).toEqual(RoleArn: 'arn', WebIdentityToken: 'token', RoleSessionName: 'web-identity')
cb null,
Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: 'SECRET'
SessionToken: 'TOKEN'
Expiration: expireTime
OtherProperty: true
describe 'refresh', ->
it 'loads federated credentials from STS', ->
mockSTS(new Date(AWS.util.date.getDate().getTime() + 100000))
creds.refresh(->)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.needsRefresh()).toEqual(false)
expect(creds.data.OtherProperty).toEqual(true)
it 'does try to load creds second time if service request failed', ->
spy = spyOn(creds.service, 'assumeRoleWithWebIdentity').andCallFake (params, cb) ->
cb(new Error('INVALID SERVICE'))
creds.refresh (err) ->
expect(err.message).toEqual('INVALID SERVICE')
creds.refresh ->
creds.refresh ->
creds.refresh ->
expect(spy.calls.length).toEqual(4)
describe 'AWS.SAMLCredentials', ->
creds = null
beforeEach ->
creds = new AWS.SAMLCredentials(SAMLAssertion: 'token', RoleArn: 'arn', PrincipalArn: 'arn')
mockSTS = (expireTime) ->
spyOn(creds.service, 'assumeRoleWithSAML').andCallFake (params, cb) ->
expect(params).toEqual(SAMLAssertion: 'token', RoleArn: 'arn', PrincipalArn: 'arn')
cb null, Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: 'SECRET'
SessionToken: 'TOKEN'
Expiration: expireTime
describe 'refresh', ->
it 'loads federated credentials from STS', ->
mockSTS(new Date(AWS.util.date.getDate().getTime() + 100000))
creds.refresh(->)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.needsRefresh()).toEqual(false)
it 'does try to load creds second time if service request failed', ->
spy = spyOn(creds.service, 'assumeRoleWithSAML').andCallFake (params, cb) ->
cb(new Error('INVALID SERVICE'))
creds.refresh (err) ->
expect(err.message).toEqual('INVALID SERVICE')
creds.refresh ->
creds.refresh ->
creds.refresh ->
expect(spy.calls.length).toEqual(4)
| 108639 | helpers = require('./helpers')
AWS = helpers.AWS
validateCredentials = (creds, key, secret, session) ->
expect(creds.accessKeyId).toEqual(key || 'akid')
expect(creds.secretAccessKey).toEqual(secret || '<KEY>')
expect(creds.sessionToken).toEqual(session || 'session')
describe 'AWS.Credentials', ->
describe 'constructor', ->
it 'should allow setting of credentials with keys', ->
config = new AWS.Config(
accessKeyId: '<KEY>'
secretAccessKey: '<KEY>'
sessionToken: '<PASSWORD>'
)
validateCredentials(config.credentials)
it 'should allow setting of credentials as object', ->
creds =
accessKeyId: '<KEY>'
secretAccessKey: '<KEY>'
sessionToken: 'session'
validateCredentials(new AWS.Credentials(creds))
it 'defaults credentials to undefined when not passed', ->
creds = new AWS.Credentials()
expect(creds.accessKeyId).toBe(undefined)
expect(creds.secretAccessKey).toBe(undefined)
expect(creds.sessionToken).toBe(undefined)
describe 'needsRefresh', ->
it 'needs refresh if credentials are not set', ->
creds = new AWS.Credentials()
expect(creds.needsRefresh()).toEqual(true)
creds = new AWS.Credentials('akid')
expect(creds.needsRefresh()).toEqual(true)
it 'does not need refresh if credentials are set', ->
creds = new AWS.Credentials('akid', 'secret')
expect(creds.needsRefresh()).toEqual(false)
it 'needs refresh if creds are expired', ->
creds = new AWS.Credentials('akid', 'secret')
creds.expired = true
expect(creds.needsRefresh()).toEqual(true)
it 'can be expired based on expireTime', ->
creds = new AWS.Credentials('akid', 'secret')
creds.expired = false
creds.expireTime = new Date(0)
expect(creds.needsRefresh()).toEqual(true)
it 'needs refresh if expireTime is within expiryWindow secs from now', ->
creds = new AWS.Credentials('akid', 'secret')
creds.expired = false
creds.expireTime = new Date(AWS.util.date.getDate().getTime() + 1000)
expect(creds.needsRefresh()).toEqual(true)
it 'does not need refresh if expireTime outside expiryWindow', ->
creds = new AWS.Credentials('akid', 'secret')
creds.expired = false
ms = AWS.util.date.getDate().getTime() + (creds.expiryWindow + 5) * 1000
creds.expireTime = new Date(ms)
expect(creds.needsRefresh()).toEqual(false)
describe 'get', ->
it 'does not call refresh if not needsRefresh', ->
spy = jasmine.createSpy('done callback')
creds = new AWS.Credentials('akid', 'secret')
refresh = spyOn(creds, 'refresh')
creds.get(spy)
expect(refresh).not.toHaveBeenCalled()
expect(spy).toHaveBeenCalled()
expect(spy.argsForCall[0][0]).toEqual(null)
expect(creds.expired).toEqual(false)
it 'calls refresh only if needsRefresh', ->
spy = jasmine.createSpy('done callback')
creds = new AWS.Credentials('akid', 'secret')
creds.expired = true
refresh = spyOn(creds, 'refresh').andCallThrough()
creds.get(spy)
expect(refresh).toHaveBeenCalled()
expect(spy).toHaveBeenCalled()
expect(spy.argsForCall[0][0]).toEqual(null)
expect(creds.expired).toEqual(false)
if AWS.util.isNode()
describe 'AWS.EnvironmentCredentials', ->
beforeEach ->
process.env = {}
describe 'constructor', ->
it 'should be able to read credentials from env with a prefix', ->
process.env.AWS_ACCESS_KEY_ID = '<KEY>'
process.env.AWS_SECRET_ACCESS_KEY = '<KEY>'
process.env.AWS_SESSION_TOKEN = 'session'
creds = new AWS.EnvironmentCredentials('AWS')
validateCredentials(creds)
it 'should be able to read credentials from env without a prefix', ->
process.env.ACCESS_KEY_ID = '<KEY>'
process.env.SECRET_ACCESS_KEY = '<KEY>'
process.env.SESSION_TOKEN = 'session'
creds = new AWS.EnvironmentCredentials()
validateCredentials(creds)
describe 'refresh', ->
it 'can refresh credentials', ->
process.env.AWS_ACCESS_KEY_ID = '<KEY>'
process.env.AWS_SECRET_ACCESS_KEY = '<KEY>'
creds = new AWS.EnvironmentCredentials('AWS')
expect(creds.accessKeyId).toEqual('<KEY>')
creds.accessKeyId = '<KEY>'
expect(creds.accessKeyId).not.toEqual('<KEY>')
creds.refresh()
expect(creds.accessKeyId).toEqual('<KEY>')
describe 'AWS.FileSystemCredentials', ->
describe 'constructor', ->
it 'should accept filename and load credentials from root doc', ->
mock = '{"accessKeyId":"<KEY>", "secretAccessKey":"<KEY>","sessionToken":"session"}'
spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.FileSystemCredentials('foo')
validateCredentials(creds)
it 'should accept filename and load credentials from credentials block', ->
mock = '{"credentials":{"accessKeyId":"<KEY>", "secretAccessKey":"<KEY>","sessionToken":"session"}}'
spy = spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.FileSystemCredentials('foo')
validateCredentials(creds)
describe 'refresh', ->
it 'should refresh from given filename', ->
mock = '{"credentials":{"accessKeyId":"RELOADED", "secretAccessKey":"RELOADED","sessionToken":"RELOADED"}}'
spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.FileSystemCredentials('foo')
validateCredentials(creds, 'RELOADED', 'RELOADED', 'RELOADED')
it 'fails if credentials are not in the file', ->
mock = '{"credentials":{}}'
spyOn(AWS.util, 'readFileSync').andReturn(mock)
new AWS.FileSystemCredentials('foo').refresh (err) ->
expect(err.message).toEqual('Credentials not set in foo')
expect(-> new AWS.FileSystemCredentials('foo').refresh()).
toThrow('Credentials not set in foo')
describe 'AWS.SharedIniFileCredentials', ->
beforeEach ->
delete process.env.AWS_PROFILE
delete process.env.HOME
delete process.env.HOMEPATH
delete process.env.USERPROFILE
describe 'constructor', ->
it 'throws an error if HOME/HOMEPATH/USERPROFILE are not set', ->
expect(-> new AWS.SharedIniFileCredentials().refresh()).
toThrow('Cannot load credentials, HOME path not set')
it 'uses HOMEPATH if HOME is not set', ->
process.env.HOMEPATH = '/homepath'
creds = new AWS.SharedIniFileCredentials()
expect(creds.filename).toEqual('/homepath/.aws/credentials')
it 'uses USERPROFILE if HOME and HOMEPATH are not set', ->
process.env.USERPROFILE = '/userprofile'
creds = new AWS.SharedIniFileCredentials()
expect(creds.filename).toEqual('/userprofile/.aws/credentials')
it 'can override filename as a constructor argument', ->
creds = new AWS.SharedIniFileCredentials(filename: '/etc/creds')
expect(creds.filename).toEqual('/etc/creds')
describe 'loading', ->
beforeEach -> process.env.HOME = '/home/user'
it 'loads credentials from ~/.aws/credentials using default profile', ->
mock = '''
[default]
aws_access_key_id = <KEY>
aws_secret_access_key = secret
aws_session_token = session
'''
spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.SharedIniFileCredentials()
validateCredentials(creds)
expect(AWS.util.readFileSync.calls[0].args[0]).toEqual('/home/user/.aws/credentials')
it 'loads the default profile if AWS_PROFILE is empty', ->
process.env.AWS_PROFILE = ''
mock = '''
[default]
aws_access_key_id = <KEY>
aws_secret_access_key = secret
aws_session_token = session
'''
spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.SharedIniFileCredentials()
validateCredentials(creds)
it 'accepts a profile name parameter', ->
mock = '''
[foo]
aws_access_key_id = <KEY>
aws_secret_access_key = secret
aws_session_token = session
'''
spy = spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.SharedIniFileCredentials(profile: 'foo')
validateCredentials(creds)
it 'sets profile based on ENV', ->
process.env.AWS_PROFILE = 'foo'
mock = '''
[foo]
aws_access_key_id = <KEY>
aws_secret_access_key = secret
aws_session_token = session
'''
spy = spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.SharedIniFileCredentials()
validateCredentials(creds)
describe 'refresh', ->
beforeEach -> process.env.HOME = '/home/user'
it 'should refresh from disk', ->
mock = '''
[default]
aws_access_key_id = RELOADED
aws_secret_access_key = RELOADED
aws_session_token = RELOADED
'''
spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.SharedIniFileCredentials()
validateCredentials(creds, 'RELOADED', 'RELOADED', 'RELOADED')
it 'fails if credentials are not in the file', ->
mock = ''
spyOn(AWS.util, 'readFileSync').andReturn(mock)
new AWS.SharedIniFileCredentials().refresh (err) ->
expect(err.message).toEqual('Credentials not set in /home/user/.aws/credentials using profile default')
expect(-> new AWS.SharedIniFileCredentials().refresh()).
toThrow('Credentials not set in /home/user/.aws/credentials using profile default')
describe 'AWS.EC2MetadataCredentials', ->
creds = null
beforeEach ->
creds = new AWS.EC2MetadataCredentials(host: 'host')
mockMetadataService = (expireTime) ->
spyOn(creds.metadataService, 'loadCredentials').andCallFake (cb) ->
cb null,
Code: 'Success'
AccessKeyId: 'KEY'
SecretAccessKey: '<KEY>'
Token: '<KEY>'
Expiration: expireTime.toISOString()
describe 'constructor', ->
it 'allows passing of AWS.MetadataService options', ->
expect(creds.metadataService.host).toEqual('host')
describe 'needsRefresh', ->
it 'can be expired based on expire time from EC2 Metadata service', ->
mockMetadataService(new Date(0))
creds.refresh(->)
expect(creds.needsRefresh()).toEqual(true)
describe 'refresh', ->
it 'loads credentials from EC2 Metadata service', ->
mockMetadataService(new Date(AWS.util.date.getDate().getTime() + 100000))
creds.refresh(->)
expect(creds.metadata.Code).toEqual('Success')
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('<KEY>')
expect(creds.sessionToken).toEqual('<KEY>')
expect(creds.needsRefresh()).toEqual(false)
it 'does try to load creds second time if Metadata service failed', ->
spy = spyOn(creds.metadataService, 'loadCredentials').andCallFake (cb) ->
cb(new Error('INVALID SERVICE'))
creds.refresh (err) ->
expect(err.message).toEqual('INVALID SERVICE')
creds.refresh ->
creds.refresh ->
creds.refresh ->
expect(spy.calls.length).toEqual(4)
describe 'AWS.TemporaryCredentials', ->
creds = null
beforeEach ->
creds = new AWS.TemporaryCredentials(DurationSeconds: 1200)
mockSTS = (expireTime, inParams) ->
if !inParams
inParams = DurationSeconds: 1200
if inParams.RoleArn
operation = 'assumeRole'
else
operation = 'getSessionToken'
spyOn(creds.service, operation).andCallFake (params, cb) ->
expect(params).toEqual(inParams)
cb null, Credentials:
AccessKeyId: '<KEY>'
SecretAccessKey: '<KEY>'
SessionToken: 'TOKEN'
Expiration: expireTime
describe 'masterCredentials', ->
it 'seeds masterCredentials from global credentials', ->
origCreds = AWS.config.credentials
AWS.config.credentials = new AWS.Credentials('AKID', 'SECRET')
creds = new AWS.TemporaryCredentials()
expect(creds.masterCredentials.accessKeyId).toEqual('<KEY>')
expect(creds.masterCredentials.secretAccessKey).toEqual('SECRET')
AWS.config.credentials = origCreds
it 'seeds masterCredentials from temporary credentials', ->
origCreds = AWS.config.credentials
AWS.config.credentials = new AWS.Credentials('AKID', 'SECRET')
for i in [0..3]
creds = new AWS.TemporaryCredentials()
expect(creds.masterCredentials.accessKeyId).toEqual('<KEY>')
expect(creds.masterCredentials.secretAccessKey).toEqual('<KEY>')
AWS.config.credentials = origCreds
describe 'needsRefresh', ->
it 'can be expired based on expire time from STS response', ->
mockSTS(new Date(0))
creds.refresh(->)
expect(creds.needsRefresh()).toEqual(true)
describe 'refresh', ->
it 'loads temporary credentials from STS using getSessionToken', ->
mockSTS(new Date(AWS.util.date.getDate().getTime() + 100000))
creds.refresh(->)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('<KEY>')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.needsRefresh()).toEqual(false)
it 'loads temporary credentials from STS using assumeRole if RoleArn is provided', ->
creds = new AWS.TemporaryCredentials(RoleArn: 'ARN')
mockSTS(new Date(AWS.util.date.getDate().getTime() + 100000),
RoleArn: 'ARN', RoleSessionName: 'temporary-credentials')
creds.refresh(->)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.needsRefresh()).toEqual(false)
it 'does try to load creds second time if service request failed', ->
spy = spyOn(creds.service, 'getSessionToken').andCallFake (params, cb) ->
cb(new Error('INVALID SERVICE'))
creds.refresh (err) ->
expect(err.message).toEqual('INVALID SERVICE')
creds.refresh ->
creds.refresh ->
creds.refresh ->
expect(spy.calls.length).toEqual(4)
describe 'AWS.WebIdentityCredentials', ->
creds = null
beforeEach ->
creds = new AWS.WebIdentityCredentials(WebIdentityToken: 'token', RoleArn: 'arn')
mockSTS = (expireTime) ->
spyOn(creds.service, 'assumeRoleWithWebIdentity').andCallFake (params, cb) ->
expect(params).toEqual(RoleArn: 'arn', WebIdentityToken: 'token', RoleSessionName: 'web-identity')
cb null,
Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: '<KEY>'
SessionToken: 'TOKEN'
Expiration: expireTime
OtherProperty: true
describe 'refresh', ->
it 'loads federated credentials from STS', ->
mockSTS(new Date(AWS.util.date.getDate().getTime() + 100000))
creds.refresh(->)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.needsRefresh()).toEqual(false)
expect(creds.data.OtherProperty).toEqual(true)
it 'does try to load creds second time if service request failed', ->
spy = spyOn(creds.service, 'assumeRoleWithWebIdentity').andCallFake (params, cb) ->
cb(new Error('INVALID SERVICE'))
creds.refresh (err) ->
expect(err.message).toEqual('INVALID SERVICE')
creds.refresh ->
creds.refresh ->
creds.refresh ->
expect(spy.calls.length).toEqual(4)
describe 'AWS.SAMLCredentials', ->
creds = null
beforeEach ->
creds = new AWS.SAMLCredentials(SAMLAssertion: 'token', RoleArn: 'arn', PrincipalArn: 'arn')
mockSTS = (expireTime) ->
spyOn(creds.service, 'assumeRoleWithSAML').andCallFake (params, cb) ->
expect(params).toEqual(SAMLAssertion: 'token', RoleArn: 'arn', PrincipalArn: 'arn')
cb null, Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: '<KEY>'
SessionToken: 'TOKEN'
Expiration: expireTime
describe 'refresh', ->
it 'loads federated credentials from STS', ->
mockSTS(new Date(AWS.util.date.getDate().getTime() + 100000))
creds.refresh(->)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.needsRefresh()).toEqual(false)
it 'does try to load creds second time if service request failed', ->
spy = spyOn(creds.service, 'assumeRoleWithSAML').andCallFake (params, cb) ->
cb(new Error('INVALID SERVICE'))
creds.refresh (err) ->
expect(err.message).toEqual('INVALID SERVICE')
creds.refresh ->
creds.refresh ->
creds.refresh ->
expect(spy.calls.length).toEqual(4)
| true | helpers = require('./helpers')
AWS = helpers.AWS
validateCredentials = (creds, key, secret, session) ->
expect(creds.accessKeyId).toEqual(key || 'akid')
expect(creds.secretAccessKey).toEqual(secret || 'PI:KEY:<KEY>END_PI')
expect(creds.sessionToken).toEqual(session || 'session')
describe 'AWS.Credentials', ->
describe 'constructor', ->
it 'should allow setting of credentials with keys', ->
config = new AWS.Config(
accessKeyId: 'PI:KEY:<KEY>END_PI'
secretAccessKey: 'PI:KEY:<KEY>END_PI'
sessionToken: 'PI:PASSWORD:<PASSWORD>END_PI'
)
validateCredentials(config.credentials)
it 'should allow setting of credentials as object', ->
creds =
accessKeyId: 'PI:KEY:<KEY>END_PI'
secretAccessKey: 'PI:KEY:<KEY>END_PI'
sessionToken: 'session'
validateCredentials(new AWS.Credentials(creds))
it 'defaults credentials to undefined when not passed', ->
creds = new AWS.Credentials()
expect(creds.accessKeyId).toBe(undefined)
expect(creds.secretAccessKey).toBe(undefined)
expect(creds.sessionToken).toBe(undefined)
describe 'needsRefresh', ->
it 'needs refresh if credentials are not set', ->
creds = new AWS.Credentials()
expect(creds.needsRefresh()).toEqual(true)
creds = new AWS.Credentials('akid')
expect(creds.needsRefresh()).toEqual(true)
it 'does not need refresh if credentials are set', ->
creds = new AWS.Credentials('akid', 'secret')
expect(creds.needsRefresh()).toEqual(false)
it 'needs refresh if creds are expired', ->
creds = new AWS.Credentials('akid', 'secret')
creds.expired = true
expect(creds.needsRefresh()).toEqual(true)
it 'can be expired based on expireTime', ->
creds = new AWS.Credentials('akid', 'secret')
creds.expired = false
creds.expireTime = new Date(0)
expect(creds.needsRefresh()).toEqual(true)
it 'needs refresh if expireTime is within expiryWindow secs from now', ->
creds = new AWS.Credentials('akid', 'secret')
creds.expired = false
creds.expireTime = new Date(AWS.util.date.getDate().getTime() + 1000)
expect(creds.needsRefresh()).toEqual(true)
it 'does not need refresh if expireTime outside expiryWindow', ->
creds = new AWS.Credentials('akid', 'secret')
creds.expired = false
ms = AWS.util.date.getDate().getTime() + (creds.expiryWindow + 5) * 1000
creds.expireTime = new Date(ms)
expect(creds.needsRefresh()).toEqual(false)
describe 'get', ->
it 'does not call refresh if not needsRefresh', ->
spy = jasmine.createSpy('done callback')
creds = new AWS.Credentials('akid', 'secret')
refresh = spyOn(creds, 'refresh')
creds.get(spy)
expect(refresh).not.toHaveBeenCalled()
expect(spy).toHaveBeenCalled()
expect(spy.argsForCall[0][0]).toEqual(null)
expect(creds.expired).toEqual(false)
it 'calls refresh only if needsRefresh', ->
spy = jasmine.createSpy('done callback')
creds = new AWS.Credentials('akid', 'secret')
creds.expired = true
refresh = spyOn(creds, 'refresh').andCallThrough()
creds.get(spy)
expect(refresh).toHaveBeenCalled()
expect(spy).toHaveBeenCalled()
expect(spy.argsForCall[0][0]).toEqual(null)
expect(creds.expired).toEqual(false)
if AWS.util.isNode()
describe 'AWS.EnvironmentCredentials', ->
beforeEach ->
process.env = {}
describe 'constructor', ->
it 'should be able to read credentials from env with a prefix', ->
process.env.AWS_ACCESS_KEY_ID = 'PI:KEY:<KEY>END_PI'
process.env.AWS_SECRET_ACCESS_KEY = 'PI:KEY:<KEY>END_PI'
process.env.AWS_SESSION_TOKEN = 'session'
creds = new AWS.EnvironmentCredentials('AWS')
validateCredentials(creds)
it 'should be able to read credentials from env without a prefix', ->
process.env.ACCESS_KEY_ID = 'PI:KEY:<KEY>END_PI'
process.env.SECRET_ACCESS_KEY = 'PI:KEY:<KEY>END_PI'
process.env.SESSION_TOKEN = 'session'
creds = new AWS.EnvironmentCredentials()
validateCredentials(creds)
describe 'refresh', ->
it 'can refresh credentials', ->
process.env.AWS_ACCESS_KEY_ID = 'PI:KEY:<KEY>END_PI'
process.env.AWS_SECRET_ACCESS_KEY = 'PI:KEY:<KEY>END_PI'
creds = new AWS.EnvironmentCredentials('AWS')
expect(creds.accessKeyId).toEqual('PI:KEY:<KEY>END_PI')
creds.accessKeyId = 'PI:KEY:<KEY>END_PI'
expect(creds.accessKeyId).not.toEqual('PI:KEY:<KEY>END_PI')
creds.refresh()
expect(creds.accessKeyId).toEqual('PI:KEY:<KEY>END_PI')
describe 'AWS.FileSystemCredentials', ->
describe 'constructor', ->
it 'should accept filename and load credentials from root doc', ->
mock = '{"accessKeyId":"PI:KEY:<KEY>END_PI", "secretAccessKey":"PI:KEY:<KEY>END_PI","sessionToken":"session"}'
spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.FileSystemCredentials('foo')
validateCredentials(creds)
it 'should accept filename and load credentials from credentials block', ->
mock = '{"credentials":{"accessKeyId":"PI:KEY:<KEY>END_PI", "secretAccessKey":"PI:KEY:<KEY>END_PI","sessionToken":"session"}}'
spy = spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.FileSystemCredentials('foo')
validateCredentials(creds)
describe 'refresh', ->
it 'should refresh from given filename', ->
mock = '{"credentials":{"accessKeyId":"RELOADED", "secretAccessKey":"RELOADED","sessionToken":"RELOADED"}}'
spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.FileSystemCredentials('foo')
validateCredentials(creds, 'RELOADED', 'RELOADED', 'RELOADED')
it 'fails if credentials are not in the file', ->
mock = '{"credentials":{}}'
spyOn(AWS.util, 'readFileSync').andReturn(mock)
new AWS.FileSystemCredentials('foo').refresh (err) ->
expect(err.message).toEqual('Credentials not set in foo')
expect(-> new AWS.FileSystemCredentials('foo').refresh()).
toThrow('Credentials not set in foo')
describe 'AWS.SharedIniFileCredentials', ->
beforeEach ->
delete process.env.AWS_PROFILE
delete process.env.HOME
delete process.env.HOMEPATH
delete process.env.USERPROFILE
describe 'constructor', ->
it 'throws an error if HOME/HOMEPATH/USERPROFILE are not set', ->
expect(-> new AWS.SharedIniFileCredentials().refresh()).
toThrow('Cannot load credentials, HOME path not set')
it 'uses HOMEPATH if HOME is not set', ->
process.env.HOMEPATH = '/homepath'
creds = new AWS.SharedIniFileCredentials()
expect(creds.filename).toEqual('/homepath/.aws/credentials')
it 'uses USERPROFILE if HOME and HOMEPATH are not set', ->
process.env.USERPROFILE = '/userprofile'
creds = new AWS.SharedIniFileCredentials()
expect(creds.filename).toEqual('/userprofile/.aws/credentials')
it 'can override filename as a constructor argument', ->
creds = new AWS.SharedIniFileCredentials(filename: '/etc/creds')
expect(creds.filename).toEqual('/etc/creds')
describe 'loading', ->
beforeEach -> process.env.HOME = '/home/user'
it 'loads credentials from ~/.aws/credentials using default profile', ->
mock = '''
[default]
aws_access_key_id = PI:KEY:<KEY>END_PI
aws_secret_access_key = secret
aws_session_token = session
'''
spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.SharedIniFileCredentials()
validateCredentials(creds)
expect(AWS.util.readFileSync.calls[0].args[0]).toEqual('/home/user/.aws/credentials')
it 'loads the default profile if AWS_PROFILE is empty', ->
process.env.AWS_PROFILE = ''
mock = '''
[default]
aws_access_key_id = PI:KEY:<KEY>END_PI
aws_secret_access_key = secret
aws_session_token = session
'''
spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.SharedIniFileCredentials()
validateCredentials(creds)
it 'accepts a profile name parameter', ->
mock = '''
[foo]
aws_access_key_id = PI:KEY:<KEY>END_PI
aws_secret_access_key = secret
aws_session_token = session
'''
spy = spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.SharedIniFileCredentials(profile: 'foo')
validateCredentials(creds)
it 'sets profile based on ENV', ->
process.env.AWS_PROFILE = 'foo'
mock = '''
[foo]
aws_access_key_id = PI:KEY:<KEY>END_PI
aws_secret_access_key = secret
aws_session_token = session
'''
spy = spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.SharedIniFileCredentials()
validateCredentials(creds)
describe 'refresh', ->
beforeEach -> process.env.HOME = '/home/user'
it 'should refresh from disk', ->
mock = '''
[default]
aws_access_key_id = RELOADED
aws_secret_access_key = RELOADED
aws_session_token = RELOADED
'''
spyOn(AWS.util, 'readFileSync').andReturn(mock)
creds = new AWS.SharedIniFileCredentials()
validateCredentials(creds, 'RELOADED', 'RELOADED', 'RELOADED')
it 'fails if credentials are not in the file', ->
mock = ''
spyOn(AWS.util, 'readFileSync').andReturn(mock)
new AWS.SharedIniFileCredentials().refresh (err) ->
expect(err.message).toEqual('Credentials not set in /home/user/.aws/credentials using profile default')
expect(-> new AWS.SharedIniFileCredentials().refresh()).
toThrow('Credentials not set in /home/user/.aws/credentials using profile default')
describe 'AWS.EC2MetadataCredentials', ->
creds = null
beforeEach ->
creds = new AWS.EC2MetadataCredentials(host: 'host')
mockMetadataService = (expireTime) ->
spyOn(creds.metadataService, 'loadCredentials').andCallFake (cb) ->
cb null,
Code: 'Success'
AccessKeyId: 'KEY'
SecretAccessKey: 'PI:KEY:<KEY>END_PI'
Token: 'PI:KEY:<KEY>END_PI'
Expiration: expireTime.toISOString()
describe 'constructor', ->
it 'allows passing of AWS.MetadataService options', ->
expect(creds.metadataService.host).toEqual('host')
describe 'needsRefresh', ->
it 'can be expired based on expire time from EC2 Metadata service', ->
mockMetadataService(new Date(0))
creds.refresh(->)
expect(creds.needsRefresh()).toEqual(true)
describe 'refresh', ->
it 'loads credentials from EC2 Metadata service', ->
mockMetadataService(new Date(AWS.util.date.getDate().getTime() + 100000))
creds.refresh(->)
expect(creds.metadata.Code).toEqual('Success')
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('PI:KEY:<KEY>END_PI')
expect(creds.sessionToken).toEqual('PI:PASSWORD:<KEY>END_PI')
expect(creds.needsRefresh()).toEqual(false)
it 'does try to load creds second time if Metadata service failed', ->
spy = spyOn(creds.metadataService, 'loadCredentials').andCallFake (cb) ->
cb(new Error('INVALID SERVICE'))
creds.refresh (err) ->
expect(err.message).toEqual('INVALID SERVICE')
creds.refresh ->
creds.refresh ->
creds.refresh ->
expect(spy.calls.length).toEqual(4)
describe 'AWS.TemporaryCredentials', ->
creds = null
beforeEach ->
creds = new AWS.TemporaryCredentials(DurationSeconds: 1200)
mockSTS = (expireTime, inParams) ->
if !inParams
inParams = DurationSeconds: 1200
if inParams.RoleArn
operation = 'assumeRole'
else
operation = 'getSessionToken'
spyOn(creds.service, operation).andCallFake (params, cb) ->
expect(params).toEqual(inParams)
cb null, Credentials:
AccessKeyId: 'PI:KEY:<KEY>END_PI'
SecretAccessKey: 'PI:KEY:<KEY>END_PI'
SessionToken: 'TOKEN'
Expiration: expireTime
describe 'masterCredentials', ->
it 'seeds masterCredentials from global credentials', ->
origCreds = AWS.config.credentials
AWS.config.credentials = new AWS.Credentials('AKID', 'SECRET')
creds = new AWS.TemporaryCredentials()
expect(creds.masterCredentials.accessKeyId).toEqual('PI:KEY:<KEY>END_PI')
expect(creds.masterCredentials.secretAccessKey).toEqual('SECRET')
AWS.config.credentials = origCreds
it 'seeds masterCredentials from temporary credentials', ->
origCreds = AWS.config.credentials
AWS.config.credentials = new AWS.Credentials('AKID', 'SECRET')
for i in [0..3]
creds = new AWS.TemporaryCredentials()
expect(creds.masterCredentials.accessKeyId).toEqual('PI:KEY:<KEY>END_PI')
expect(creds.masterCredentials.secretAccessKey).toEqual('PI:KEY:<KEY>END_PI')
AWS.config.credentials = origCreds
describe 'needsRefresh', ->
it 'can be expired based on expire time from STS response', ->
mockSTS(new Date(0))
creds.refresh(->)
expect(creds.needsRefresh()).toEqual(true)
describe 'refresh', ->
it 'loads temporary credentials from STS using getSessionToken', ->
mockSTS(new Date(AWS.util.date.getDate().getTime() + 100000))
creds.refresh(->)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('PI:KEY:<KEY>END_PI')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.needsRefresh()).toEqual(false)
it 'loads temporary credentials from STS using assumeRole if RoleArn is provided', ->
creds = new AWS.TemporaryCredentials(RoleArn: 'ARN')
mockSTS(new Date(AWS.util.date.getDate().getTime() + 100000),
RoleArn: 'ARN', RoleSessionName: 'temporary-credentials')
creds.refresh(->)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.needsRefresh()).toEqual(false)
it 'does try to load creds second time if service request failed', ->
spy = spyOn(creds.service, 'getSessionToken').andCallFake (params, cb) ->
cb(new Error('INVALID SERVICE'))
creds.refresh (err) ->
expect(err.message).toEqual('INVALID SERVICE')
creds.refresh ->
creds.refresh ->
creds.refresh ->
expect(spy.calls.length).toEqual(4)
describe 'AWS.WebIdentityCredentials', ->
creds = null
beforeEach ->
creds = new AWS.WebIdentityCredentials(WebIdentityToken: 'token', RoleArn: 'arn')
mockSTS = (expireTime) ->
spyOn(creds.service, 'assumeRoleWithWebIdentity').andCallFake (params, cb) ->
expect(params).toEqual(RoleArn: 'arn', WebIdentityToken: 'token', RoleSessionName: 'web-identity')
cb null,
Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: 'PI:KEY:<KEY>END_PI'
SessionToken: 'TOKEN'
Expiration: expireTime
OtherProperty: true
describe 'refresh', ->
it 'loads federated credentials from STS', ->
mockSTS(new Date(AWS.util.date.getDate().getTime() + 100000))
creds.refresh(->)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.needsRefresh()).toEqual(false)
expect(creds.data.OtherProperty).toEqual(true)
it 'does try to load creds second time if service request failed', ->
spy = spyOn(creds.service, 'assumeRoleWithWebIdentity').andCallFake (params, cb) ->
cb(new Error('INVALID SERVICE'))
creds.refresh (err) ->
expect(err.message).toEqual('INVALID SERVICE')
creds.refresh ->
creds.refresh ->
creds.refresh ->
expect(spy.calls.length).toEqual(4)
describe 'AWS.SAMLCredentials', ->
creds = null
beforeEach ->
creds = new AWS.SAMLCredentials(SAMLAssertion: 'token', RoleArn: 'arn', PrincipalArn: 'arn')
mockSTS = (expireTime) ->
spyOn(creds.service, 'assumeRoleWithSAML').andCallFake (params, cb) ->
expect(params).toEqual(SAMLAssertion: 'token', RoleArn: 'arn', PrincipalArn: 'arn')
cb null, Credentials:
AccessKeyId: 'KEY'
SecretAccessKey: 'PI:KEY:<KEY>END_PI'
SessionToken: 'TOKEN'
Expiration: expireTime
describe 'refresh', ->
it 'loads federated credentials from STS', ->
mockSTS(new Date(AWS.util.date.getDate().getTime() + 100000))
creds.refresh(->)
expect(creds.accessKeyId).toEqual('KEY')
expect(creds.secretAccessKey).toEqual('SECRET')
expect(creds.sessionToken).toEqual('TOKEN')
expect(creds.needsRefresh()).toEqual(false)
it 'does try to load creds second time if service request failed', ->
spy = spyOn(creds.service, 'assumeRoleWithSAML').andCallFake (params, cb) ->
cb(new Error('INVALID SERVICE'))
creds.refresh (err) ->
expect(err.message).toEqual('INVALID SERVICE')
creds.refresh ->
creds.refresh ->
creds.refresh ->
expect(spy.calls.length).toEqual(4)
|
[
{
"context": "rage name\n# hubot encourage all\n# \n# Author:\n# WoogieNoogie\n\nremarks = [\n \"Great job, %!\",\n \"Way to go,",
"end": 215,
"score": 0.9813544154167175,
"start": 203,
"tag": "NAME",
"value": "WoogieNoogie"
}
] | scripts/encourage.coffee | hdavidzhu/goinvo-hubot | 0 | # Description:
# Robot is very encouraging
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot encourage me
# hubot encourage name
# hubot encourage all
#
# Author:
# WoogieNoogie
remarks = [
"Great job, %!",
"Way to go, %!",
"% is amazing, and everyone should be happy this amazing person is around.",
"I wish I was more like %.",
"% is good at like, 10 times more things than I am.",
"%, you are an incredibly sensitive person who inspires joyous feelings in all those around you.",
"%, you are crazy, but in a good way.",
"% has a phenomenal attitude.",
"% is a great part of the team!",
"I admire %'s strength and perseverance.",
"% is a problem-solver and cooperative teammate.",
"% is the wind beneath my wings.",
"% has a great reputation."
]
allinclusive = [
"Great job today, everyone!",
"Go team!",
"Super duper, gang!",
"If I could afford it, I would buy you all lunch!",
"What a great group of individuals there are in here. I'm proud to be chatting with you.",
"You all are capable of accomplishing whatever you set your mind to.",
"I love this team's different way of looking at things!"
]
module.exports = (robot) ->
robot.respond /(encourage )(.*)/i, (msg) ->
encourage = msg.random remarks
encouragingme = () -> msg.send encourage.replace "%", msg.message.user.name
encouragingyou = () -> msg.send encourage.replace "%", msg.match[2]
if msg.match[2] == 'me'
encouragingme()
else if msg.match[2] == 'all'
msg.send msg.random allinclusive
else
encouragingyou() | 37548 | # Description:
# Robot is very encouraging
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot encourage me
# hubot encourage name
# hubot encourage all
#
# Author:
# <NAME>
remarks = [
"Great job, %!",
"Way to go, %!",
"% is amazing, and everyone should be happy this amazing person is around.",
"I wish I was more like %.",
"% is good at like, 10 times more things than I am.",
"%, you are an incredibly sensitive person who inspires joyous feelings in all those around you.",
"%, you are crazy, but in a good way.",
"% has a phenomenal attitude.",
"% is a great part of the team!",
"I admire %'s strength and perseverance.",
"% is a problem-solver and cooperative teammate.",
"% is the wind beneath my wings.",
"% has a great reputation."
]
allinclusive = [
"Great job today, everyone!",
"Go team!",
"Super duper, gang!",
"If I could afford it, I would buy you all lunch!",
"What a great group of individuals there are in here. I'm proud to be chatting with you.",
"You all are capable of accomplishing whatever you set your mind to.",
"I love this team's different way of looking at things!"
]
module.exports = (robot) ->
robot.respond /(encourage )(.*)/i, (msg) ->
encourage = msg.random remarks
encouragingme = () -> msg.send encourage.replace "%", msg.message.user.name
encouragingyou = () -> msg.send encourage.replace "%", msg.match[2]
if msg.match[2] == 'me'
encouragingme()
else if msg.match[2] == 'all'
msg.send msg.random allinclusive
else
encouragingyou() | true | # Description:
# Robot is very encouraging
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot encourage me
# hubot encourage name
# hubot encourage all
#
# Author:
# PI:NAME:<NAME>END_PI
remarks = [
"Great job, %!",
"Way to go, %!",
"% is amazing, and everyone should be happy this amazing person is around.",
"I wish I was more like %.",
"% is good at like, 10 times more things than I am.",
"%, you are an incredibly sensitive person who inspires joyous feelings in all those around you.",
"%, you are crazy, but in a good way.",
"% has a phenomenal attitude.",
"% is a great part of the team!",
"I admire %'s strength and perseverance.",
"% is a problem-solver and cooperative teammate.",
"% is the wind beneath my wings.",
"% has a great reputation."
]
allinclusive = [
"Great job today, everyone!",
"Go team!",
"Super duper, gang!",
"If I could afford it, I would buy you all lunch!",
"What a great group of individuals there are in here. I'm proud to be chatting with you.",
"You all are capable of accomplishing whatever you set your mind to.",
"I love this team's different way of looking at things!"
]
module.exports = (robot) ->
robot.respond /(encourage )(.*)/i, (msg) ->
encourage = msg.random remarks
encouragingme = () -> msg.send encourage.replace "%", msg.message.user.name
encouragingyou = () -> msg.send encourage.replace "%", msg.match[2]
if msg.match[2] == 'me'
encouragingme()
else if msg.match[2] == 'all'
msg.send msg.random allinclusive
else
encouragingyou() |
[
{
"context": "###################################\n#\n# Created by Markus\n#\n###############################################",
"end": 77,
"score": 0.9987450242042542,
"start": 71,
"tag": "NAME",
"value": "Markus"
}
] | server/3_database/create.coffee | MooqitaSFH/worklearn | 0 | #######################################################
#
# Created by Markus
#
#######################################################
#######################################################
@store_document_unprotected = (collection, document, owner, admission)->
document["created"] = new Date()
document["modified"] = new Date()
id = collection.insert document
item = collection.findOne id
if not owner
return id
if not admission
return id
collection_name = get_collection_name collection
gen_admission collection_name, item, owner, OWNER
return id
#######################################################
@remove_documents = (collection, filter, user) ->
if typeof collection == "string"
collection = get_collection(collection)
mod =
fields:
_id: 1
items = collection.find(filter, mod).fetch()
ids = (i._id for i in items)
remove_admissions(collection, ids, user)
count = collection.remove filter
msg = count + " admissions removed by: " + get_user_mail()
log_event msg, event_db, event_info
return count
| 76770 | #######################################################
#
# Created by <NAME>
#
#######################################################
#######################################################
@store_document_unprotected = (collection, document, owner, admission)->
document["created"] = new Date()
document["modified"] = new Date()
id = collection.insert document
item = collection.findOne id
if not owner
return id
if not admission
return id
collection_name = get_collection_name collection
gen_admission collection_name, item, owner, OWNER
return id
#######################################################
@remove_documents = (collection, filter, user) ->
if typeof collection == "string"
collection = get_collection(collection)
mod =
fields:
_id: 1
items = collection.find(filter, mod).fetch()
ids = (i._id for i in items)
remove_admissions(collection, ids, user)
count = collection.remove filter
msg = count + " admissions removed by: " + get_user_mail()
log_event msg, event_db, event_info
return count
| true | #######################################################
#
# Created by PI:NAME:<NAME>END_PI
#
#######################################################
#######################################################
@store_document_unprotected = (collection, document, owner, admission)->
document["created"] = new Date()
document["modified"] = new Date()
id = collection.insert document
item = collection.findOne id
if not owner
return id
if not admission
return id
collection_name = get_collection_name collection
gen_admission collection_name, item, owner, OWNER
return id
#######################################################
@remove_documents = (collection, filter, user) ->
if typeof collection == "string"
collection = get_collection(collection)
mod =
fields:
_id: 1
items = collection.find(filter, mod).fetch()
ids = (i._id for i in items)
remove_admissions(collection, ids, user)
count = collection.remove filter
msg = count + " admissions removed by: " + get_user_mail()
log_event msg, event_db, event_info
return count
|
[
{
"context": " strings:\n user: 'Benutzername'\n pass: 'Password'\n ",
"end": 264,
"score": 0.8109416961669922,
"start": 252,
"tag": "NAME",
"value": "Benutzername"
},
{
"context": "er: 'Benutzername'\n pass: 'Password'\n login: 'Login'\n ",
"end": 305,
"score": 0.9989669322967529,
"start": 297,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": " else\n username = user\n\n span class:'username",
"end": 1260,
"score": 0.8684633374214172,
"start": 1256,
"tag": "USERNAME",
"value": "user"
}
] | modules/gui/lib/widgets/LoginForm.coffee | nero-networks/floyd | 0 |
module.exports =
class LoginForm extends floyd.gui.ViewContext
##
##
##
configure: (config)->
super new floyd.Config
data:
strings:
user: 'Benutzername'
pass: 'Password'
login: 'Login'
logout:'Logout'
minimized: false
content: ->
if @data.logo
img src:@data.logo
form method:'post', action:'#', class:'gui widgets LoginForm', ->
if !(user = @identity.login())
p class:'hint'
div (if @data.minimized then style:'display:none' else {}), ->
input name:'user', value:'', placeholder: @data.strings.user
input name:'pass', value:'', type:'password', placeholder:@data.strings.pass
if user && _fn = @data.username
if typeof _fn is 'function'
username = _fn.apply @
else
username = user
span class:'username', username
attr =
type: 'submit'
name:'button'
class: if user then 'logout' else 'login'
if cls = @data.button?.class || @data.button
attr.class = attr.class+' '+cls
title = if user then @data.strings.logout else @data.strings.login
if @data.button?.title
attr.title = title
button attr, ->
if !@data.button?.title
text title
, config
##
##
##
wire: (done)->
super (err)=>
return done(err) if err
hint = @find '.hint'
login = @find('form.gui.widgets.LoginForm')
user = login.find('input[name=user]')
pass = login.find('input[name=pass]')
button = login.find('[name=button]')
div = login.find('> div')
login.on 'submit', ()=>
hint.text('')
if @identity.login()
@_getAuthManager().logout (err)=> location.reload()
else
if div.is ':visible'
button.attr 'disabled', true
@__root.addClass 'working'
@_getAuthManager().login user.val(), pass.val(), (err)=>
button.attr 'disabled', false
@__root.removeClass 'working'
if err
pass.val ''
hint.addClass('error').text(err.message)
else
@_loginSuccess()
else div.show()
return false
done()
##
_loginSuccess: ()->
location.reload()
| 51887 |
module.exports =
class LoginForm extends floyd.gui.ViewContext
##
##
##
configure: (config)->
super new floyd.Config
data:
strings:
user: '<NAME>'
pass: '<PASSWORD>'
login: 'Login'
logout:'Logout'
minimized: false
content: ->
if @data.logo
img src:@data.logo
form method:'post', action:'#', class:'gui widgets LoginForm', ->
if !(user = @identity.login())
p class:'hint'
div (if @data.minimized then style:'display:none' else {}), ->
input name:'user', value:'', placeholder: @data.strings.user
input name:'pass', value:'', type:'password', placeholder:@data.strings.pass
if user && _fn = @data.username
if typeof _fn is 'function'
username = _fn.apply @
else
username = user
span class:'username', username
attr =
type: 'submit'
name:'button'
class: if user then 'logout' else 'login'
if cls = @data.button?.class || @data.button
attr.class = attr.class+' '+cls
title = if user then @data.strings.logout else @data.strings.login
if @data.button?.title
attr.title = title
button attr, ->
if !@data.button?.title
text title
, config
##
##
##
wire: (done)->
super (err)=>
return done(err) if err
hint = @find '.hint'
login = @find('form.gui.widgets.LoginForm')
user = login.find('input[name=user]')
pass = login.find('input[name=pass]')
button = login.find('[name=button]')
div = login.find('> div')
login.on 'submit', ()=>
hint.text('')
if @identity.login()
@_getAuthManager().logout (err)=> location.reload()
else
if div.is ':visible'
button.attr 'disabled', true
@__root.addClass 'working'
@_getAuthManager().login user.val(), pass.val(), (err)=>
button.attr 'disabled', false
@__root.removeClass 'working'
if err
pass.val ''
hint.addClass('error').text(err.message)
else
@_loginSuccess()
else div.show()
return false
done()
##
_loginSuccess: ()->
location.reload()
| true |
module.exports =
class LoginForm extends floyd.gui.ViewContext
##
##
##
configure: (config)->
super new floyd.Config
data:
strings:
user: 'PI:NAME:<NAME>END_PI'
pass: 'PI:PASSWORD:<PASSWORD>END_PI'
login: 'Login'
logout:'Logout'
minimized: false
content: ->
if @data.logo
img src:@data.logo
form method:'post', action:'#', class:'gui widgets LoginForm', ->
if !(user = @identity.login())
p class:'hint'
div (if @data.minimized then style:'display:none' else {}), ->
input name:'user', value:'', placeholder: @data.strings.user
input name:'pass', value:'', type:'password', placeholder:@data.strings.pass
if user && _fn = @data.username
if typeof _fn is 'function'
username = _fn.apply @
else
username = user
span class:'username', username
attr =
type: 'submit'
name:'button'
class: if user then 'logout' else 'login'
if cls = @data.button?.class || @data.button
attr.class = attr.class+' '+cls
title = if user then @data.strings.logout else @data.strings.login
if @data.button?.title
attr.title = title
button attr, ->
if !@data.button?.title
text title
, config
##
##
##
wire: (done)->
super (err)=>
return done(err) if err
hint = @find '.hint'
login = @find('form.gui.widgets.LoginForm')
user = login.find('input[name=user]')
pass = login.find('input[name=pass]')
button = login.find('[name=button]')
div = login.find('> div')
login.on 'submit', ()=>
hint.text('')
if @identity.login()
@_getAuthManager().logout (err)=> location.reload()
else
if div.is ':visible'
button.attr 'disabled', true
@__root.addClass 'working'
@_getAuthManager().login user.val(), pass.val(), (err)=>
button.attr 'disabled', false
@__root.removeClass 'working'
if err
pass.val ''
hint.addClass('error').text(err.message)
else
@_loginSuccess()
else div.show()
return false
done()
##
_loginSuccess: ()->
location.reload()
|
[
{
"context": "ime Completions converted from https://github.com/Southclaw/pawn-sublime-language\n# Converter created by Rena",
"end": 112,
"score": 0.7878562808036804,
"start": 103,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "hclaw/pawn-sublime-language\n# Converter created by Renato \"Hii\" Garcia\n# Repo: https://github.com/Renato-Ga",
"end": 164,
"score": 0.9996782541275024,
"start": 158,
"tag": "NAME",
"value": "Renato"
},
{
"context": "n-sublime-language\n# Converter created by Renato \"Hii\" Garcia\n# Repo: https://github.com/Renato-Garcia/sublime-",
"end": 177,
"score": 0.8857946991920471,
"start": 166,
"tag": "NAME",
"value": "Hii\" Garcia"
},
{
"context": "by Renato \"Hii\" Garcia\n# Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets\n'.source.pwn",
"end": 218,
"score": 0.9944696426391602,
"start": 205,
"tag": "USERNAME",
"value": "Renato-Garcia"
},
{
"context": " 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetCraftSetUniqueID':\n 'prefix': 'Get",
"end": 503,
"score": 0.7110730409622192,
"start": 499,
"tag": "USERNAME",
"value": "claw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'IsValidCraftSet':\n 'prefix': 'IsValid",
"end": 754,
"score": 0.7661612629890442,
"start": 745,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetCraftSetIngredients':\n 'prefix': '",
"end": 954,
"score": 0.8400490880012512,
"start": 945,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetCraftSetItemType':\n 'prefix': 'Get",
"end": 1232,
"score": 0.8157408237457275,
"start": 1223,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetCraftSetItemKeep':\n 'prefix': 'Get",
"end": 1456,
"score": 0.7560569643974304,
"start": 1447,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetCraftSetItemCount':\n 'prefix': 'Ge",
"end": 1680,
"score": 0.999481201171875,
"start": 1671,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetCraftSetResult':\n 'prefix': 'GetCr",
"end": 1895,
"score": 0.9995179176330566,
"start": 1886,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetCraftSetTotal':\n 'prefix': 'GetCra",
"end": 2101,
"score": 0.9995142817497253,
"start": 2092,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetPlayerSelectedCraftItems':\n 'prefi",
"end": 2291,
"score": 0.9990535378456116,
"start": 2282,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetPlayerSelectedCraftItemType':\n 'pr",
"end": 2587,
"score": 0.9992604851722717,
"start": 2578,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetPlayerSelectedCraftItemID':\n 'pref",
"end": 2844,
"score": 0.9994869828224182,
"start": 2835,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetPlayerSelectedCraftItemCount':\n 'p",
"end": 3095,
"score": 0.9993618130683899,
"start": 3086,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'GetPlayerCraftEnvironment':\n 'prefix'",
"end": 3343,
"score": 0.9987156391143799,
"start": 3334,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'ItemTypeResultForCraftingSet':\n 'pref",
"end": 3573,
"score": 0.9996855854988098,
"start": 3564,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'OnPlayerCraft':\n 'prefix': 'OnPlayerC",
"end": 3821,
"score": 0.9996841549873352,
"start": 3812,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n\n 'OnPlayerCrafted':\n 'prefix': 'OnPlaye",
"end": 4030,
"score": 0.9996346831321716,
"start": 4021,
"tag": "USERNAME",
"value": "Southclaw"
},
{
"context": "IF'\n 'descriptionMoreURL': 'https://github.com/Southclaw/SIF'\n",
"end": 4258,
"score": 0.9996649622917175,
"start": 4249,
"tag": "USERNAME",
"value": "Southclaw"
}
] | snippets/SIF.Craft.pwn.cson | Wuzi/language-pawn | 4 | # SIF.Craft.pwn snippets for Atom converted from Sublime Completions converted from https://github.com/Southclaw/pawn-sublime-language
# Converter created by Renato "Hii" Garcia
# Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets
'.source.pwn, .source.inc':
'DefineItemCraftSet':
'prefix': 'DefineItemCraftSet'
'body': 'DefineItemCraftSet(${1:ItemType:result}, ${2:...})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetUniqueID':
'prefix': 'GetCraftSetUniqueID'
'body': 'GetCraftSetUniqueID(${1:craftset}, ${2:id[]}, ${3:maxlength = sizeof(id})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'IsValidCraftSet':
'prefix': 'IsValidCraftSet'
'body': 'IsValidCraftSet(${1:craftset})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetIngredients':
'prefix': 'GetCraftSetIngredients'
'body': 'GetCraftSetIngredients(${1:craftset}, ${2:output[CFT_MAX_CRAFT_SET_ITEMS][e_craft_item_data]})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetItemType':
'prefix': 'GetCraftSetItemType'
'body': 'GetCraftSetItemType(${1:craftset}, ${2:index})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetItemKeep':
'prefix': 'GetCraftSetItemKeep'
'body': 'GetCraftSetItemKeep(${1:craftset}, ${2:index})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetItemCount':
'prefix': 'GetCraftSetItemCount'
'body': 'GetCraftSetItemCount(${1:craftset})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetResult':
'prefix': 'GetCraftSetResult'
'body': 'GetCraftSetResult(${1:craftset})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetTotal':
'prefix': 'GetCraftSetTotal'
'body': 'GetCraftSetTotal()'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetPlayerSelectedCraftItems':
'prefix': 'GetPlayerSelectedCraftItems'
'body': 'GetPlayerSelectedCraftItems(${1:playerid}, ${2:output[CFT_MAX_CRAFT_SET_ITEMS][e_selected_item_data]})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetPlayerSelectedCraftItemType':
'prefix': 'GetPlayerSelectedCraftItemType'
'body': 'GetPlayerSelectedCraftItemType(${1:playerid}, ${2:index})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetPlayerSelectedCraftItemID':
'prefix': 'GetPlayerSelectedCraftItemID'
'body': 'GetPlayerSelectedCraftItemID(${1:playerid}, ${2:index})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetPlayerSelectedCraftItemCount':
'prefix': 'GetPlayerSelectedCraftItemCount'
'body': 'GetPlayerSelectedCraftItemCount(${1:playerid})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetPlayerCraftEnvironment':
'prefix': 'GetPlayerCraftEnvironment'
'body': 'GetPlayerCraftEnvironment(${1:playerid})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'ItemTypeResultForCraftingSet':
'prefix': 'ItemTypeResultForCraftingSet'
'body': 'ItemTypeResultForCraftingSet(${1:ItemType:itemtype})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'OnPlayerCraft':
'prefix': 'OnPlayerCraft'
'body': 'OnPlayerCraft(${1:playerid}, ${2:craftset})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'OnPlayerCrafted':
'prefix': 'OnPlayerCrafted'
'body': 'OnPlayerCrafted(${1:playerid}, ${2:craftset}, ${3:result})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
| 129398 | # SIF.Craft.pwn snippets for Atom converted from Sublime Completions converted from https://github.com/Southclaw/pawn-sublime-language
# Converter created by <NAME> "<NAME>
# Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets
'.source.pwn, .source.inc':
'DefineItemCraftSet':
'prefix': 'DefineItemCraftSet'
'body': 'DefineItemCraftSet(${1:ItemType:result}, ${2:...})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetUniqueID':
'prefix': 'GetCraftSetUniqueID'
'body': 'GetCraftSetUniqueID(${1:craftset}, ${2:id[]}, ${3:maxlength = sizeof(id})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'IsValidCraftSet':
'prefix': 'IsValidCraftSet'
'body': 'IsValidCraftSet(${1:craftset})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetIngredients':
'prefix': 'GetCraftSetIngredients'
'body': 'GetCraftSetIngredients(${1:craftset}, ${2:output[CFT_MAX_CRAFT_SET_ITEMS][e_craft_item_data]})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetItemType':
'prefix': 'GetCraftSetItemType'
'body': 'GetCraftSetItemType(${1:craftset}, ${2:index})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetItemKeep':
'prefix': 'GetCraftSetItemKeep'
'body': 'GetCraftSetItemKeep(${1:craftset}, ${2:index})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetItemCount':
'prefix': 'GetCraftSetItemCount'
'body': 'GetCraftSetItemCount(${1:craftset})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetResult':
'prefix': 'GetCraftSetResult'
'body': 'GetCraftSetResult(${1:craftset})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetTotal':
'prefix': 'GetCraftSetTotal'
'body': 'GetCraftSetTotal()'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetPlayerSelectedCraftItems':
'prefix': 'GetPlayerSelectedCraftItems'
'body': 'GetPlayerSelectedCraftItems(${1:playerid}, ${2:output[CFT_MAX_CRAFT_SET_ITEMS][e_selected_item_data]})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetPlayerSelectedCraftItemType':
'prefix': 'GetPlayerSelectedCraftItemType'
'body': 'GetPlayerSelectedCraftItemType(${1:playerid}, ${2:index})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetPlayerSelectedCraftItemID':
'prefix': 'GetPlayerSelectedCraftItemID'
'body': 'GetPlayerSelectedCraftItemID(${1:playerid}, ${2:index})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetPlayerSelectedCraftItemCount':
'prefix': 'GetPlayerSelectedCraftItemCount'
'body': 'GetPlayerSelectedCraftItemCount(${1:playerid})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetPlayerCraftEnvironment':
'prefix': 'GetPlayerCraftEnvironment'
'body': 'GetPlayerCraftEnvironment(${1:playerid})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'ItemTypeResultForCraftingSet':
'prefix': 'ItemTypeResultForCraftingSet'
'body': 'ItemTypeResultForCraftingSet(${1:ItemType:itemtype})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'OnPlayerCraft':
'prefix': 'OnPlayerCraft'
'body': 'OnPlayerCraft(${1:playerid}, ${2:craftset})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'OnPlayerCrafted':
'prefix': 'OnPlayerCrafted'
'body': 'OnPlayerCrafted(${1:playerid}, ${2:craftset}, ${3:result})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
| true | # SIF.Craft.pwn snippets for Atom converted from Sublime Completions converted from https://github.com/Southclaw/pawn-sublime-language
# Converter created by PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI
# Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets
'.source.pwn, .source.inc':
'DefineItemCraftSet':
'prefix': 'DefineItemCraftSet'
'body': 'DefineItemCraftSet(${1:ItemType:result}, ${2:...})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetUniqueID':
'prefix': 'GetCraftSetUniqueID'
'body': 'GetCraftSetUniqueID(${1:craftset}, ${2:id[]}, ${3:maxlength = sizeof(id})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'IsValidCraftSet':
'prefix': 'IsValidCraftSet'
'body': 'IsValidCraftSet(${1:craftset})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetIngredients':
'prefix': 'GetCraftSetIngredients'
'body': 'GetCraftSetIngredients(${1:craftset}, ${2:output[CFT_MAX_CRAFT_SET_ITEMS][e_craft_item_data]})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetItemType':
'prefix': 'GetCraftSetItemType'
'body': 'GetCraftSetItemType(${1:craftset}, ${2:index})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetItemKeep':
'prefix': 'GetCraftSetItemKeep'
'body': 'GetCraftSetItemKeep(${1:craftset}, ${2:index})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetItemCount':
'prefix': 'GetCraftSetItemCount'
'body': 'GetCraftSetItemCount(${1:craftset})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetResult':
'prefix': 'GetCraftSetResult'
'body': 'GetCraftSetResult(${1:craftset})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetCraftSetTotal':
'prefix': 'GetCraftSetTotal'
'body': 'GetCraftSetTotal()'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetPlayerSelectedCraftItems':
'prefix': 'GetPlayerSelectedCraftItems'
'body': 'GetPlayerSelectedCraftItems(${1:playerid}, ${2:output[CFT_MAX_CRAFT_SET_ITEMS][e_selected_item_data]})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetPlayerSelectedCraftItemType':
'prefix': 'GetPlayerSelectedCraftItemType'
'body': 'GetPlayerSelectedCraftItemType(${1:playerid}, ${2:index})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetPlayerSelectedCraftItemID':
'prefix': 'GetPlayerSelectedCraftItemID'
'body': 'GetPlayerSelectedCraftItemID(${1:playerid}, ${2:index})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetPlayerSelectedCraftItemCount':
'prefix': 'GetPlayerSelectedCraftItemCount'
'body': 'GetPlayerSelectedCraftItemCount(${1:playerid})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'GetPlayerCraftEnvironment':
'prefix': 'GetPlayerCraftEnvironment'
'body': 'GetPlayerCraftEnvironment(${1:playerid})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'ItemTypeResultForCraftingSet':
'prefix': 'ItemTypeResultForCraftingSet'
'body': 'ItemTypeResultForCraftingSet(${1:ItemType:itemtype})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'OnPlayerCraft':
'prefix': 'OnPlayerCraft'
'body': 'OnPlayerCraft(${1:playerid}, ${2:craftset})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
'OnPlayerCrafted':
'prefix': 'OnPlayerCrafted'
'body': 'OnPlayerCrafted(${1:playerid}, ${2:craftset}, ${3:result})'
'description': 'Function from: SIF'
'descriptionMoreURL': 'https://github.com/Southclaw/SIF'
|
[
{
"context": " $http.post \"/users\",\n# user:\n# name: @name\n# email: @email\n# password: @passwo",
"end": 1160,
"score": 0.9993987083435059,
"start": 1155,
"tag": "USERNAME",
"value": "@name"
},
{
"context": "e: @name\n# email: @email\n# password: @password\n# password_confirmation: @password_confirm",
"end": 1212,
"score": 0.999211311340332,
"start": 1203,
"tag": "PASSWORD",
"value": "@password"
},
{
"context": "assword: @password\n# password_confirmation: @password_confirmation\n#\n# UserRegistration\n#\n## Loaders\n#CurrentUserLo",
"end": 1267,
"score": 0.9989637136459351,
"start": 1245,
"tag": "PASSWORD",
"value": "@password_confirmation"
}
] | test/spec/services/api_mock.coffee | Spokenvote/spokenvote | 21 | ## Rest
#CurrentUser = ($resource) ->
# $resource '/currentuser'
#
#Hub = ($resource) ->
# $resource '/hubs/:id',
# id: '@id'
# ,
# update:
# method: 'PUT'
#
#Vote = ($resource) ->
# $resource '/votes/:id',
# id: '@id'
# ,
# update:
# method: 'PUT'
#
#Proposal = ($resource) ->
# $resource '/proposals/:id',
# id: '@id'
# ,
# update:
# method: 'PUT'
#
#RelatedProposals = ($resource) ->
# $resource '/proposals/:id/related_proposals?related_sort_by=:related_sort_by',
# id: '@id'
# related_sort_by: '@related_sort_by'
#
#RelatedVoteInTree = ($resource) ->
# $resource '/proposals/:id/related_vote_in_tree',
# id: '@id'
#
## Resources
#UserOmniauthResource = ($http) ->
# UserOmniauth = (options) ->
# angular.extend this, options
#
# UserOmniauth::$save = ->
# $http.post '/authentications',
# auth: @auth
#
# UserOmniauth::$destroy = ->
# $http.delete "/users/logout"
#
# UserOmniauth
#
#
#UserRegistrationResource = ($http) ->
# UserRegistration = (options) ->
# angular.extend this, options
#
# UserRegistration::$save = ->
# $http.post "/users",
# user:
# name: @name
# email: @email
# password: @password
# password_confirmation: @password_confirmation
#
# UserRegistration
#
## Loaders
#CurrentUserLoader = (CurrentUser, $route, $q) ->
# ->
# delay = $q.defer()
# CurrentUser.get {}
# , (current_user) ->
# delay.resolve current_user
# , ->
# delay.reject 'Unable to locate a current user '
# delay.promise
#
#CurrentHubLoader = (Hub, $route, $q) ->
# ->
# delay = $q.defer()
# if $route.current.params.hub
# Hub.get
# id: $route.current.params.hub
# , (hub) ->
# delay.resolve hub
# , ->
# delay.reject 'Unable to locate a hub '
# else
# delay.resolve false
# delay.promise
#
#ProposalLoader = (Proposal, $route, $q) ->
# ->
# delay = $q.defer()
# Proposal.get
# id: $route.current.params.proposalId
# , (proposal) ->
# delay.resolve proposal
# , ->
# delay.reject 'Unable to locate proposal ' + $route.current.params.proposalId
# delay.promise
MultiProposalLoader = ($q) ->
->
delay = $q.defer()
proposals = [ 1, 2, 3 ]
delay.resolve proposals
delay.promise
#RelatedProposalsLoader = (RelatedProposals, $route, $q) ->
# ->
# delay = $q.defer()
# RelatedProposals.get
# id: $route.current.params.proposalId
# related_sort_by: $route.current.params.related_sort_by
# , (related_proposals) ->
# delay.resolve related_proposals
# , ->
# delay.reject 'Unable to locate related proposals ' + $route.current.params.proposalId
# delay.promise
#
#RelatedVoteInTreeLoader = (RelatedVoteInTree, $q) ->
# (clicked_proposal) ->
# delay = $q.defer()
# RelatedVoteInTree.get
# id: clicked_proposal.id
# , (relatedVoteInTree) ->
# delay.resolve relatedVoteInTree
# , ->
# delay.reject 'Unable to find any related votes in the tree for proposal: ' + clicked_proposal.id
# delay.promise
#
## Injects
#CurrentUser.$inject = [ '$resource' ]
#Hub.$inject = [ '$resource' ]
#Vote.$inject = [ '$resource' ]
#Proposal.$inject = [ '$resource' ]
#RelatedProposals.$inject = [ '$resource' ]
#RelatedVoteInTree.$inject = [ '$resource' ]
#
#UserOmniauthResource.$inject = [ '$http' ]
#UserSessionResource.$inject = [ '$http' ]
#UserRegistrationResource.$inject = [ '$http' ]
#
#CurrentUserLoader.$inject = [ 'CurrentUser', '$route', '$q' ]
#CurrentHubLoader.$inject = [ 'Hub', '$route', '$q' ]
#ProposalLoader.$inject = [ 'Proposal', '$route', '$q' ]
#RelatedProposalsLoader.$inject = [ 'RelatedProposals', '$route', '$q' ]
#RelatedVoteInTreeLoader.$inject = [ 'RelatedVoteInTree', '$q' ]
#
## Register
AppMocks = angular.module 'spokenvoteMocks', [ 'spokenvoteMocks.services' ]
AppMocks.Services = angular.module 'spokenvoteMocks.services', [ 'ngResource', 'ngCookies' ]
#App.Services.factory 'CurrentUser', CurrentUser
#App.Services.factory 'Hub', Hub
#App.Services.factory 'Vote', Vote
#App.Services.factory 'Proposal', Proposal
#
#App.Services.factory 'CurrentHubLoader', CurrentHubLoader
#App.Services.factory 'RelatedProposals', RelatedProposals
#App.Services.factory 'RelatedVoteInTree', RelatedVoteInTree
#
#App.Services.factory 'UserOmniauthResource', UserOmniauthResource
#App.Services.factory 'UserSessionResource', UserSessionResource
#App.Services.factory 'UserRegistrationResource', UserRegistrationResource
#
#App.Services.factory 'CurrentUserLoader', CurrentUserLoader
#App.Services.factory 'ProposalLoader', ProposalLoader
AppMocks.Services.factory 'MultiProposalLoader', MultiProposalLoader
#App.Services.factory 'RelatedProposalsLoader', RelatedProposalsLoader
#App.Services.factory 'RelatedVoteInTreeLoader', RelatedVoteInTreeLoader | 17939 | ## Rest
#CurrentUser = ($resource) ->
# $resource '/currentuser'
#
#Hub = ($resource) ->
# $resource '/hubs/:id',
# id: '@id'
# ,
# update:
# method: 'PUT'
#
#Vote = ($resource) ->
# $resource '/votes/:id',
# id: '@id'
# ,
# update:
# method: 'PUT'
#
#Proposal = ($resource) ->
# $resource '/proposals/:id',
# id: '@id'
# ,
# update:
# method: 'PUT'
#
#RelatedProposals = ($resource) ->
# $resource '/proposals/:id/related_proposals?related_sort_by=:related_sort_by',
# id: '@id'
# related_sort_by: '@related_sort_by'
#
#RelatedVoteInTree = ($resource) ->
# $resource '/proposals/:id/related_vote_in_tree',
# id: '@id'
#
## Resources
#UserOmniauthResource = ($http) ->
# UserOmniauth = (options) ->
# angular.extend this, options
#
# UserOmniauth::$save = ->
# $http.post '/authentications',
# auth: @auth
#
# UserOmniauth::$destroy = ->
# $http.delete "/users/logout"
#
# UserOmniauth
#
#
#UserRegistrationResource = ($http) ->
# UserRegistration = (options) ->
# angular.extend this, options
#
# UserRegistration::$save = ->
# $http.post "/users",
# user:
# name: @name
# email: @email
# password: <PASSWORD>
# password_confirmation: <PASSWORD>
#
# UserRegistration
#
## Loaders
#CurrentUserLoader = (CurrentUser, $route, $q) ->
# ->
# delay = $q.defer()
# CurrentUser.get {}
# , (current_user) ->
# delay.resolve current_user
# , ->
# delay.reject 'Unable to locate a current user '
# delay.promise
#
#CurrentHubLoader = (Hub, $route, $q) ->
# ->
# delay = $q.defer()
# if $route.current.params.hub
# Hub.get
# id: $route.current.params.hub
# , (hub) ->
# delay.resolve hub
# , ->
# delay.reject 'Unable to locate a hub '
# else
# delay.resolve false
# delay.promise
#
#ProposalLoader = (Proposal, $route, $q) ->
# ->
# delay = $q.defer()
# Proposal.get
# id: $route.current.params.proposalId
# , (proposal) ->
# delay.resolve proposal
# , ->
# delay.reject 'Unable to locate proposal ' + $route.current.params.proposalId
# delay.promise
MultiProposalLoader = ($q) ->
->
delay = $q.defer()
proposals = [ 1, 2, 3 ]
delay.resolve proposals
delay.promise
#RelatedProposalsLoader = (RelatedProposals, $route, $q) ->
# ->
# delay = $q.defer()
# RelatedProposals.get
# id: $route.current.params.proposalId
# related_sort_by: $route.current.params.related_sort_by
# , (related_proposals) ->
# delay.resolve related_proposals
# , ->
# delay.reject 'Unable to locate related proposals ' + $route.current.params.proposalId
# delay.promise
#
#RelatedVoteInTreeLoader = (RelatedVoteInTree, $q) ->
# (clicked_proposal) ->
# delay = $q.defer()
# RelatedVoteInTree.get
# id: clicked_proposal.id
# , (relatedVoteInTree) ->
# delay.resolve relatedVoteInTree
# , ->
# delay.reject 'Unable to find any related votes in the tree for proposal: ' + clicked_proposal.id
# delay.promise
#
## Injects
#CurrentUser.$inject = [ '$resource' ]
#Hub.$inject = [ '$resource' ]
#Vote.$inject = [ '$resource' ]
#Proposal.$inject = [ '$resource' ]
#RelatedProposals.$inject = [ '$resource' ]
#RelatedVoteInTree.$inject = [ '$resource' ]
#
#UserOmniauthResource.$inject = [ '$http' ]
#UserSessionResource.$inject = [ '$http' ]
#UserRegistrationResource.$inject = [ '$http' ]
#
#CurrentUserLoader.$inject = [ 'CurrentUser', '$route', '$q' ]
#CurrentHubLoader.$inject = [ 'Hub', '$route', '$q' ]
#ProposalLoader.$inject = [ 'Proposal', '$route', '$q' ]
#RelatedProposalsLoader.$inject = [ 'RelatedProposals', '$route', '$q' ]
#RelatedVoteInTreeLoader.$inject = [ 'RelatedVoteInTree', '$q' ]
#
## Register
AppMocks = angular.module 'spokenvoteMocks', [ 'spokenvoteMocks.services' ]
AppMocks.Services = angular.module 'spokenvoteMocks.services', [ 'ngResource', 'ngCookies' ]
#App.Services.factory 'CurrentUser', CurrentUser
#App.Services.factory 'Hub', Hub
#App.Services.factory 'Vote', Vote
#App.Services.factory 'Proposal', Proposal
#
#App.Services.factory 'CurrentHubLoader', CurrentHubLoader
#App.Services.factory 'RelatedProposals', RelatedProposals
#App.Services.factory 'RelatedVoteInTree', RelatedVoteInTree
#
#App.Services.factory 'UserOmniauthResource', UserOmniauthResource
#App.Services.factory 'UserSessionResource', UserSessionResource
#App.Services.factory 'UserRegistrationResource', UserRegistrationResource
#
#App.Services.factory 'CurrentUserLoader', CurrentUserLoader
#App.Services.factory 'ProposalLoader', ProposalLoader
AppMocks.Services.factory 'MultiProposalLoader', MultiProposalLoader
#App.Services.factory 'RelatedProposalsLoader', RelatedProposalsLoader
#App.Services.factory 'RelatedVoteInTreeLoader', RelatedVoteInTreeLoader | true | ## Rest
#CurrentUser = ($resource) ->
# $resource '/currentuser'
#
#Hub = ($resource) ->
# $resource '/hubs/:id',
# id: '@id'
# ,
# update:
# method: 'PUT'
#
#Vote = ($resource) ->
# $resource '/votes/:id',
# id: '@id'
# ,
# update:
# method: 'PUT'
#
#Proposal = ($resource) ->
# $resource '/proposals/:id',
# id: '@id'
# ,
# update:
# method: 'PUT'
#
#RelatedProposals = ($resource) ->
# $resource '/proposals/:id/related_proposals?related_sort_by=:related_sort_by',
# id: '@id'
# related_sort_by: '@related_sort_by'
#
#RelatedVoteInTree = ($resource) ->
# $resource '/proposals/:id/related_vote_in_tree',
# id: '@id'
#
## Resources
#UserOmniauthResource = ($http) ->
# UserOmniauth = (options) ->
# angular.extend this, options
#
# UserOmniauth::$save = ->
# $http.post '/authentications',
# auth: @auth
#
# UserOmniauth::$destroy = ->
# $http.delete "/users/logout"
#
# UserOmniauth
#
#
#UserRegistrationResource = ($http) ->
# UserRegistration = (options) ->
# angular.extend this, options
#
# UserRegistration::$save = ->
# $http.post "/users",
# user:
# name: @name
# email: @email
# password: PI:PASSWORD:<PASSWORD>END_PI
# password_confirmation: PI:PASSWORD:<PASSWORD>END_PI
#
# UserRegistration
#
## Loaders
#CurrentUserLoader = (CurrentUser, $route, $q) ->
# ->
# delay = $q.defer()
# CurrentUser.get {}
# , (current_user) ->
# delay.resolve current_user
# , ->
# delay.reject 'Unable to locate a current user '
# delay.promise
#
#CurrentHubLoader = (Hub, $route, $q) ->
# ->
# delay = $q.defer()
# if $route.current.params.hub
# Hub.get
# id: $route.current.params.hub
# , (hub) ->
# delay.resolve hub
# , ->
# delay.reject 'Unable to locate a hub '
# else
# delay.resolve false
# delay.promise
#
#ProposalLoader = (Proposal, $route, $q) ->
# ->
# delay = $q.defer()
# Proposal.get
# id: $route.current.params.proposalId
# , (proposal) ->
# delay.resolve proposal
# , ->
# delay.reject 'Unable to locate proposal ' + $route.current.params.proposalId
# delay.promise
MultiProposalLoader = ($q) ->
->
delay = $q.defer()
proposals = [ 1, 2, 3 ]
delay.resolve proposals
delay.promise
#RelatedProposalsLoader = (RelatedProposals, $route, $q) ->
# ->
# delay = $q.defer()
# RelatedProposals.get
# id: $route.current.params.proposalId
# related_sort_by: $route.current.params.related_sort_by
# , (related_proposals) ->
# delay.resolve related_proposals
# , ->
# delay.reject 'Unable to locate related proposals ' + $route.current.params.proposalId
# delay.promise
#
#RelatedVoteInTreeLoader = (RelatedVoteInTree, $q) ->
# (clicked_proposal) ->
# delay = $q.defer()
# RelatedVoteInTree.get
# id: clicked_proposal.id
# , (relatedVoteInTree) ->
# delay.resolve relatedVoteInTree
# , ->
# delay.reject 'Unable to find any related votes in the tree for proposal: ' + clicked_proposal.id
# delay.promise
#
## Injects
#CurrentUser.$inject = [ '$resource' ]
#Hub.$inject = [ '$resource' ]
#Vote.$inject = [ '$resource' ]
#Proposal.$inject = [ '$resource' ]
#RelatedProposals.$inject = [ '$resource' ]
#RelatedVoteInTree.$inject = [ '$resource' ]
#
#UserOmniauthResource.$inject = [ '$http' ]
#UserSessionResource.$inject = [ '$http' ]
#UserRegistrationResource.$inject = [ '$http' ]
#
#CurrentUserLoader.$inject = [ 'CurrentUser', '$route', '$q' ]
#CurrentHubLoader.$inject = [ 'Hub', '$route', '$q' ]
#ProposalLoader.$inject = [ 'Proposal', '$route', '$q' ]
#RelatedProposalsLoader.$inject = [ 'RelatedProposals', '$route', '$q' ]
#RelatedVoteInTreeLoader.$inject = [ 'RelatedVoteInTree', '$q' ]
#
## Register
AppMocks = angular.module 'spokenvoteMocks', [ 'spokenvoteMocks.services' ]
AppMocks.Services = angular.module 'spokenvoteMocks.services', [ 'ngResource', 'ngCookies' ]
#App.Services.factory 'CurrentUser', CurrentUser
#App.Services.factory 'Hub', Hub
#App.Services.factory 'Vote', Vote
#App.Services.factory 'Proposal', Proposal
#
#App.Services.factory 'CurrentHubLoader', CurrentHubLoader
#App.Services.factory 'RelatedProposals', RelatedProposals
#App.Services.factory 'RelatedVoteInTree', RelatedVoteInTree
#
#App.Services.factory 'UserOmniauthResource', UserOmniauthResource
#App.Services.factory 'UserSessionResource', UserSessionResource
#App.Services.factory 'UserRegistrationResource', UserRegistrationResource
#
#App.Services.factory 'CurrentUserLoader', CurrentUserLoader
#App.Services.factory 'ProposalLoader', ProposalLoader
AppMocks.Services.factory 'MultiProposalLoader', MultiProposalLoader
#App.Services.factory 'RelatedProposalsLoader', RelatedProposalsLoader
#App.Services.factory 'RelatedVoteInTreeLoader', RelatedVoteInTreeLoader |
[
{
"context": "values.push(obj)\n assert deepMatch(mailReg, 'bob@mail.com', assign)\n assert exprs.shift() is mailReg\n ",
"end": 3848,
"score": 0.9999130368232727,
"start": 3836,
"tag": "EMAIL",
"value": "bob@mail.com"
},
{
"context": "eg\n v = values.shift()\n assert v[0] is 'bob@mail.com'\n assert v[1] is 'bob'\n assert v[2] is ",
"end": 3956,
"score": 0.9999149441719055,
"start": 3944,
"tag": "EMAIL",
"value": "bob@mail.com"
}
] | node_modules/pat-mat/test/matcher-test.coffee | prasanthbendra/ng-2 | 0 | assert = require('assert')
{
Matcher
deepMatch
} = require('../dest/matcher')
{
quote
paramSeq
parameter
Parameter
wildcard
wildcardSeq
} = require('../dest/placeholder')
_ = wildcard
q = quote
$ = parameter
$$ = paramSeq
__ = wildcardSeq
extract = require('../dest/extractor').extract
Point = extract class Point
constructor: (@x, @y) ->
Circle = extract class Circle extends Point
constructor: (@r) ->
@unapply: (other) ->
x = other.x
y = other.y
{ r: Math.sqrt(x*x + y*y) }
UnitVector = extract class UnitVector
constructor: (@x, @y) ->
@unapply: {
transform: (other) ->
x = other.x
y = other.y
norm = Math.sqrt(x*x + y*y)
{x: x/norm, y: y/norm}
}
describe 'Matcher', ->
it 'default unapply should check constructor', ->
annotation = ['x', 'y']
argList = [3, 4]
ctor = Point
matcher = new Matcher(annotation, null, argList, ctor)
p = new Point(3, 4)
pp = new Point(4, 5)
assert matcher.unapply(p, ->)
assert matcher.unapply(pp, ->) is false
assert matcher.unapply({x: 3, y: 4}, ->) is false
it 'should cooperate with extractor', ->
matcher = Point(3, 4)
p = new Point(3, 4)
pp = new Point(4, 5)
assert matcher.unapply(p, ->)
assert matcher.unapply(pp, ->) is false
assert matcher.unapply({x: 3, y: 4}, ->) is false
it 'should use transform if provided', ->
matcher = Circle(5)
p = new Point(3, 4)
pp = new Point(4, 5)
assert matcher.unapply(p, ->)
assert matcher.unapply(pp, ->) is false
assert Circle($).unapply(p, ->)
assert Circle($).unapply(pp, ->)
it 'should use unapply object', ->
matcher = UnitVector(3/5, 4/5)
p = new Point(3, 4)
pp = new Point(4, 5)
assert matcher.unapply(p, ->)
assert matcher.unapply(pp, ->) is false
describe 'deepMatch', ->
it 'match wildcard and Wildcard instance', ->
assign = -> throw 'should not call'
assert deepMatch(_, 1, assign)
assert deepMatch(_, null, assign)
assert deepMatch(_, 'whatever', assign)
assert deepMatch(_(Number), 1, assign)
assert deepMatch(_(Number), 'ddd', assign) is false
it 'quoted pattern should match literally', ->
assign = -> throw 'should not call'
assert deepMatch(q(1), 1, assign)
assert deepMatch(q($), $, assign)
assert deepMatch(q(Number), 1, assign) is false
assert deepMatch(q($), 'whatever', assign) is false
it 'should make Matcher happy', ->
exprs = []
values = []
assign = (expr, obj) ->
exprs.push(expr)
values.push(obj)
p = new Point(3, 4)
pp = new Point(4, 4)
matcher0 = Point(3, 4)
matcher1 = Circle(5)
matcher2 = UnitVector(3/5, 4/5)
assert deepMatch(matcher0, p, assign)
assert deepMatch(matcher1, p, assign)
assert deepMatch(matcher2, p, assign)
assert deepMatch(matcher1, pp, assign) is false
assert deepMatch(matcher2, pp, assign) is false
assert deepMatch(Point($('x', _), $('y', _)), p, assign)
# exprs = [$x, $y]
# values = [3, 4]
assert exprs.shift().name is 'x'
assert exprs.shift().name is 'y'
assert values.shift() is 3
assert values.shift() is 4
assert deepMatch(Point(3, $), p, assign)
assert exprs.shift() is $
assert values.shift() is 4
assert deepMatch(Point(3, $), pp, assign) is false
assert exprs.length is 0
assert values.length is 0
assert deepMatch(Circle($), p, assign)
assert exprs.shift() is $
assert values.shift() is 5
it 'match Regex and assign matched array', ->
mailReg = /(.+?)@([^\.]+)\..+/
exprs = []
values = []
assign = (expr, obj) ->
exprs.push(expr)
values.push(obj)
assert deepMatch(mailReg, 'bob@mail.com', assign)
assert exprs.shift() is mailReg
v = values.shift()
assert v[0] is 'bob@mail.com'
assert v[1] is 'bob'
assert v[2] is 'mail'
assert deepMatch(mailReg, 'xxx', assign) is false
assert exprs.length is 0
assert values.length is 0
it 'match parameter', ->
exprs = []
values = []
assign = (expr, obj) ->
exprs.push(expr)
values.push(obj)
assert deepMatch($, 5, assign)
assert exprs.shift() is $
assert values.shift() is 5
assert deepMatch($(String), 5, assign) is false
# unmatch does not clean exprs
exprs.pop()
values.pop()
assert deepMatch($(String), 'string', assign)
assert exprs.shift().pattern is String
assert values.shift() is 'string'
it 'match primitive', ->
assign = -> throw 'should not come here'
assert deepMatch(5, 5, ->)
assert deepMatch('5', 5, ->) is false
assert deepMatch(NaN, NaN, ->)
assert deepMatch(q(NaN), NaN, ->) is false
assert deepMatch(undefined, undefined, ->)
assert deepMatch(undefined, 'ss', ->) is false
assert deepMatch(null, undefined, ->) is false
it 'match plain object', ->
Parameter.reset()
matched = []
assign = (expr, obj) ->
matched[expr.index] = obj
p = new Point(3, 4)
assert deepMatch({x: 3, y: 4}, p, assign)
assert deepMatch({x: $(), y: $(Number)}, p, assign)
assert matched[0] is 3
assert matched[1] is 4
it 'match array', ->
Parameter.reset()
obj = [1..5]
matched = []
assign = -> throw 'never here'
assert deepMatch([1, 2, 3, 4, 5], obj, assign)
assert deepMatch([1, __, 5], obj, assign)
assign = (expr, obj) ->
matched[0] = obj
assert deepMatch([1, 2, $$], obj, assign)
tail = matched.shift()
assert tail[0] is 3 and tail[1] is 4 and tail[2] is 5
assign = (expr, obj) ->
matched[expr.getKey()] = obj
assert deepMatch([$$('head'), 4, 5], obj, assign)
head = matched.head
assert head[0] is 1 and head[1] is 2 and head[2] is 3
assign = (expr, obj) ->
matched[expr.index] = obj
Parameter.reset()
$$()
assert deepMatch([1, $$(), 5], obj, assign)
mid = matched[1]
assert mid[0] is 2 and mid[1] is 3 and mid[2] is 4
Parameter.reset()
it 'fail to match array', ->
assign = -> throw 'never here'
obj = [1..5]
assert deepMatch([1, $$, 6], obj, assign) is false
assert deepMatch([], 123, assign) is false
assert.throws(->
deepMatch([$$, 3, $$, 5], obj, assign)
Error)
it 'should fail to match array', ->
assign = -> throw 'never here'
# would match because only pre and post are tested
obj = [1, 2]
assert deepMatch([1, 2, $$, 1, 2], obj, assign) is false
assert deepMatch([], obj, assign) is false
it 'should not match twice', ->
counter = 0
assign = -> counter++
assert deepMatch([$], [1], assign)
assert counter is 1
it 'patter length and that of obj are different', ->
assert deepMatch([$, $, $], [1, 2], ->) is false
assert deepMatch([$, $], [1, 2, 3], ->) is false
it 'match func javascript primitive', ->
counter = 0
i = 0
assign = -> ++counter
assert deepMatch(String, 'ttt', assign)
assert counter is ++i
assert deepMatch(String, 3, assign) is false
assert counter is i
assert deepMatch(Number, 3, assign)
assert counter is ++i
assert deepMatch(Boolean, true, assign)
assert counter is ++i
assert deepMatch(Point, new Point(3, 4), assign)
assert counter is ++i
assert deepMatch(Point, new Circle(5), assign)
assert counter is ++i
assert deepMatch(Point, new UnitVector(.727, .727), assign) is false
assert counter is i
assert deepMatch(Array, [1,2,3], assign)
assert counter is ++i
assert deepMatch(Number, true, ->) is false
| 121820 | assert = require('assert')
{
Matcher
deepMatch
} = require('../dest/matcher')
{
quote
paramSeq
parameter
Parameter
wildcard
wildcardSeq
} = require('../dest/placeholder')
_ = wildcard
q = quote
$ = parameter
$$ = paramSeq
__ = wildcardSeq
extract = require('../dest/extractor').extract
Point = extract class Point
constructor: (@x, @y) ->
Circle = extract class Circle extends Point
constructor: (@r) ->
@unapply: (other) ->
x = other.x
y = other.y
{ r: Math.sqrt(x*x + y*y) }
UnitVector = extract class UnitVector
constructor: (@x, @y) ->
@unapply: {
transform: (other) ->
x = other.x
y = other.y
norm = Math.sqrt(x*x + y*y)
{x: x/norm, y: y/norm}
}
describe 'Matcher', ->
it 'default unapply should check constructor', ->
annotation = ['x', 'y']
argList = [3, 4]
ctor = Point
matcher = new Matcher(annotation, null, argList, ctor)
p = new Point(3, 4)
pp = new Point(4, 5)
assert matcher.unapply(p, ->)
assert matcher.unapply(pp, ->) is false
assert matcher.unapply({x: 3, y: 4}, ->) is false
it 'should cooperate with extractor', ->
matcher = Point(3, 4)
p = new Point(3, 4)
pp = new Point(4, 5)
assert matcher.unapply(p, ->)
assert matcher.unapply(pp, ->) is false
assert matcher.unapply({x: 3, y: 4}, ->) is false
it 'should use transform if provided', ->
matcher = Circle(5)
p = new Point(3, 4)
pp = new Point(4, 5)
assert matcher.unapply(p, ->)
assert matcher.unapply(pp, ->) is false
assert Circle($).unapply(p, ->)
assert Circle($).unapply(pp, ->)
it 'should use unapply object', ->
matcher = UnitVector(3/5, 4/5)
p = new Point(3, 4)
pp = new Point(4, 5)
assert matcher.unapply(p, ->)
assert matcher.unapply(pp, ->) is false
describe 'deepMatch', ->
it 'match wildcard and Wildcard instance', ->
assign = -> throw 'should not call'
assert deepMatch(_, 1, assign)
assert deepMatch(_, null, assign)
assert deepMatch(_, 'whatever', assign)
assert deepMatch(_(Number), 1, assign)
assert deepMatch(_(Number), 'ddd', assign) is false
it 'quoted pattern should match literally', ->
assign = -> throw 'should not call'
assert deepMatch(q(1), 1, assign)
assert deepMatch(q($), $, assign)
assert deepMatch(q(Number), 1, assign) is false
assert deepMatch(q($), 'whatever', assign) is false
it 'should make Matcher happy', ->
exprs = []
values = []
assign = (expr, obj) ->
exprs.push(expr)
values.push(obj)
p = new Point(3, 4)
pp = new Point(4, 4)
matcher0 = Point(3, 4)
matcher1 = Circle(5)
matcher2 = UnitVector(3/5, 4/5)
assert deepMatch(matcher0, p, assign)
assert deepMatch(matcher1, p, assign)
assert deepMatch(matcher2, p, assign)
assert deepMatch(matcher1, pp, assign) is false
assert deepMatch(matcher2, pp, assign) is false
assert deepMatch(Point($('x', _), $('y', _)), p, assign)
# exprs = [$x, $y]
# values = [3, 4]
assert exprs.shift().name is 'x'
assert exprs.shift().name is 'y'
assert values.shift() is 3
assert values.shift() is 4
assert deepMatch(Point(3, $), p, assign)
assert exprs.shift() is $
assert values.shift() is 4
assert deepMatch(Point(3, $), pp, assign) is false
assert exprs.length is 0
assert values.length is 0
assert deepMatch(Circle($), p, assign)
assert exprs.shift() is $
assert values.shift() is 5
it 'match Regex and assign matched array', ->
mailReg = /(.+?)@([^\.]+)\..+/
exprs = []
values = []
assign = (expr, obj) ->
exprs.push(expr)
values.push(obj)
assert deepMatch(mailReg, '<EMAIL>', assign)
assert exprs.shift() is mailReg
v = values.shift()
assert v[0] is '<EMAIL>'
assert v[1] is 'bob'
assert v[2] is 'mail'
assert deepMatch(mailReg, 'xxx', assign) is false
assert exprs.length is 0
assert values.length is 0
it 'match parameter', ->
exprs = []
values = []
assign = (expr, obj) ->
exprs.push(expr)
values.push(obj)
assert deepMatch($, 5, assign)
assert exprs.shift() is $
assert values.shift() is 5
assert deepMatch($(String), 5, assign) is false
# unmatch does not clean exprs
exprs.pop()
values.pop()
assert deepMatch($(String), 'string', assign)
assert exprs.shift().pattern is String
assert values.shift() is 'string'
it 'match primitive', ->
assign = -> throw 'should not come here'
assert deepMatch(5, 5, ->)
assert deepMatch('5', 5, ->) is false
assert deepMatch(NaN, NaN, ->)
assert deepMatch(q(NaN), NaN, ->) is false
assert deepMatch(undefined, undefined, ->)
assert deepMatch(undefined, 'ss', ->) is false
assert deepMatch(null, undefined, ->) is false
it 'match plain object', ->
Parameter.reset()
matched = []
assign = (expr, obj) ->
matched[expr.index] = obj
p = new Point(3, 4)
assert deepMatch({x: 3, y: 4}, p, assign)
assert deepMatch({x: $(), y: $(Number)}, p, assign)
assert matched[0] is 3
assert matched[1] is 4
it 'match array', ->
Parameter.reset()
obj = [1..5]
matched = []
assign = -> throw 'never here'
assert deepMatch([1, 2, 3, 4, 5], obj, assign)
assert deepMatch([1, __, 5], obj, assign)
assign = (expr, obj) ->
matched[0] = obj
assert deepMatch([1, 2, $$], obj, assign)
tail = matched.shift()
assert tail[0] is 3 and tail[1] is 4 and tail[2] is 5
assign = (expr, obj) ->
matched[expr.getKey()] = obj
assert deepMatch([$$('head'), 4, 5], obj, assign)
head = matched.head
assert head[0] is 1 and head[1] is 2 and head[2] is 3
assign = (expr, obj) ->
matched[expr.index] = obj
Parameter.reset()
$$()
assert deepMatch([1, $$(), 5], obj, assign)
mid = matched[1]
assert mid[0] is 2 and mid[1] is 3 and mid[2] is 4
Parameter.reset()
it 'fail to match array', ->
assign = -> throw 'never here'
obj = [1..5]
assert deepMatch([1, $$, 6], obj, assign) is false
assert deepMatch([], 123, assign) is false
assert.throws(->
deepMatch([$$, 3, $$, 5], obj, assign)
Error)
it 'should fail to match array', ->
assign = -> throw 'never here'
# would match because only pre and post are tested
obj = [1, 2]
assert deepMatch([1, 2, $$, 1, 2], obj, assign) is false
assert deepMatch([], obj, assign) is false
it 'should not match twice', ->
counter = 0
assign = -> counter++
assert deepMatch([$], [1], assign)
assert counter is 1
it 'patter length and that of obj are different', ->
assert deepMatch([$, $, $], [1, 2], ->) is false
assert deepMatch([$, $], [1, 2, 3], ->) is false
it 'match func javascript primitive', ->
counter = 0
i = 0
assign = -> ++counter
assert deepMatch(String, 'ttt', assign)
assert counter is ++i
assert deepMatch(String, 3, assign) is false
assert counter is i
assert deepMatch(Number, 3, assign)
assert counter is ++i
assert deepMatch(Boolean, true, assign)
assert counter is ++i
assert deepMatch(Point, new Point(3, 4), assign)
assert counter is ++i
assert deepMatch(Point, new Circle(5), assign)
assert counter is ++i
assert deepMatch(Point, new UnitVector(.727, .727), assign) is false
assert counter is i
assert deepMatch(Array, [1,2,3], assign)
assert counter is ++i
assert deepMatch(Number, true, ->) is false
| true | assert = require('assert')
{
Matcher
deepMatch
} = require('../dest/matcher')
{
quote
paramSeq
parameter
Parameter
wildcard
wildcardSeq
} = require('../dest/placeholder')
_ = wildcard
q = quote
$ = parameter
$$ = paramSeq
__ = wildcardSeq
extract = require('../dest/extractor').extract
Point = extract class Point
constructor: (@x, @y) ->
Circle = extract class Circle extends Point
constructor: (@r) ->
@unapply: (other) ->
x = other.x
y = other.y
{ r: Math.sqrt(x*x + y*y) }
UnitVector = extract class UnitVector
constructor: (@x, @y) ->
@unapply: {
transform: (other) ->
x = other.x
y = other.y
norm = Math.sqrt(x*x + y*y)
{x: x/norm, y: y/norm}
}
describe 'Matcher', ->
it 'default unapply should check constructor', ->
annotation = ['x', 'y']
argList = [3, 4]
ctor = Point
matcher = new Matcher(annotation, null, argList, ctor)
p = new Point(3, 4)
pp = new Point(4, 5)
assert matcher.unapply(p, ->)
assert matcher.unapply(pp, ->) is false
assert matcher.unapply({x: 3, y: 4}, ->) is false
it 'should cooperate with extractor', ->
matcher = Point(3, 4)
p = new Point(3, 4)
pp = new Point(4, 5)
assert matcher.unapply(p, ->)
assert matcher.unapply(pp, ->) is false
assert matcher.unapply({x: 3, y: 4}, ->) is false
it 'should use transform if provided', ->
matcher = Circle(5)
p = new Point(3, 4)
pp = new Point(4, 5)
assert matcher.unapply(p, ->)
assert matcher.unapply(pp, ->) is false
assert Circle($).unapply(p, ->)
assert Circle($).unapply(pp, ->)
it 'should use unapply object', ->
matcher = UnitVector(3/5, 4/5)
p = new Point(3, 4)
pp = new Point(4, 5)
assert matcher.unapply(p, ->)
assert matcher.unapply(pp, ->) is false
describe 'deepMatch', ->
it 'match wildcard and Wildcard instance', ->
assign = -> throw 'should not call'
assert deepMatch(_, 1, assign)
assert deepMatch(_, null, assign)
assert deepMatch(_, 'whatever', assign)
assert deepMatch(_(Number), 1, assign)
assert deepMatch(_(Number), 'ddd', assign) is false
it 'quoted pattern should match literally', ->
assign = -> throw 'should not call'
assert deepMatch(q(1), 1, assign)
assert deepMatch(q($), $, assign)
assert deepMatch(q(Number), 1, assign) is false
assert deepMatch(q($), 'whatever', assign) is false
it 'should make Matcher happy', ->
exprs = []
values = []
assign = (expr, obj) ->
exprs.push(expr)
values.push(obj)
p = new Point(3, 4)
pp = new Point(4, 4)
matcher0 = Point(3, 4)
matcher1 = Circle(5)
matcher2 = UnitVector(3/5, 4/5)
assert deepMatch(matcher0, p, assign)
assert deepMatch(matcher1, p, assign)
assert deepMatch(matcher2, p, assign)
assert deepMatch(matcher1, pp, assign) is false
assert deepMatch(matcher2, pp, assign) is false
assert deepMatch(Point($('x', _), $('y', _)), p, assign)
# exprs = [$x, $y]
# values = [3, 4]
assert exprs.shift().name is 'x'
assert exprs.shift().name is 'y'
assert values.shift() is 3
assert values.shift() is 4
assert deepMatch(Point(3, $), p, assign)
assert exprs.shift() is $
assert values.shift() is 4
assert deepMatch(Point(3, $), pp, assign) is false
assert exprs.length is 0
assert values.length is 0
assert deepMatch(Circle($), p, assign)
assert exprs.shift() is $
assert values.shift() is 5
it 'match Regex and assign matched array', ->
mailReg = /(.+?)@([^\.]+)\..+/
exprs = []
values = []
assign = (expr, obj) ->
exprs.push(expr)
values.push(obj)
assert deepMatch(mailReg, 'PI:EMAIL:<EMAIL>END_PI', assign)
assert exprs.shift() is mailReg
v = values.shift()
assert v[0] is 'PI:EMAIL:<EMAIL>END_PI'
assert v[1] is 'bob'
assert v[2] is 'mail'
assert deepMatch(mailReg, 'xxx', assign) is false
assert exprs.length is 0
assert values.length is 0
it 'match parameter', ->
exprs = []
values = []
assign = (expr, obj) ->
exprs.push(expr)
values.push(obj)
assert deepMatch($, 5, assign)
assert exprs.shift() is $
assert values.shift() is 5
assert deepMatch($(String), 5, assign) is false
# unmatch does not clean exprs
exprs.pop()
values.pop()
assert deepMatch($(String), 'string', assign)
assert exprs.shift().pattern is String
assert values.shift() is 'string'
it 'match primitive', ->
assign = -> throw 'should not come here'
assert deepMatch(5, 5, ->)
assert deepMatch('5', 5, ->) is false
assert deepMatch(NaN, NaN, ->)
assert deepMatch(q(NaN), NaN, ->) is false
assert deepMatch(undefined, undefined, ->)
assert deepMatch(undefined, 'ss', ->) is false
assert deepMatch(null, undefined, ->) is false
it 'match plain object', ->
Parameter.reset()
matched = []
assign = (expr, obj) ->
matched[expr.index] = obj
p = new Point(3, 4)
assert deepMatch({x: 3, y: 4}, p, assign)
assert deepMatch({x: $(), y: $(Number)}, p, assign)
assert matched[0] is 3
assert matched[1] is 4
it 'match array', ->
Parameter.reset()
obj = [1..5]
matched = []
assign = -> throw 'never here'
assert deepMatch([1, 2, 3, 4, 5], obj, assign)
assert deepMatch([1, __, 5], obj, assign)
assign = (expr, obj) ->
matched[0] = obj
assert deepMatch([1, 2, $$], obj, assign)
tail = matched.shift()
assert tail[0] is 3 and tail[1] is 4 and tail[2] is 5
assign = (expr, obj) ->
matched[expr.getKey()] = obj
assert deepMatch([$$('head'), 4, 5], obj, assign)
head = matched.head
assert head[0] is 1 and head[1] is 2 and head[2] is 3
assign = (expr, obj) ->
matched[expr.index] = obj
Parameter.reset()
$$()
assert deepMatch([1, $$(), 5], obj, assign)
mid = matched[1]
assert mid[0] is 2 and mid[1] is 3 and mid[2] is 4
Parameter.reset()
it 'fail to match array', ->
assign = -> throw 'never here'
obj = [1..5]
assert deepMatch([1, $$, 6], obj, assign) is false
assert deepMatch([], 123, assign) is false
assert.throws(->
deepMatch([$$, 3, $$, 5], obj, assign)
Error)
it 'should fail to match array', ->
assign = -> throw 'never here'
# would match because only pre and post are tested
obj = [1, 2]
assert deepMatch([1, 2, $$, 1, 2], obj, assign) is false
assert deepMatch([], obj, assign) is false
it 'should not match twice', ->
counter = 0
assign = -> counter++
assert deepMatch([$], [1], assign)
assert counter is 1
it 'patter length and that of obj are different', ->
assert deepMatch([$, $, $], [1, 2], ->) is false
assert deepMatch([$, $], [1, 2, 3], ->) is false
it 'match func javascript primitive', ->
counter = 0
i = 0
assign = -> ++counter
assert deepMatch(String, 'ttt', assign)
assert counter is ++i
assert deepMatch(String, 3, assign) is false
assert counter is i
assert deepMatch(Number, 3, assign)
assert counter is ++i
assert deepMatch(Boolean, true, assign)
assert counter is ++i
assert deepMatch(Point, new Point(3, 4), assign)
assert counter is ++i
assert deepMatch(Point, new Circle(5), assign)
assert counter is ++i
assert deepMatch(Point, new UnitVector(.727, .727), assign) is false
assert counter is i
assert deepMatch(Array, [1,2,3], assign)
assert counter is ++i
assert deepMatch(Number, true, ->) is false
|
[
{
"context": "ull, level = 0 }) ->\n if !userId\n userId = @userId\n if !userId\n throw new (Meteor.Error)('no",
"end": 862,
"score": 0.9990975260734558,
"start": 855,
"tag": "USERNAME",
"value": "@userId"
},
{
"context": " to: email,\n from: \"BulletNotes.io <admin@bulletnotes.io>\",\n subject: \"Daily Activity Summary\",\n ",
"end": 5106,
"score": 0.9999280571937561,
"start": 5086,
"tag": "EMAIL",
"value": "admin@bulletnotes.io"
}
] | imports/api/notes/server/methods.coffee | jean/BulletNotes | 7 | import { Meteor } from 'meteor/meteor'
import { _ } from 'meteor/underscore'
import { ValidatedMethod } from 'meteor/mdg:validated-method'
import SimpleSchema from 'simpl-schema'
import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'
Dropbox = require('dropbox')
import rankDenormalizer from '/imports/api/notes/rankDenormalizer.coffee'
import childCountDenormalizer from '/imports/api/notes/childCountDenormalizer.coffee'
import { Notes } from '/imports/api/notes/notes.coffee'
export notesExport = new ValidatedMethod
name: 'notes.export'
validate: new SimpleSchema
noteId:
type: String
optional: true
userId: Notes.simpleSchema().schema('owner')
level: Notes.simpleSchema().schema('level')
.validator
clean: yes
filter: no
run: ({ noteId = null, userId = null, level = 0 }) ->
if !userId
userId = @userId
if !userId
throw new (Meteor.Error)('not-authorized - no userId')
topLevelNotes = Notes.find {
parent: noteId
owner: userId
deleted: {$exists: false}
}, sort: rank: 1
exportText = ''
topLevelNotes.forEach (note) ->
spacing = new Array(level * 5).join(' ')
exportText += spacing + '- '
if note.title
exportText += note.title
exportText += '\n'
if note.body
exportText += spacing + ' "' + note.body + '"\n'
exportText = exportText + notesExport.call {
noteId: note._id
userId: userId
level: level+1
}
exportText
export dropboxExport = new ValidatedMethod
name: 'notes.dropboxExport'
validate: null
run: () ->
user = Meteor.user()
if (
user.profile &&
user.profile.dropbox_token
)
exportText = notesExport.call
noteId: null
userId: user._id
dbx = new Dropbox(
accessToken: user.profile.dropbox_token
)
dbx.filesUpload(
path: '/BulletNotes'+moment().format('-YYYY-MM-DD')+'.txt'
contents: exportText).then((response) ->
console.log response
).catch (error) ->
console.error error
throw new (Meteor.Error)(error)
else
throw new (Meteor.Error)('No linked Dropbox account')
export dropboxNightly = new ValidatedMethod
name: 'notes.dropboxNightly'
validate: null
run: () ->
users = Meteor.users.find({
isPro:true
})
users.forEach (user) ->
if (
user.profile &&
user.profile.dropbox_token
)
exportText = notesExport.call
noteId: null
userId: user._id
dbx = new Dropbox(
accessToken: user.profile.dropbox_token
)
dbx.filesUpload(
path: '/BulletNotes'+moment().format('-YYYY-MM-DD')+'.txt'
contents: exportText).then((response) ->
console.log response
).catch (error) ->
console.error error
export inbox = new ValidatedMethod
name: 'notes.inbox'
validate: new SimpleSchema
title: Notes.simpleSchema().schema('title')
body: Notes.simpleSchema().schema('body')
userId: Notes.simpleSchema().schema('_id')
parentId:
type: String
optional: true
.validator
clean: yes
filter: no
# userId has already been translated from apiKey by notes/routes by the time it gets here
run: ({ title, body, userId, parentId = null }) ->
# If we have a parent note to put it under, use that. But make sure we have write permissions.
if parentId
note = Notes.findOne
owner: userId
_id: parentId
if !note
# No permission, or no note. Just quit.
false
# We don't have a specific note to put this under, put it in the Inbox
else
inbox = Notes.findOne
owner: userId
inbox: true
deleted: {$exists:false}
# If there is not an existing Inbox note, create one.
if !inbox
parentId = Notes.insert
title: ":inbox_tray: <b>Inbox</b>"
createdAt: new Date()
owner: userId
inbox: true
showChildren: true
complete: false
# Otherwise, use the existing inbox
else
parentId = inbox._id
if parentId
noteId = Notes.insert
title: title
body: body
parent: parentId
owner: userId
createdAt: new Date()
rank: 0
complete: false
Meteor.users.update userId,
{$inc:{"notesCreated":1}}
Meteor.defer ->
rankDenormalizer.updateChildren parentId
return noteId
export summary = new ValidatedMethod
name: 'notes.summary'
validate: null
run: () ->
users = Meteor.users.find({})
users.forEach (user) ->
if user.emails
email = user.emails[0].address
notes = Notes.search 'last-changed:24h', user._id
SSR.compileTemplate( 'Email_summary', Assets.getText( 'email/summary.html' ) )
html = SSR.render 'Email_summary',
site_url: Meteor.absoluteUrl()
notes: notes
Email.send({
to: email,
from: "BulletNotes.io <admin@bulletnotes.io>",
subject: "Daily Activity Summary",
html: html
})
# We don't add this to to rate limiter because imports hit it a bunch. Hence the defer.
export denormalizeChildCount = new ValidatedMethod
name: 'notes.denormalizeChildCount'
validate: new SimpleSchema
noteId: Notes.simpleSchema().schema('_id')
.validator
clean: yes
filter: no
run: ({ noteId }) ->
Meteor.defer ->
childCountDenormalizer.afterInsertNote noteId
export denormalizeRanks = new ValidatedMethod
name: 'notes.denormalizeRanks'
validate: new SimpleSchema
noteId: Notes.simpleSchema().schema('_id')
.validator
clean: yes
filter: no
run: ({ noteId }) ->
Meteor.defer ->
rankDenormalizer.updateChildren noteId
# Get note of all method names on Notes
NOTES_METHODS = _.pluck([
notesExport
dropboxExport
dropboxNightly
denormalizeRanks
summary
inbox
], 'name')
if Meteor.isServer
# Only allow 5 notes operations per connection per second
DDPRateLimiter.addRule {
name: (name) ->
_.contains NOTES_METHODS, name
# Rate limit per connection ID
connectionId: ->
yes
}, 5, 1000
| 196643 | import { Meteor } from 'meteor/meteor'
import { _ } from 'meteor/underscore'
import { ValidatedMethod } from 'meteor/mdg:validated-method'
import SimpleSchema from 'simpl-schema'
import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'
Dropbox = require('dropbox')
import rankDenormalizer from '/imports/api/notes/rankDenormalizer.coffee'
import childCountDenormalizer from '/imports/api/notes/childCountDenormalizer.coffee'
import { Notes } from '/imports/api/notes/notes.coffee'
export notesExport = new ValidatedMethod
name: 'notes.export'
validate: new SimpleSchema
noteId:
type: String
optional: true
userId: Notes.simpleSchema().schema('owner')
level: Notes.simpleSchema().schema('level')
.validator
clean: yes
filter: no
run: ({ noteId = null, userId = null, level = 0 }) ->
if !userId
userId = @userId
if !userId
throw new (Meteor.Error)('not-authorized - no userId')
topLevelNotes = Notes.find {
parent: noteId
owner: userId
deleted: {$exists: false}
}, sort: rank: 1
exportText = ''
topLevelNotes.forEach (note) ->
spacing = new Array(level * 5).join(' ')
exportText += spacing + '- '
if note.title
exportText += note.title
exportText += '\n'
if note.body
exportText += spacing + ' "' + note.body + '"\n'
exportText = exportText + notesExport.call {
noteId: note._id
userId: userId
level: level+1
}
exportText
export dropboxExport = new ValidatedMethod
name: 'notes.dropboxExport'
validate: null
run: () ->
user = Meteor.user()
if (
user.profile &&
user.profile.dropbox_token
)
exportText = notesExport.call
noteId: null
userId: user._id
dbx = new Dropbox(
accessToken: user.profile.dropbox_token
)
dbx.filesUpload(
path: '/BulletNotes'+moment().format('-YYYY-MM-DD')+'.txt'
contents: exportText).then((response) ->
console.log response
).catch (error) ->
console.error error
throw new (Meteor.Error)(error)
else
throw new (Meteor.Error)('No linked Dropbox account')
export dropboxNightly = new ValidatedMethod
name: 'notes.dropboxNightly'
validate: null
run: () ->
users = Meteor.users.find({
isPro:true
})
users.forEach (user) ->
if (
user.profile &&
user.profile.dropbox_token
)
exportText = notesExport.call
noteId: null
userId: user._id
dbx = new Dropbox(
accessToken: user.profile.dropbox_token
)
dbx.filesUpload(
path: '/BulletNotes'+moment().format('-YYYY-MM-DD')+'.txt'
contents: exportText).then((response) ->
console.log response
).catch (error) ->
console.error error
export inbox = new ValidatedMethod
name: 'notes.inbox'
validate: new SimpleSchema
title: Notes.simpleSchema().schema('title')
body: Notes.simpleSchema().schema('body')
userId: Notes.simpleSchema().schema('_id')
parentId:
type: String
optional: true
.validator
clean: yes
filter: no
# userId has already been translated from apiKey by notes/routes by the time it gets here
run: ({ title, body, userId, parentId = null }) ->
# If we have a parent note to put it under, use that. But make sure we have write permissions.
if parentId
note = Notes.findOne
owner: userId
_id: parentId
if !note
# No permission, or no note. Just quit.
false
# We don't have a specific note to put this under, put it in the Inbox
else
inbox = Notes.findOne
owner: userId
inbox: true
deleted: {$exists:false}
# If there is not an existing Inbox note, create one.
if !inbox
parentId = Notes.insert
title: ":inbox_tray: <b>Inbox</b>"
createdAt: new Date()
owner: userId
inbox: true
showChildren: true
complete: false
# Otherwise, use the existing inbox
else
parentId = inbox._id
if parentId
noteId = Notes.insert
title: title
body: body
parent: parentId
owner: userId
createdAt: new Date()
rank: 0
complete: false
Meteor.users.update userId,
{$inc:{"notesCreated":1}}
Meteor.defer ->
rankDenormalizer.updateChildren parentId
return noteId
export summary = new ValidatedMethod
name: 'notes.summary'
validate: null
run: () ->
users = Meteor.users.find({})
users.forEach (user) ->
if user.emails
email = user.emails[0].address
notes = Notes.search 'last-changed:24h', user._id
SSR.compileTemplate( 'Email_summary', Assets.getText( 'email/summary.html' ) )
html = SSR.render 'Email_summary',
site_url: Meteor.absoluteUrl()
notes: notes
Email.send({
to: email,
from: "BulletNotes.io <<EMAIL>>",
subject: "Daily Activity Summary",
html: html
})
# We don't add this to to rate limiter because imports hit it a bunch. Hence the defer.
export denormalizeChildCount = new ValidatedMethod
name: 'notes.denormalizeChildCount'
validate: new SimpleSchema
noteId: Notes.simpleSchema().schema('_id')
.validator
clean: yes
filter: no
run: ({ noteId }) ->
Meteor.defer ->
childCountDenormalizer.afterInsertNote noteId
export denormalizeRanks = new ValidatedMethod
name: 'notes.denormalizeRanks'
validate: new SimpleSchema
noteId: Notes.simpleSchema().schema('_id')
.validator
clean: yes
filter: no
run: ({ noteId }) ->
Meteor.defer ->
rankDenormalizer.updateChildren noteId
# Get note of all method names on Notes
NOTES_METHODS = _.pluck([
notesExport
dropboxExport
dropboxNightly
denormalizeRanks
summary
inbox
], 'name')
if Meteor.isServer
# Only allow 5 notes operations per connection per second
DDPRateLimiter.addRule {
name: (name) ->
_.contains NOTES_METHODS, name
# Rate limit per connection ID
connectionId: ->
yes
}, 5, 1000
| true | import { Meteor } from 'meteor/meteor'
import { _ } from 'meteor/underscore'
import { ValidatedMethod } from 'meteor/mdg:validated-method'
import SimpleSchema from 'simpl-schema'
import { DDPRateLimiter } from 'meteor/ddp-rate-limiter'
Dropbox = require('dropbox')
import rankDenormalizer from '/imports/api/notes/rankDenormalizer.coffee'
import childCountDenormalizer from '/imports/api/notes/childCountDenormalizer.coffee'
import { Notes } from '/imports/api/notes/notes.coffee'
export notesExport = new ValidatedMethod
name: 'notes.export'
validate: new SimpleSchema
noteId:
type: String
optional: true
userId: Notes.simpleSchema().schema('owner')
level: Notes.simpleSchema().schema('level')
.validator
clean: yes
filter: no
run: ({ noteId = null, userId = null, level = 0 }) ->
if !userId
userId = @userId
if !userId
throw new (Meteor.Error)('not-authorized - no userId')
topLevelNotes = Notes.find {
parent: noteId
owner: userId
deleted: {$exists: false}
}, sort: rank: 1
exportText = ''
topLevelNotes.forEach (note) ->
spacing = new Array(level * 5).join(' ')
exportText += spacing + '- '
if note.title
exportText += note.title
exportText += '\n'
if note.body
exportText += spacing + ' "' + note.body + '"\n'
exportText = exportText + notesExport.call {
noteId: note._id
userId: userId
level: level+1
}
exportText
export dropboxExport = new ValidatedMethod
name: 'notes.dropboxExport'
validate: null
run: () ->
user = Meteor.user()
if (
user.profile &&
user.profile.dropbox_token
)
exportText = notesExport.call
noteId: null
userId: user._id
dbx = new Dropbox(
accessToken: user.profile.dropbox_token
)
dbx.filesUpload(
path: '/BulletNotes'+moment().format('-YYYY-MM-DD')+'.txt'
contents: exportText).then((response) ->
console.log response
).catch (error) ->
console.error error
throw new (Meteor.Error)(error)
else
throw new (Meteor.Error)('No linked Dropbox account')
export dropboxNightly = new ValidatedMethod
name: 'notes.dropboxNightly'
validate: null
run: () ->
users = Meteor.users.find({
isPro:true
})
users.forEach (user) ->
if (
user.profile &&
user.profile.dropbox_token
)
exportText = notesExport.call
noteId: null
userId: user._id
dbx = new Dropbox(
accessToken: user.profile.dropbox_token
)
dbx.filesUpload(
path: '/BulletNotes'+moment().format('-YYYY-MM-DD')+'.txt'
contents: exportText).then((response) ->
console.log response
).catch (error) ->
console.error error
export inbox = new ValidatedMethod
name: 'notes.inbox'
validate: new SimpleSchema
title: Notes.simpleSchema().schema('title')
body: Notes.simpleSchema().schema('body')
userId: Notes.simpleSchema().schema('_id')
parentId:
type: String
optional: true
.validator
clean: yes
filter: no
# userId has already been translated from apiKey by notes/routes by the time it gets here
run: ({ title, body, userId, parentId = null }) ->
# If we have a parent note to put it under, use that. But make sure we have write permissions.
if parentId
note = Notes.findOne
owner: userId
_id: parentId
if !note
# No permission, or no note. Just quit.
false
# We don't have a specific note to put this under, put it in the Inbox
else
inbox = Notes.findOne
owner: userId
inbox: true
deleted: {$exists:false}
# If there is not an existing Inbox note, create one.
if !inbox
parentId = Notes.insert
title: ":inbox_tray: <b>Inbox</b>"
createdAt: new Date()
owner: userId
inbox: true
showChildren: true
complete: false
# Otherwise, use the existing inbox
else
parentId = inbox._id
if parentId
noteId = Notes.insert
title: title
body: body
parent: parentId
owner: userId
createdAt: new Date()
rank: 0
complete: false
Meteor.users.update userId,
{$inc:{"notesCreated":1}}
Meteor.defer ->
rankDenormalizer.updateChildren parentId
return noteId
export summary = new ValidatedMethod
name: 'notes.summary'
validate: null
run: () ->
users = Meteor.users.find({})
users.forEach (user) ->
if user.emails
email = user.emails[0].address
notes = Notes.search 'last-changed:24h', user._id
SSR.compileTemplate( 'Email_summary', Assets.getText( 'email/summary.html' ) )
html = SSR.render 'Email_summary',
site_url: Meteor.absoluteUrl()
notes: notes
Email.send({
to: email,
from: "BulletNotes.io <PI:EMAIL:<EMAIL>END_PI>",
subject: "Daily Activity Summary",
html: html
})
# We don't add this to to rate limiter because imports hit it a bunch. Hence the defer.
export denormalizeChildCount = new ValidatedMethod
name: 'notes.denormalizeChildCount'
validate: new SimpleSchema
noteId: Notes.simpleSchema().schema('_id')
.validator
clean: yes
filter: no
run: ({ noteId }) ->
Meteor.defer ->
childCountDenormalizer.afterInsertNote noteId
export denormalizeRanks = new ValidatedMethod
name: 'notes.denormalizeRanks'
validate: new SimpleSchema
noteId: Notes.simpleSchema().schema('_id')
.validator
clean: yes
filter: no
run: ({ noteId }) ->
Meteor.defer ->
rankDenormalizer.updateChildren noteId
# Get note of all method names on Notes
NOTES_METHODS = _.pluck([
notesExport
dropboxExport
dropboxNightly
denormalizeRanks
summary
inbox
], 'name')
if Meteor.isServer
# Only allow 5 notes operations per connection per second
DDPRateLimiter.addRule {
name: (name) ->
_.contains NOTES_METHODS, name
# Rate limit per connection ID
connectionId: ->
yes
}, 5, 1000
|
[
{
"context": "'Times Unmentioned']]\n csvHash = {}\n # {\n # \"Andy Warhol\": {\n # unlinkedArticles: ['writer.artsy.net/",
"end": 1007,
"score": 0.9998501539230347,
"start": 996,
"tag": "NAME",
"value": "Andy Warhol"
}
] | scripts/unlinked_artists.coffee | craigspaeth/positron | 0 | #
# A script that identifies articles that use artist names that aren't linked.
# Currently just run locally to report to the Growth team once and a while.
#
require('node-env-file')(require('path').resolve __dirname, '../.env')
db = require '../src/api/lib/db'
cheerio = require 'cheerio'
fs = require 'fs'
_ = require 'underscore'
_s = require 'underscore.string'
debug = require('debug') 'scripts'
# upload an array of artist names to search for in this directory
ARTISTS = require './artist_list.coffee'
#Pull all of the articles into memory and extract out their html
db.articles.find({ published: true }).toArray (err, articles) ->
return exit err if err
debug "Found #{articles?.length} articles, extracting html..."
articlesElements = articles.map getHtmlFrom
# Parse the HTML and find any instances of artist names not inside <a>s
csv = [['Artist Name', 'Unlinked Articles', 'Unlinked Artsy URLs', 'Total Articles Unlinked', 'Times Unmentioned']]
csvHash = {}
# {
# "Andy Warhol": {
# unlinkedArticles: ['writer.artsy.net/...']
# unlinkedArtsyUrls: ['artsy.net/article/...']
# totalUnlinked: 5
# timesUnmentioned: 10
# }
# }
for article, i in articles
unlinkedArtistNamesAndCounts = findUnlinked articlesElements[i]
for artistName, unmentionedCount of unlinkedArtistNamesAndCounts
csvHash[artistName] ?= { unlinkedArticles: [], unlinkedArtsyUrls: [], totalUnlinked: 0, timesUnmentioned: 0 }
csvHash[artistName].unlinkedArticles.push(
"http://writer.artsy.net/articles/#{article._id}/edit"
)
csvHash[artistName].unlinkedArtsyUrls.push(
"http://artsy.net/article/#{article.slugs.slice(-1)[0]}"
)
csvHash[artistName].timesUnmentioned += unmentionedCount
debug "Searched #{i + 1 * 1000} articles..." if i % 1000 is 0
for artistName, data of csvHash
csv.push [
artistName
data.unlinkedArticles.join(' | ')
data.unlinkedArtsyUrls.join(' | ')
data.unlinkedArticles.length
data.timesUnmentioned
]
# Build up a CSV string and write the file
csvstring = ''
csvstring += row.join(',') + '\n' for row in csv
fs.writeFileSync(__dirname + '/tmp/unlinked_artists.csv', csvstring)
debug 'CSV written'
process.exit()
findUnlinked = ($) ->
namesAndCounts = {}
html = $.html().toLowerCase()
for name in ARTISTS
nameLink = 'artsy.net/artist/' + name.toLowerCase().split(' ').join('-')
# if name appears in article without a link
if (_s.count html, nameLink) is 0 && (_s.count html, name) > 0
namesAndCounts[name] = _s.count html, name
namesAndCounts
getHtmlFrom = (article) ->
texts = (section.body for section in article.sections \
when section.type is 'text').join('') + article.lead_paragraph
$ = cheerio.load texts
exit = (err) ->
console.error "ERROR", err
process.exit 1
| 172742 | #
# A script that identifies articles that use artist names that aren't linked.
# Currently just run locally to report to the Growth team once and a while.
#
require('node-env-file')(require('path').resolve __dirname, '../.env')
db = require '../src/api/lib/db'
cheerio = require 'cheerio'
fs = require 'fs'
_ = require 'underscore'
_s = require 'underscore.string'
debug = require('debug') 'scripts'
# upload an array of artist names to search for in this directory
ARTISTS = require './artist_list.coffee'
#Pull all of the articles into memory and extract out their html
db.articles.find({ published: true }).toArray (err, articles) ->
return exit err if err
debug "Found #{articles?.length} articles, extracting html..."
articlesElements = articles.map getHtmlFrom
# Parse the HTML and find any instances of artist names not inside <a>s
csv = [['Artist Name', 'Unlinked Articles', 'Unlinked Artsy URLs', 'Total Articles Unlinked', 'Times Unmentioned']]
csvHash = {}
# {
# "<NAME>": {
# unlinkedArticles: ['writer.artsy.net/...']
# unlinkedArtsyUrls: ['artsy.net/article/...']
# totalUnlinked: 5
# timesUnmentioned: 10
# }
# }
for article, i in articles
unlinkedArtistNamesAndCounts = findUnlinked articlesElements[i]
for artistName, unmentionedCount of unlinkedArtistNamesAndCounts
csvHash[artistName] ?= { unlinkedArticles: [], unlinkedArtsyUrls: [], totalUnlinked: 0, timesUnmentioned: 0 }
csvHash[artistName].unlinkedArticles.push(
"http://writer.artsy.net/articles/#{article._id}/edit"
)
csvHash[artistName].unlinkedArtsyUrls.push(
"http://artsy.net/article/#{article.slugs.slice(-1)[0]}"
)
csvHash[artistName].timesUnmentioned += unmentionedCount
debug "Searched #{i + 1 * 1000} articles..." if i % 1000 is 0
for artistName, data of csvHash
csv.push [
artistName
data.unlinkedArticles.join(' | ')
data.unlinkedArtsyUrls.join(' | ')
data.unlinkedArticles.length
data.timesUnmentioned
]
# Build up a CSV string and write the file
csvstring = ''
csvstring += row.join(',') + '\n' for row in csv
fs.writeFileSync(__dirname + '/tmp/unlinked_artists.csv', csvstring)
debug 'CSV written'
process.exit()
findUnlinked = ($) ->
namesAndCounts = {}
html = $.html().toLowerCase()
for name in ARTISTS
nameLink = 'artsy.net/artist/' + name.toLowerCase().split(' ').join('-')
# if name appears in article without a link
if (_s.count html, nameLink) is 0 && (_s.count html, name) > 0
namesAndCounts[name] = _s.count html, name
namesAndCounts
getHtmlFrom = (article) ->
texts = (section.body for section in article.sections \
when section.type is 'text').join('') + article.lead_paragraph
$ = cheerio.load texts
exit = (err) ->
console.error "ERROR", err
process.exit 1
| true | #
# A script that identifies articles that use artist names that aren't linked.
# Currently just run locally to report to the Growth team once and a while.
#
require('node-env-file')(require('path').resolve __dirname, '../.env')
db = require '../src/api/lib/db'
cheerio = require 'cheerio'
fs = require 'fs'
_ = require 'underscore'
_s = require 'underscore.string'
debug = require('debug') 'scripts'
# upload an array of artist names to search for in this directory
ARTISTS = require './artist_list.coffee'
#Pull all of the articles into memory and extract out their html
db.articles.find({ published: true }).toArray (err, articles) ->
return exit err if err
debug "Found #{articles?.length} articles, extracting html..."
articlesElements = articles.map getHtmlFrom
# Parse the HTML and find any instances of artist names not inside <a>s
csv = [['Artist Name', 'Unlinked Articles', 'Unlinked Artsy URLs', 'Total Articles Unlinked', 'Times Unmentioned']]
csvHash = {}
# {
# "PI:NAME:<NAME>END_PI": {
# unlinkedArticles: ['writer.artsy.net/...']
# unlinkedArtsyUrls: ['artsy.net/article/...']
# totalUnlinked: 5
# timesUnmentioned: 10
# }
# }
for article, i in articles
unlinkedArtistNamesAndCounts = findUnlinked articlesElements[i]
for artistName, unmentionedCount of unlinkedArtistNamesAndCounts
csvHash[artistName] ?= { unlinkedArticles: [], unlinkedArtsyUrls: [], totalUnlinked: 0, timesUnmentioned: 0 }
csvHash[artistName].unlinkedArticles.push(
"http://writer.artsy.net/articles/#{article._id}/edit"
)
csvHash[artistName].unlinkedArtsyUrls.push(
"http://artsy.net/article/#{article.slugs.slice(-1)[0]}"
)
csvHash[artistName].timesUnmentioned += unmentionedCount
debug "Searched #{i + 1 * 1000} articles..." if i % 1000 is 0
for artistName, data of csvHash
csv.push [
artistName
data.unlinkedArticles.join(' | ')
data.unlinkedArtsyUrls.join(' | ')
data.unlinkedArticles.length
data.timesUnmentioned
]
# Build up a CSV string and write the file
csvstring = ''
csvstring += row.join(',') + '\n' for row in csv
fs.writeFileSync(__dirname + '/tmp/unlinked_artists.csv', csvstring)
debug 'CSV written'
process.exit()
findUnlinked = ($) ->
namesAndCounts = {}
html = $.html().toLowerCase()
for name in ARTISTS
nameLink = 'artsy.net/artist/' + name.toLowerCase().split(' ').join('-')
# if name appears in article without a link
if (_s.count html, nameLink) is 0 && (_s.count html, name) > 0
namesAndCounts[name] = _s.count html, name
namesAndCounts
getHtmlFrom = (article) ->
texts = (section.body for section in article.sections \
when section.type is 'text').join('') + article.lead_paragraph
$ = cheerio.load texts
exit = (err) ->
console.error "ERROR", err
process.exit 1
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999106526374817,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/modding-profile/stats.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 { div, dd, dl, dt } from 'react-dom-factories'
el = React.createElement
export class Stats extends React.PureComponent
entries = [
'ranked_and_approved_beatmapset_count'
'loved_beatmapset_count'
'unranked_beatmapset_count'
'graveyard_beatmapset_count'
]
render: =>
div className: 'profile-stats', entries.map(@renderEntry)
renderEntry: (key) =>
dl
className: 'profile-stats__entry'
key: key
dt className: 'profile-stats__key', osu.trans("users.show.stats.#{key}")
dd className: 'profile-stats__value', osu.formatNumber(@props.user[key])
| 223616 | # 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 { div, dd, dl, dt } from 'react-dom-factories'
el = React.createElement
export class Stats extends React.PureComponent
entries = [
'ranked_and_approved_beatmapset_count'
'loved_beatmapset_count'
'unranked_beatmapset_count'
'graveyard_beatmapset_count'
]
render: =>
div className: 'profile-stats', entries.map(@renderEntry)
renderEntry: (key) =>
dl
className: 'profile-stats__entry'
key: key
dt className: 'profile-stats__key', osu.trans("users.show.stats.#{key}")
dd className: 'profile-stats__value', osu.formatNumber(@props.user[key])
| 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 { div, dd, dl, dt } from 'react-dom-factories'
el = React.createElement
export class Stats extends React.PureComponent
entries = [
'ranked_and_approved_beatmapset_count'
'loved_beatmapset_count'
'unranked_beatmapset_count'
'graveyard_beatmapset_count'
]
render: =>
div className: 'profile-stats', entries.map(@renderEntry)
renderEntry: (key) =>
dl
className: 'profile-stats__entry'
key: key
dt className: 'profile-stats__key', osu.trans("users.show.stats.#{key}")
dd className: 'profile-stats__value', osu.formatNumber(@props.user[key])
|
[
{
"context": "{\n name: 'string'\n image: 'string'\n bio: 'text'\n}\n",
"end": 17,
"score": 0.6627017259597778,
"start": 11,
"tag": "NAME",
"value": "string"
}
] | bootstrap/app/schema/biography.cson | lessthan3/dobi | 5 | {
name: 'string'
image: 'string'
bio: 'text'
}
| 85742 | {
name: '<NAME>'
image: 'string'
bio: 'text'
}
| true | {
name: 'PI:NAME:<NAME>END_PI'
image: 'string'
bio: 'text'
}
|
[
{
"context": "er name</span>\n <input type=\"text\" name=\"username\" />\n </label>\n\n <label>\n <",
"end": 206,
"score": 0.9995421171188354,
"start": 198,
"tag": "USERNAME",
"value": "username"
},
{
"context": " <span>Password</span>\n <input type=\"password\" name=\"password\" />\n </label>\n\n <bu",
"end": 308,
"score": 0.9971258044242859,
"start": 300,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "ord</span>\n <input type=\"password\" name=\"password\" />\n </label>\n\n <button type=\"submi",
"end": 324,
"score": 0.6630483269691467,
"start": 316,
"tag": "PASSWORD",
"value": "password"
}
] | framework-idea/scripts/src/lib/zooniverse/views/LoginForm.coffee | zooniverse/Front-End-Assets | 0 | define (require, exports, module) ->
'''
<div class="errors"></div>
<div class="sign-in">
<form>
<label>
<span>User name</span>
<input type="text" name="username" />
</label>
<label>
<span>Password</span>
<input type="password" name="password" />
</label>
<button type="submit">Sign in</button>
</form>
</div>
<div class="waiting">Signing in...</div>
<div class="sign-out">
<p>Currently logged in as <strong class="current"></strong>. <button>Sign out</button></p>
</div>
'''
| 102087 | define (require, exports, module) ->
'''
<div class="errors"></div>
<div class="sign-in">
<form>
<label>
<span>User name</span>
<input type="text" name="username" />
</label>
<label>
<span>Password</span>
<input type="<PASSWORD>" name="<PASSWORD>" />
</label>
<button type="submit">Sign in</button>
</form>
</div>
<div class="waiting">Signing in...</div>
<div class="sign-out">
<p>Currently logged in as <strong class="current"></strong>. <button>Sign out</button></p>
</div>
'''
| true | define (require, exports, module) ->
'''
<div class="errors"></div>
<div class="sign-in">
<form>
<label>
<span>User name</span>
<input type="text" name="username" />
</label>
<label>
<span>Password</span>
<input type="PI:PASSWORD:<PASSWORD>END_PI" name="PI:PASSWORD:<PASSWORD>END_PI" />
</label>
<button type="submit">Sign in</button>
</form>
</div>
<div class="waiting">Signing in...</div>
<div class="sign-out">
<p>Currently logged in as <strong class="current"></strong>. <button>Sign out</button></p>
</div>
'''
|
[
{
"context": "er\n# @todo Refactor\n# property factory\n# @author Netzpirat\n# @author Supermakaka\n# @abstract Each listener i",
"end": 283,
"score": 0.9211699962615967,
"start": 274,
"tag": "NAME",
"value": "Netzpirat"
},
{
"context": "# property factory\n# @author Netzpirat\n# @author Supermakaka\n# @abstract Each listener implementation must inc",
"end": 305,
"score": 0.9765374064445496,
"start": 294,
"tag": "NAME",
"value": "Supermakaka"
}
] | node_modules/grunt-codo/node_modules/codo/spec/_templates/mixins/mixin_documentation.coffee | fredturnerr/SRT | 1 | # This is a test module with `inline.dot`. Beware.
#
# @note Please use
# this carefully
# @note For internal use only
#
# @example Use it in this way
# class Rumba
# @include Foo.Bar
#
# @todo Clean up socket handler
# @todo Refactor
# property factory
# @author Netzpirat
# @author Supermakaka
# @abstract Each listener implementation must include
# @private
# @deprecated Use other module
# which is thread safe
# @since 1.0.0
# @version 1.0.2
#
# @mixin
#
Foo.Bar = {}
| 208214 | # This is a test module with `inline.dot`. Beware.
#
# @note Please use
# this carefully
# @note For internal use only
#
# @example Use it in this way
# class Rumba
# @include Foo.Bar
#
# @todo Clean up socket handler
# @todo Refactor
# property factory
# @author <NAME>
# @author <NAME>
# @abstract Each listener implementation must include
# @private
# @deprecated Use other module
# which is thread safe
# @since 1.0.0
# @version 1.0.2
#
# @mixin
#
Foo.Bar = {}
| true | # This is a test module with `inline.dot`. Beware.
#
# @note Please use
# this carefully
# @note For internal use only
#
# @example Use it in this way
# class Rumba
# @include Foo.Bar
#
# @todo Clean up socket handler
# @todo Refactor
# property factory
# @author PI:NAME:<NAME>END_PI
# @author PI:NAME:<NAME>END_PI
# @abstract Each listener implementation must include
# @private
# @deprecated Use other module
# which is thread safe
# @since 1.0.0
# @version 1.0.2
#
# @mixin
#
Foo.Bar = {}
|
[
{
"context": "key: 'ia-writer'\npatterns: [\n\n {\n match: '(?x)\n ^\\\\s{0,3",
"end": 15,
"score": 0.9992022514343262,
"start": 6,
"tag": "KEY",
"value": "ia-writer"
}
] | grammars/repositories/flavors/ia-writer.cson | doc22940/language-markdown | 138 | key: 'ia-writer'
patterns: [
{
match: '(?x)
^\\s{0,3}(
(/)([^\'"()]*?)
(\\.[a-z0-9]+)
(\\s*?)
(("|\')[^\'"]*?(\\7))?
)$'
captures:
1: name: 'block.content.link.markup.md'
2: name: 'punctuation.md'
# 4: name: 'punctuation.md'
6: name: 'title.string.markup.md'
7: name: 'punctuation.md'
8: name: 'punctuation.md'
}
{
match: '(?x)
^\\s{0,3}(
(/)([^\'"()]*?)
(\\.[a-z0-9]+)
(\\s*?)
((\\()[^()]*?(\\)))?
)$'
captures:
1: name: 'block.content.link.markup.md'
2: name: 'punctuation.md'
# 4: name: 'punctuation.md'
6: name: 'title.string.markup.md'
7: name: 'punctuation.md'
8: name: 'punctuation.md'
}
]
| 199554 | key: '<KEY>'
patterns: [
{
match: '(?x)
^\\s{0,3}(
(/)([^\'"()]*?)
(\\.[a-z0-9]+)
(\\s*?)
(("|\')[^\'"]*?(\\7))?
)$'
captures:
1: name: 'block.content.link.markup.md'
2: name: 'punctuation.md'
# 4: name: 'punctuation.md'
6: name: 'title.string.markup.md'
7: name: 'punctuation.md'
8: name: 'punctuation.md'
}
{
match: '(?x)
^\\s{0,3}(
(/)([^\'"()]*?)
(\\.[a-z0-9]+)
(\\s*?)
((\\()[^()]*?(\\)))?
)$'
captures:
1: name: 'block.content.link.markup.md'
2: name: 'punctuation.md'
# 4: name: 'punctuation.md'
6: name: 'title.string.markup.md'
7: name: 'punctuation.md'
8: name: 'punctuation.md'
}
]
| true | key: 'PI:KEY:<KEY>END_PI'
patterns: [
{
match: '(?x)
^\\s{0,3}(
(/)([^\'"()]*?)
(\\.[a-z0-9]+)
(\\s*?)
(("|\')[^\'"]*?(\\7))?
)$'
captures:
1: name: 'block.content.link.markup.md'
2: name: 'punctuation.md'
# 4: name: 'punctuation.md'
6: name: 'title.string.markup.md'
7: name: 'punctuation.md'
8: name: 'punctuation.md'
}
{
match: '(?x)
^\\s{0,3}(
(/)([^\'"()]*?)
(\\.[a-z0-9]+)
(\\s*?)
((\\()[^()]*?(\\)))?
)$'
captures:
1: name: 'block.content.link.markup.md'
2: name: 'punctuation.md'
# 4: name: 'punctuation.md'
6: name: 'title.string.markup.md'
7: name: 'punctuation.md'
8: name: 'punctuation.md'
}
]
|
[
{
"context": "\n a_post = $('a.js-post').postify {csrfToken: \"foobar\", }\n plugin_postify = a_post.first().data 'plu",
"end": 286,
"score": 0.8149958252906799,
"start": 280,
"tag": "PASSWORD",
"value": "foobar"
}
] | spirit/static/spirit/scripts/test/suites/postify-spec.coffee | rterehov/Spirit | 1 | describe "postify plugin tests", ->
a_post = null
plugin_postify = null
Postify = null
beforeEach ->
fixtures = do jasmine.getFixtures
fixtures.fixturesPath = 'base/test/fixtures/'
loadFixtures 'postify.html'
a_post = $('a.js-post').postify {csrfToken: "foobar", }
plugin_postify = a_post.first().data 'plugin_postify'
Postify = $.fn.postify.Postify
it "doesnt break selector chaining", ->
expect(a_post).toEqual $('.js-post')
expect(a_post.length).toEqual 2
it "prevents the default click behaviour on click", ->
event = {type: 'click', stopPropagation: (->), preventDefault: (->)}
stopPropagation = spyOn event, 'stopPropagation'
preventDefault = spyOn event, 'preventDefault'
spyOn plugin_postify, 'formSubmit'
$(".js-post").first().trigger event
expect(stopPropagation).toHaveBeenCalled()
expect(preventDefault).toHaveBeenCalled()
it "submits the form", ->
formSubmit = spyOn plugin_postify, 'formSubmit'
$('.js-post').first().trigger 'click'
expect(formSubmit).toHaveBeenCalled()
expect($("form").last().attr('action')).toEqual "/link1/"
expect($("form").last().is ":visible").toEqual false
expect($("input[name=csrfmiddlewaretoken]").val()).toEqual "foobar" | 9555 | describe "postify plugin tests", ->
a_post = null
plugin_postify = null
Postify = null
beforeEach ->
fixtures = do jasmine.getFixtures
fixtures.fixturesPath = 'base/test/fixtures/'
loadFixtures 'postify.html'
a_post = $('a.js-post').postify {csrfToken: "<PASSWORD>", }
plugin_postify = a_post.first().data 'plugin_postify'
Postify = $.fn.postify.Postify
it "doesnt break selector chaining", ->
expect(a_post).toEqual $('.js-post')
expect(a_post.length).toEqual 2
it "prevents the default click behaviour on click", ->
event = {type: 'click', stopPropagation: (->), preventDefault: (->)}
stopPropagation = spyOn event, 'stopPropagation'
preventDefault = spyOn event, 'preventDefault'
spyOn plugin_postify, 'formSubmit'
$(".js-post").first().trigger event
expect(stopPropagation).toHaveBeenCalled()
expect(preventDefault).toHaveBeenCalled()
it "submits the form", ->
formSubmit = spyOn plugin_postify, 'formSubmit'
$('.js-post').first().trigger 'click'
expect(formSubmit).toHaveBeenCalled()
expect($("form").last().attr('action')).toEqual "/link1/"
expect($("form").last().is ":visible").toEqual false
expect($("input[name=csrfmiddlewaretoken]").val()).toEqual "foobar" | true | describe "postify plugin tests", ->
a_post = null
plugin_postify = null
Postify = null
beforeEach ->
fixtures = do jasmine.getFixtures
fixtures.fixturesPath = 'base/test/fixtures/'
loadFixtures 'postify.html'
a_post = $('a.js-post').postify {csrfToken: "PI:PASSWORD:<PASSWORD>END_PI", }
plugin_postify = a_post.first().data 'plugin_postify'
Postify = $.fn.postify.Postify
it "doesnt break selector chaining", ->
expect(a_post).toEqual $('.js-post')
expect(a_post.length).toEqual 2
it "prevents the default click behaviour on click", ->
event = {type: 'click', stopPropagation: (->), preventDefault: (->)}
stopPropagation = spyOn event, 'stopPropagation'
preventDefault = spyOn event, 'preventDefault'
spyOn plugin_postify, 'formSubmit'
$(".js-post").first().trigger event
expect(stopPropagation).toHaveBeenCalled()
expect(preventDefault).toHaveBeenCalled()
it "submits the form", ->
formSubmit = spyOn plugin_postify, 'formSubmit'
$('.js-post').first().trigger 'click'
expect(formSubmit).toHaveBeenCalled()
expect($("form").last().attr('action')).toEqual "/link1/"
expect($("form").last().is ":visible").toEqual false
expect($("input[name=csrfmiddlewaretoken]").val()).toEqual "foobar" |
[
{
"context": "to Javascript files.\n \n @version 0.0.1\n @author Fabian M. <mail.fabianm@gmail.com>\n###\nmodule.exports = ->",
"end": 206,
"score": 0.9998161792755127,
"start": 198,
"tag": "NAME",
"value": "Fabian M"
},
{
"context": "t files.\n \n @version 0.0.1\n @author Fabian M. <mail.fabianm@gmail.com>\n###\nmodule.exports = ->\n\t###\n\t Utility to creat",
"end": 231,
"score": 0.9999329447746277,
"start": 209,
"tag": "EMAIL",
"value": "mail.fabianm@gmail.com"
}
] | kaffee-coffeemaker/src/main/plugin.coffee | fabianm/kaffee | 1 | Fs = require "fs"
Path = require "path"
CoffeeScript = require "coffee-script"
###
The kaffee-coffeemaker plugins compiles Coffeescript files into Javascript files.
@version 0.0.1
@author Fabian M. <mail.fabianm@gmail.com>
###
module.exports = ->
###
Utility to create a directory.
@since 0.0.1
@param path The path to the directory to create.
###
mkdir = (path) ->
try
Fs.mkdirSync path
catch e
if e.errno is 34
mkdir Path.dirname(path)
mkdir path
###
Returns an array of Coffeescript files in the given directory
and its childs.
@since 0.0.1
@param path The path to the directory.
@return An array of Coffeescript files in the given directory
and its childs.
###
getFiles = (path) ->
return [] if not Fs.existsSync path
files = []
files.push Path.join(path, file) for file in Fs.readdirSync path
files
###
Tests all Coffeescript files in the given directory.
@since 0.0.1
@param path The path to the directory to check.
@return <code>true</code> if no errors occured, <code>false</code> otherwise.
###
test = (path) ->
ok = true
for file in getFiles(path)
try
stats = Fs.lstatSync file
if stats.isDirectory()
ok = false unless test.call this, file
continue
CoffeeScript.compile Fs.readFileSync(file, 'UTF-8') if Path.extname(file) is ".coffee"
catch e
e.message += " in #{ file }"
this.logger.error e
return false
ok
###
Compiles all Coffeescript files in the given directory.
@since 0.0.1
@param goal The goal instance.
@param path The path to the input directory.
@param output The path to the output directory.
###
compile = (path, output) ->
return unless test.call this, path
files = getFiles path
mkdir output unless Fs.existsSync(output) and files.length > 0
for file, i in getFiles(path)
try
stats = Fs.lstatSync file
compile.call this, file, Path.join(output, Path.basename(file)) if stats.isDirectory()
if Path.extname(file) is ".coffee"
this.logger.info file
fd = Fs.openSync Path.join(output, Path.basename(file, ".coffee") + ".js"), "w"
out = CoffeeScript.compile Fs.readFileSync(file, 'UTF-8')
Fs.writeSync fd, out, 0, out.length
Fs.closeSync fd
else if Path.basename(file) is "package.json"
this.logger.info file
fd = Fs.openSync Path.join(output, Path.basename(file)), "w"
out = Fs.readFileSync file, 'UTF-8'
Fs.writeSync fd, out, 0, out.length
Fs.closeSync fd
catch e
e.message += " in #{ file }"
this.logger.error e
###
Compiles Coffeescript files into Javascript files.
###
this.register "compile", (request) ->
this.dependsOn "clean", request
structure = this.getProject().getConfiguration().getKaffeeConfiguration().getStructure()
return this.logger.warn "No structure" unless structure
this.logger.info "Compiling files for project #{ this.getProject().getConfiguration().getName() }"
compile.call this, structure.get('src'), structure.get('bin')
compile.call this, structure.get('src-test'), structure.get('bin-test')
###
Tests Coffeescript files.
###
this.register "test", ->
structure = this.getProject().getConfiguration().getKaffeeConfiguration().getStructure()
return this.logger.warn "No structure" unless structure
this.logger.info "Testing files for project #{ this.getProject().getConfiguration().getName() }"
ok = test.call(this, structure.get('src')) and test.call(this, structure.get('src-test'))
if ok then this.logger.info "Test passed!" else this.logger.warn "Test failed!"
###
Registers the archtype.
###
this.archtype
kaffee:
plugins:
"kaffee-coffeemaker" : {}
lifecycles:
"compile" : ["kaffee-coffeemaker:compile"]
"test" : ["kaffee-coffeemaker:test"]
| 104196 | Fs = require "fs"
Path = require "path"
CoffeeScript = require "coffee-script"
###
The kaffee-coffeemaker plugins compiles Coffeescript files into Javascript files.
@version 0.0.1
@author <NAME>. <<EMAIL>>
###
module.exports = ->
###
Utility to create a directory.
@since 0.0.1
@param path The path to the directory to create.
###
mkdir = (path) ->
try
Fs.mkdirSync path
catch e
if e.errno is 34
mkdir Path.dirname(path)
mkdir path
###
Returns an array of Coffeescript files in the given directory
and its childs.
@since 0.0.1
@param path The path to the directory.
@return An array of Coffeescript files in the given directory
and its childs.
###
getFiles = (path) ->
return [] if not Fs.existsSync path
files = []
files.push Path.join(path, file) for file in Fs.readdirSync path
files
###
Tests all Coffeescript files in the given directory.
@since 0.0.1
@param path The path to the directory to check.
@return <code>true</code> if no errors occured, <code>false</code> otherwise.
###
test = (path) ->
ok = true
for file in getFiles(path)
try
stats = Fs.lstatSync file
if stats.isDirectory()
ok = false unless test.call this, file
continue
CoffeeScript.compile Fs.readFileSync(file, 'UTF-8') if Path.extname(file) is ".coffee"
catch e
e.message += " in #{ file }"
this.logger.error e
return false
ok
###
Compiles all Coffeescript files in the given directory.
@since 0.0.1
@param goal The goal instance.
@param path The path to the input directory.
@param output The path to the output directory.
###
compile = (path, output) ->
return unless test.call this, path
files = getFiles path
mkdir output unless Fs.existsSync(output) and files.length > 0
for file, i in getFiles(path)
try
stats = Fs.lstatSync file
compile.call this, file, Path.join(output, Path.basename(file)) if stats.isDirectory()
if Path.extname(file) is ".coffee"
this.logger.info file
fd = Fs.openSync Path.join(output, Path.basename(file, ".coffee") + ".js"), "w"
out = CoffeeScript.compile Fs.readFileSync(file, 'UTF-8')
Fs.writeSync fd, out, 0, out.length
Fs.closeSync fd
else if Path.basename(file) is "package.json"
this.logger.info file
fd = Fs.openSync Path.join(output, Path.basename(file)), "w"
out = Fs.readFileSync file, 'UTF-8'
Fs.writeSync fd, out, 0, out.length
Fs.closeSync fd
catch e
e.message += " in #{ file }"
this.logger.error e
###
Compiles Coffeescript files into Javascript files.
###
this.register "compile", (request) ->
this.dependsOn "clean", request
structure = this.getProject().getConfiguration().getKaffeeConfiguration().getStructure()
return this.logger.warn "No structure" unless structure
this.logger.info "Compiling files for project #{ this.getProject().getConfiguration().getName() }"
compile.call this, structure.get('src'), structure.get('bin')
compile.call this, structure.get('src-test'), structure.get('bin-test')
###
Tests Coffeescript files.
###
this.register "test", ->
structure = this.getProject().getConfiguration().getKaffeeConfiguration().getStructure()
return this.logger.warn "No structure" unless structure
this.logger.info "Testing files for project #{ this.getProject().getConfiguration().getName() }"
ok = test.call(this, structure.get('src')) and test.call(this, structure.get('src-test'))
if ok then this.logger.info "Test passed!" else this.logger.warn "Test failed!"
###
Registers the archtype.
###
this.archtype
kaffee:
plugins:
"kaffee-coffeemaker" : {}
lifecycles:
"compile" : ["kaffee-coffeemaker:compile"]
"test" : ["kaffee-coffeemaker:test"]
| true | Fs = require "fs"
Path = require "path"
CoffeeScript = require "coffee-script"
###
The kaffee-coffeemaker plugins compiles Coffeescript files into Javascript files.
@version 0.0.1
@author PI:NAME:<NAME>END_PI. <PI:EMAIL:<EMAIL>END_PI>
###
module.exports = ->
###
Utility to create a directory.
@since 0.0.1
@param path The path to the directory to create.
###
mkdir = (path) ->
try
Fs.mkdirSync path
catch e
if e.errno is 34
mkdir Path.dirname(path)
mkdir path
###
Returns an array of Coffeescript files in the given directory
and its childs.
@since 0.0.1
@param path The path to the directory.
@return An array of Coffeescript files in the given directory
and its childs.
###
getFiles = (path) ->
return [] if not Fs.existsSync path
files = []
files.push Path.join(path, file) for file in Fs.readdirSync path
files
###
Tests all Coffeescript files in the given directory.
@since 0.0.1
@param path The path to the directory to check.
@return <code>true</code> if no errors occured, <code>false</code> otherwise.
###
test = (path) ->
ok = true
for file in getFiles(path)
try
stats = Fs.lstatSync file
if stats.isDirectory()
ok = false unless test.call this, file
continue
CoffeeScript.compile Fs.readFileSync(file, 'UTF-8') if Path.extname(file) is ".coffee"
catch e
e.message += " in #{ file }"
this.logger.error e
return false
ok
###
Compiles all Coffeescript files in the given directory.
@since 0.0.1
@param goal The goal instance.
@param path The path to the input directory.
@param output The path to the output directory.
###
compile = (path, output) ->
return unless test.call this, path
files = getFiles path
mkdir output unless Fs.existsSync(output) and files.length > 0
for file, i in getFiles(path)
try
stats = Fs.lstatSync file
compile.call this, file, Path.join(output, Path.basename(file)) if stats.isDirectory()
if Path.extname(file) is ".coffee"
this.logger.info file
fd = Fs.openSync Path.join(output, Path.basename(file, ".coffee") + ".js"), "w"
out = CoffeeScript.compile Fs.readFileSync(file, 'UTF-8')
Fs.writeSync fd, out, 0, out.length
Fs.closeSync fd
else if Path.basename(file) is "package.json"
this.logger.info file
fd = Fs.openSync Path.join(output, Path.basename(file)), "w"
out = Fs.readFileSync file, 'UTF-8'
Fs.writeSync fd, out, 0, out.length
Fs.closeSync fd
catch e
e.message += " in #{ file }"
this.logger.error e
###
Compiles Coffeescript files into Javascript files.
###
this.register "compile", (request) ->
this.dependsOn "clean", request
structure = this.getProject().getConfiguration().getKaffeeConfiguration().getStructure()
return this.logger.warn "No structure" unless structure
this.logger.info "Compiling files for project #{ this.getProject().getConfiguration().getName() }"
compile.call this, structure.get('src'), structure.get('bin')
compile.call this, structure.get('src-test'), structure.get('bin-test')
###
Tests Coffeescript files.
###
this.register "test", ->
structure = this.getProject().getConfiguration().getKaffeeConfiguration().getStructure()
return this.logger.warn "No structure" unless structure
this.logger.info "Testing files for project #{ this.getProject().getConfiguration().getName() }"
ok = test.call(this, structure.get('src')) and test.call(this, structure.get('src-test'))
if ok then this.logger.info "Test passed!" else this.logger.warn "Test failed!"
###
Registers the archtype.
###
this.archtype
kaffee:
plugins:
"kaffee-coffeemaker" : {}
lifecycles:
"compile" : ["kaffee-coffeemaker:compile"]
"test" : ["kaffee-coffeemaker:test"]
|
[
{
"context": "tenantId: '53af466e96ab7635384b71fb'\n username: 'mw1' \n userA:\n username: 'mw1'\n password: ",
"end": 75,
"score": 0.999578058719635,
"start": 72,
"tag": "USERNAME",
"value": "mw1"
},
{
"context": "1fb'\n username: 'mw1' \n userA:\n username: 'mw1'\n password: 'abcdefgh1'\n primaryEmail:'",
"end": 107,
"score": 0.999575138092041,
"start": 104,
"tag": "USERNAME",
"value": "mw1"
},
{
"context": " \n userA:\n username: 'mw1'\n password: 'abcdefgh1'\n primaryEmail:'martin@wawrusch.com'\n r",
"end": 135,
"score": 0.9992704391479492,
"start": 126,
"tag": "PASSWORD",
"value": "abcdefgh1"
},
{
"context": "'\n password: 'abcdefgh1'\n primaryEmail:'martin@wawrusch.com'\n roles: ['rolea','roleb','rolec']\n \n",
"end": 176,
"score": 0.999924898147583,
"start": 157,
"tag": "EMAIL",
"value": "martin@wawrusch.com"
}
] | test/support/fixtures.coffee | codedoctor/hapi-auth-bearer-mw | 1 |
module.exports =
tenantId: '53af466e96ab7635384b71fb'
username: 'mw1'
userA:
username: 'mw1'
password: 'abcdefgh1'
primaryEmail:'martin@wawrusch.com'
roles: ['rolea','roleb','rolec']
| 164837 |
module.exports =
tenantId: '53af466e96ab7635384b71fb'
username: 'mw1'
userA:
username: 'mw1'
password: '<PASSWORD>'
primaryEmail:'<EMAIL>'
roles: ['rolea','roleb','rolec']
| true |
module.exports =
tenantId: '53af466e96ab7635384b71fb'
username: 'mw1'
userA:
username: 'mw1'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
primaryEmail:'PI:EMAIL:<EMAIL>END_PI'
roles: ['rolea','roleb','rolec']
|
[
{
"context": "eepalive\n# GET /heroku/keepalive\n#\n# Author:\n# Josh Nichols <technicalpickles@github.com>\n\nmodule.exports = (",
"end": 778,
"score": 0.9998165369033813,
"start": 766,
"tag": "NAME",
"value": "Josh Nichols"
},
{
"context": "T /heroku/keepalive\n#\n# Author:\n# Josh Nichols <technicalpickles@github.com>\n\nmodule.exports = (robot) ->\n wakeUpTime = (pro",
"end": 807,
"score": 0.9999237656593323,
"start": 780,
"tag": "EMAIL",
"value": "technicalpickles@github.com"
}
] | hubot-test-bostonstei/node_modules/hubot-heroku-keepalive/src/heroku-keepalive.coffee | dimbi/boston-stei | 1 | # Description
# A hubot script that keeps its Heroko web dynos alive.
#
# Notes:
# This replaces hubot's builtin Heroku keepalive behavior. It uses the same
# environment variable (HEROKU_URL), but removes the period ping. Pings will
# only occur between the WAKEUP_TIME and SLEEP_TIME in the timezone your
# heroku instance is running in (UTC by default).
#
# Configuration:
# HUBOT_HEROKU_KEEPALIVE_URL or HEROKU_URL: required
# HUBOT_HEROKU_KEEPALIVE_INTERVAL: optional, defaults to 5 minutes
# HUBOT_HEROKU_WAKEUP_TIME: optional, defaults to 6:00 (6 AM).
# HUBOT_HEROKU_SLEEP_TIME: optional, defaults to 22:00 (10 PM)
#
# heroku config:add TZ="America/New_York"
#
# URLs:
# POST /heroku/keepalive
# GET /heroku/keepalive
#
# Author:
# Josh Nichols <technicalpickles@github.com>
module.exports = (robot) ->
wakeUpTime = (process.env.HUBOT_HEROKU_WAKEUP_TIME or '6:00').split(':').map (i) -> parseInt i, 10
sleepTime = (process.env.HUBOT_HEROKU_SLEEP_TIME or '22:00').split(':').map (i) -> parseInt i, 10
wakeUpOffset = (60 * wakeUpTime[0] + wakeUpTime[1]) % (60 * 24)
awakeMinutes = (60 * (sleepTime[0] + 24) + sleepTime[1] - wakeUpOffset) % (60 * 24)
keepaliveUrl = process.env.HUBOT_HEROKU_KEEPALIVE_URL or process.env.HEROKU_URL
if keepaliveUrl and not keepaliveUrl.match(/\/$/)
keepaliveUrl = "#{keepaliveUrl}/"
# interval, in minutes
keepaliveInterval = if process.env.HUBOT_HEROKU_KEEPALIVE_INTERVAL?
parseFloat process.env.HUBOT_HEROKU_KEEPALIVE_INTERVAL
else
5
unless keepaliveUrl?
robot.logger.error "hubot-heroku-alive included, but missing HUBOT_HEROKU_KEEPALIVE_URL. `heroku config:set HUBOT_HEROKU_KEEPALIVE_URL=$(heroku apps:info -s | grep web-url | cut -d= -f2)`"
return
# check for legacy heroku keepalive from robot.coffee, and remove it
if robot.pingIntervalId
clearInterval(robot.pingIntervalId)
if keepaliveInterval > 0.0
robot.herokuKeepaliveIntervalId = setInterval =>
robot.logger.info 'keepalive ping'
now = new Date()
elapsedMinutes = (60 * (now.getHours() + 24) + now.getMinutes() - wakeUpOffset) % (60 * 24)
if elapsedMinutes < awakeMinutes
client = robot.http("#{keepaliveUrl}heroku/keepalive")
if process.env.EXPRESS_USER && process.env.EXPRESS_PASSWORD
client.auth(process.env.EXPRESS_USER, process.env.EXPRESS_PASSWORD)
client.post() (err, res, body) =>
if err?
robot.logger.info "keepalive pong: #{err}"
robot.emit 'error', err
else
robot.logger.info "keepalive pong: #{res.statusCode} #{body}"
else
robot.logger.info "Skipping keep alive, time to rest"
, keepaliveInterval * 60 * 1000
else
robot.logger.info "hubot-heroku-keepalive is #{keepaliveInterval}, so not keeping alive"
keepaliveCallback = (req, res) ->
res.set 'Content-Type', 'text/plain'
res.send 'OK'
# keep this different from the legacy URL in httpd.coffee
robot.router.post "/heroku/keepalive", keepaliveCallback
robot.router.get "/heroku/keepalive", keepaliveCallback
| 36305 | # Description
# A hubot script that keeps its Heroko web dynos alive.
#
# Notes:
# This replaces hubot's builtin Heroku keepalive behavior. It uses the same
# environment variable (HEROKU_URL), but removes the period ping. Pings will
# only occur between the WAKEUP_TIME and SLEEP_TIME in the timezone your
# heroku instance is running in (UTC by default).
#
# Configuration:
# HUBOT_HEROKU_KEEPALIVE_URL or HEROKU_URL: required
# HUBOT_HEROKU_KEEPALIVE_INTERVAL: optional, defaults to 5 minutes
# HUBOT_HEROKU_WAKEUP_TIME: optional, defaults to 6:00 (6 AM).
# HUBOT_HEROKU_SLEEP_TIME: optional, defaults to 22:00 (10 PM)
#
# heroku config:add TZ="America/New_York"
#
# URLs:
# POST /heroku/keepalive
# GET /heroku/keepalive
#
# Author:
# <NAME> <<EMAIL>>
module.exports = (robot) ->
wakeUpTime = (process.env.HUBOT_HEROKU_WAKEUP_TIME or '6:00').split(':').map (i) -> parseInt i, 10
sleepTime = (process.env.HUBOT_HEROKU_SLEEP_TIME or '22:00').split(':').map (i) -> parseInt i, 10
wakeUpOffset = (60 * wakeUpTime[0] + wakeUpTime[1]) % (60 * 24)
awakeMinutes = (60 * (sleepTime[0] + 24) + sleepTime[1] - wakeUpOffset) % (60 * 24)
keepaliveUrl = process.env.HUBOT_HEROKU_KEEPALIVE_URL or process.env.HEROKU_URL
if keepaliveUrl and not keepaliveUrl.match(/\/$/)
keepaliveUrl = "#{keepaliveUrl}/"
# interval, in minutes
keepaliveInterval = if process.env.HUBOT_HEROKU_KEEPALIVE_INTERVAL?
parseFloat process.env.HUBOT_HEROKU_KEEPALIVE_INTERVAL
else
5
unless keepaliveUrl?
robot.logger.error "hubot-heroku-alive included, but missing HUBOT_HEROKU_KEEPALIVE_URL. `heroku config:set HUBOT_HEROKU_KEEPALIVE_URL=$(heroku apps:info -s | grep web-url | cut -d= -f2)`"
return
# check for legacy heroku keepalive from robot.coffee, and remove it
if robot.pingIntervalId
clearInterval(robot.pingIntervalId)
if keepaliveInterval > 0.0
robot.herokuKeepaliveIntervalId = setInterval =>
robot.logger.info 'keepalive ping'
now = new Date()
elapsedMinutes = (60 * (now.getHours() + 24) + now.getMinutes() - wakeUpOffset) % (60 * 24)
if elapsedMinutes < awakeMinutes
client = robot.http("#{keepaliveUrl}heroku/keepalive")
if process.env.EXPRESS_USER && process.env.EXPRESS_PASSWORD
client.auth(process.env.EXPRESS_USER, process.env.EXPRESS_PASSWORD)
client.post() (err, res, body) =>
if err?
robot.logger.info "keepalive pong: #{err}"
robot.emit 'error', err
else
robot.logger.info "keepalive pong: #{res.statusCode} #{body}"
else
robot.logger.info "Skipping keep alive, time to rest"
, keepaliveInterval * 60 * 1000
else
robot.logger.info "hubot-heroku-keepalive is #{keepaliveInterval}, so not keeping alive"
keepaliveCallback = (req, res) ->
res.set 'Content-Type', 'text/plain'
res.send 'OK'
# keep this different from the legacy URL in httpd.coffee
robot.router.post "/heroku/keepalive", keepaliveCallback
robot.router.get "/heroku/keepalive", keepaliveCallback
| true | # Description
# A hubot script that keeps its Heroko web dynos alive.
#
# Notes:
# This replaces hubot's builtin Heroku keepalive behavior. It uses the same
# environment variable (HEROKU_URL), but removes the period ping. Pings will
# only occur between the WAKEUP_TIME and SLEEP_TIME in the timezone your
# heroku instance is running in (UTC by default).
#
# Configuration:
# HUBOT_HEROKU_KEEPALIVE_URL or HEROKU_URL: required
# HUBOT_HEROKU_KEEPALIVE_INTERVAL: optional, defaults to 5 minutes
# HUBOT_HEROKU_WAKEUP_TIME: optional, defaults to 6:00 (6 AM).
# HUBOT_HEROKU_SLEEP_TIME: optional, defaults to 22:00 (10 PM)
#
# heroku config:add TZ="America/New_York"
#
# URLs:
# POST /heroku/keepalive
# GET /heroku/keepalive
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
module.exports = (robot) ->
wakeUpTime = (process.env.HUBOT_HEROKU_WAKEUP_TIME or '6:00').split(':').map (i) -> parseInt i, 10
sleepTime = (process.env.HUBOT_HEROKU_SLEEP_TIME or '22:00').split(':').map (i) -> parseInt i, 10
wakeUpOffset = (60 * wakeUpTime[0] + wakeUpTime[1]) % (60 * 24)
awakeMinutes = (60 * (sleepTime[0] + 24) + sleepTime[1] - wakeUpOffset) % (60 * 24)
keepaliveUrl = process.env.HUBOT_HEROKU_KEEPALIVE_URL or process.env.HEROKU_URL
if keepaliveUrl and not keepaliveUrl.match(/\/$/)
keepaliveUrl = "#{keepaliveUrl}/"
# interval, in minutes
keepaliveInterval = if process.env.HUBOT_HEROKU_KEEPALIVE_INTERVAL?
parseFloat process.env.HUBOT_HEROKU_KEEPALIVE_INTERVAL
else
5
unless keepaliveUrl?
robot.logger.error "hubot-heroku-alive included, but missing HUBOT_HEROKU_KEEPALIVE_URL. `heroku config:set HUBOT_HEROKU_KEEPALIVE_URL=$(heroku apps:info -s | grep web-url | cut -d= -f2)`"
return
# check for legacy heroku keepalive from robot.coffee, and remove it
if robot.pingIntervalId
clearInterval(robot.pingIntervalId)
if keepaliveInterval > 0.0
robot.herokuKeepaliveIntervalId = setInterval =>
robot.logger.info 'keepalive ping'
now = new Date()
elapsedMinutes = (60 * (now.getHours() + 24) + now.getMinutes() - wakeUpOffset) % (60 * 24)
if elapsedMinutes < awakeMinutes
client = robot.http("#{keepaliveUrl}heroku/keepalive")
if process.env.EXPRESS_USER && process.env.EXPRESS_PASSWORD
client.auth(process.env.EXPRESS_USER, process.env.EXPRESS_PASSWORD)
client.post() (err, res, body) =>
if err?
robot.logger.info "keepalive pong: #{err}"
robot.emit 'error', err
else
robot.logger.info "keepalive pong: #{res.statusCode} #{body}"
else
robot.logger.info "Skipping keep alive, time to rest"
, keepaliveInterval * 60 * 1000
else
robot.logger.info "hubot-heroku-keepalive is #{keepaliveInterval}, so not keeping alive"
keepaliveCallback = (req, res) ->
res.set 'Content-Type', 'text/plain'
res.send 'OK'
# keep this different from the legacy URL in httpd.coffee
robot.router.post "/heroku/keepalive", keepaliveCallback
robot.router.get "/heroku/keepalive", keepaliveCallback
|
[
{
"context": "$childHead\n\t\tscope.$apply ->\n\t\t\tscope.players = ['Jacob Buysse','Blake Adams','Ben Dixon','Greg Smith','Ezra McN",
"end": 1093,
"score": 0.9998700022697449,
"start": 1081,
"tag": "NAME",
"value": "Jacob Buysse"
},
{
"context": "ope.$apply ->\n\t\t\tscope.players = ['Jacob Buysse','Blake Adams','Ben Dixon','Greg Smith','Ezra McNichols','Anne ",
"end": 1107,
"score": 0.9998666644096375,
"start": 1096,
"tag": "NAME",
"value": "Blake Adams"
},
{
"context": "\t\t\tscope.players = ['Jacob Buysse','Blake Adams','Ben Dixon','Greg Smith','Ezra McNichols','Anne Sechtig'].ma",
"end": 1119,
"score": 0.9998663067817688,
"start": 1110,
"tag": "NAME",
"value": "Ben Dixon"
},
{
"context": "yers = ['Jacob Buysse','Blake Adams','Ben Dixon','Greg Smith','Ezra McNichols','Anne Sechtig'].map (name) -> {",
"end": 1132,
"score": 0.999865710735321,
"start": 1122,
"tag": "NAME",
"value": "Greg Smith"
},
{
"context": "b Buysse','Blake Adams','Ben Dixon','Greg Smith','Ezra McNichols','Anne Sechtig'].map (name) -> {name}\n\nwindow._ =",
"end": 1149,
"score": 0.9998757839202881,
"start": 1135,
"tag": "NAME",
"value": "Ezra McNichols"
},
{
"context": "Adams','Ben Dixon','Greg Smith','Ezra McNichols','Anne Sechtig'].map (name) -> {name}\n\nwindow._ = _\n\ndocument.ad",
"end": 1164,
"score": 0.9998868703842163,
"start": 1152,
"tag": "NAME",
"value": "Anne Sechtig"
}
] | src/scripts/index.coffee | smrq/sheepshead-mobile | 0 | angular = require 'angular'
attachFastclick = require 'fastclick'
_ = require 'underscore'
require 'angular-animate'
require 'angular-bootstrap'
require 'angular-route'
require './underscoreExt'
unless inBrowser
attachFastclick document.body
m = angular.module 'app', ['ngRoute', 'ngAnimate', 'ui.bootstrap'],
($routeProvider, $httpProvider) ->
require('./setupRoutes')($routeProvider)
# require('./setupHttpProvider')($httpProvider)
require('./controllers/mainCtrl')(m)
require('./controllers/selectPlayersCtrl')(m)
require('./controllers/scoreListCtrl')(m)
require('./controllers/scoreHandCtrl')(m)
require('./controllers/scoresSubmittedCtrl')(m)
require('./services/scoreKeeperService')(m)
require('./services/screenService')(m)
require('./services/webService')(m)
window.testData =
setup: ->
localStorage.setItem 'scoreKeeperService', require('fs').readFileSync('test.json')
teardown: ->
localStorage.removeItem 'scoreKeeperService'
selectPlayers: ->
scope = angular.element(document).scope().$$childHead.$$childHead
scope.$apply ->
scope.players = ['Jacob Buysse','Blake Adams','Ben Dixon','Greg Smith','Ezra McNichols','Anne Sechtig'].map (name) -> {name}
window._ = _
document.addEventListener "deviceready", ->
angular.bootstrap document, ['app'] | 10246 | angular = require 'angular'
attachFastclick = require 'fastclick'
_ = require 'underscore'
require 'angular-animate'
require 'angular-bootstrap'
require 'angular-route'
require './underscoreExt'
unless inBrowser
attachFastclick document.body
m = angular.module 'app', ['ngRoute', 'ngAnimate', 'ui.bootstrap'],
($routeProvider, $httpProvider) ->
require('./setupRoutes')($routeProvider)
# require('./setupHttpProvider')($httpProvider)
require('./controllers/mainCtrl')(m)
require('./controllers/selectPlayersCtrl')(m)
require('./controllers/scoreListCtrl')(m)
require('./controllers/scoreHandCtrl')(m)
require('./controllers/scoresSubmittedCtrl')(m)
require('./services/scoreKeeperService')(m)
require('./services/screenService')(m)
require('./services/webService')(m)
window.testData =
setup: ->
localStorage.setItem 'scoreKeeperService', require('fs').readFileSync('test.json')
teardown: ->
localStorage.removeItem 'scoreKeeperService'
selectPlayers: ->
scope = angular.element(document).scope().$$childHead.$$childHead
scope.$apply ->
scope.players = ['<NAME>','<NAME>','<NAME>','<NAME>','<NAME>','<NAME>'].map (name) -> {name}
window._ = _
document.addEventListener "deviceready", ->
angular.bootstrap document, ['app'] | true | angular = require 'angular'
attachFastclick = require 'fastclick'
_ = require 'underscore'
require 'angular-animate'
require 'angular-bootstrap'
require 'angular-route'
require './underscoreExt'
unless inBrowser
attachFastclick document.body
m = angular.module 'app', ['ngRoute', 'ngAnimate', 'ui.bootstrap'],
($routeProvider, $httpProvider) ->
require('./setupRoutes')($routeProvider)
# require('./setupHttpProvider')($httpProvider)
require('./controllers/mainCtrl')(m)
require('./controllers/selectPlayersCtrl')(m)
require('./controllers/scoreListCtrl')(m)
require('./controllers/scoreHandCtrl')(m)
require('./controllers/scoresSubmittedCtrl')(m)
require('./services/scoreKeeperService')(m)
require('./services/screenService')(m)
require('./services/webService')(m)
window.testData =
setup: ->
localStorage.setItem 'scoreKeeperService', require('fs').readFileSync('test.json')
teardown: ->
localStorage.removeItem 'scoreKeeperService'
selectPlayers: ->
scope = angular.element(document).scope().$$childHead.$$childHead
scope.$apply ->
scope.players = ['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','PI:NAME:<NAME>END_PI'].map (name) -> {name}
window._ = _
document.addEventListener "deviceready", ->
angular.bootstrap document, ['app'] |
[
{
"context": "rt', ->\n sampleData1 = [\n key: 'Series 1'\n values: [\n [-1,-1]\n ",
"end": 110,
"score": 0.8862261772155762,
"start": 102,
"tag": "KEY",
"value": "Series 1"
}
] | public/admin/assets/plugins/nvd3/test/mocha/historical-bar.coffee | enuenan/enan | 4,529 | describe 'NVD3', ->
describe 'Historical Bar Chart', ->
sampleData1 = [
key: 'Series 1'
values: [
[-1,-1]
[0,0]
[1,1]
[2,2]
]
]
options =
x: (d,i)-> i
y: (d)-> d[1]
margin:
top: 30
right: 20
bottom: 50
left: 75
width: 200
height: 200
color: nv.utils.defaultColor()
showLegend: true
showXAxis: true
showYAxis: true
rightAlignYAxis: false
noData: 'No Data Available'
builder = null
beforeEach ->
builder = new ChartBuilder nv.models.historicalBarChart()
builder.build options, sampleData1
afterEach ->
builder.teardown()
it 'api check', ->
should.exist builder.model.options, 'options exposed'
for opt of options
should.exist builder.model[opt](), "#{opt} can be called"
it 'renders', ->
wrap = builder.$ 'g.nvd3.nv-historicalBarChart'
should.exist wrap[0]
it 'clears chart objects for no data', ->
builder = new ChartBuilder nv.models.historicalBarChart()
builder.buildover options, sampleData1, []
groups = builder.$ 'g'
groups.length.should.equal 0, 'removes chart components'
it 'has correct structure', ->
cssClasses = [
'.nv-x.nv-axis'
'.nv-y.nv-axis'
'.nv-barsWrap'
'.nv-bars'
'.nv-legendWrap'
]
for cssClass in cssClasses
do (cssClass) ->
should.exist builder.$("g.nvd3.nv-historicalBarChart #{cssClass}")[0]
it 'can override axis ticks', ->
builder.model.xAxis.ticks(34)
builder.model.yAxis.ticks(56)
builder.model.update()
builder.model.xAxis.ticks().should.equal 34
builder.model.yAxis.ticks().should.equal 56
| 176790 | describe 'NVD3', ->
describe 'Historical Bar Chart', ->
sampleData1 = [
key: '<KEY>'
values: [
[-1,-1]
[0,0]
[1,1]
[2,2]
]
]
options =
x: (d,i)-> i
y: (d)-> d[1]
margin:
top: 30
right: 20
bottom: 50
left: 75
width: 200
height: 200
color: nv.utils.defaultColor()
showLegend: true
showXAxis: true
showYAxis: true
rightAlignYAxis: false
noData: 'No Data Available'
builder = null
beforeEach ->
builder = new ChartBuilder nv.models.historicalBarChart()
builder.build options, sampleData1
afterEach ->
builder.teardown()
it 'api check', ->
should.exist builder.model.options, 'options exposed'
for opt of options
should.exist builder.model[opt](), "#{opt} can be called"
it 'renders', ->
wrap = builder.$ 'g.nvd3.nv-historicalBarChart'
should.exist wrap[0]
it 'clears chart objects for no data', ->
builder = new ChartBuilder nv.models.historicalBarChart()
builder.buildover options, sampleData1, []
groups = builder.$ 'g'
groups.length.should.equal 0, 'removes chart components'
it 'has correct structure', ->
cssClasses = [
'.nv-x.nv-axis'
'.nv-y.nv-axis'
'.nv-barsWrap'
'.nv-bars'
'.nv-legendWrap'
]
for cssClass in cssClasses
do (cssClass) ->
should.exist builder.$("g.nvd3.nv-historicalBarChart #{cssClass}")[0]
it 'can override axis ticks', ->
builder.model.xAxis.ticks(34)
builder.model.yAxis.ticks(56)
builder.model.update()
builder.model.xAxis.ticks().should.equal 34
builder.model.yAxis.ticks().should.equal 56
| true | describe 'NVD3', ->
describe 'Historical Bar Chart', ->
sampleData1 = [
key: 'PI:KEY:<KEY>END_PI'
values: [
[-1,-1]
[0,0]
[1,1]
[2,2]
]
]
options =
x: (d,i)-> i
y: (d)-> d[1]
margin:
top: 30
right: 20
bottom: 50
left: 75
width: 200
height: 200
color: nv.utils.defaultColor()
showLegend: true
showXAxis: true
showYAxis: true
rightAlignYAxis: false
noData: 'No Data Available'
builder = null
beforeEach ->
builder = new ChartBuilder nv.models.historicalBarChart()
builder.build options, sampleData1
afterEach ->
builder.teardown()
it 'api check', ->
should.exist builder.model.options, 'options exposed'
for opt of options
should.exist builder.model[opt](), "#{opt} can be called"
it 'renders', ->
wrap = builder.$ 'g.nvd3.nv-historicalBarChart'
should.exist wrap[0]
it 'clears chart objects for no data', ->
builder = new ChartBuilder nv.models.historicalBarChart()
builder.buildover options, sampleData1, []
groups = builder.$ 'g'
groups.length.should.equal 0, 'removes chart components'
it 'has correct structure', ->
cssClasses = [
'.nv-x.nv-axis'
'.nv-y.nv-axis'
'.nv-barsWrap'
'.nv-bars'
'.nv-legendWrap'
]
for cssClass in cssClasses
do (cssClass) ->
should.exist builder.$("g.nvd3.nv-historicalBarChart #{cssClass}")[0]
it 'can override axis ticks', ->
builder.model.xAxis.ticks(34)
builder.model.yAxis.ticks(56)
builder.model.update()
builder.model.xAxis.ticks().should.equal 34
builder.model.yAxis.ticks().should.equal 56
|
[
{
"context": "lize: () ->\n\t\t\t\tsuper\n\t\t\t\t@setItem {id: 1, name: 'John Doe'}\n\n\t\tuser = new class UserStore extends EntitySto",
"end": 850,
"score": 0.9997804164886475,
"start": 842,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "ize: () ->\n\t\t\t\tsuper\n\t\t\t\t@setItem {id: 1, email: \"johndoe@mail.com\"}\n\n\t\texpect UserStore._references?.articles\n\t\t.to",
"end": 1939,
"score": 0.999929666519165,
"start": 1923,
"tag": "EMAIL",
"value": "johndoe@mail.com"
},
{
"context": "lize: () ->\n\t\t\t\tsuper\n\t\t\t\t@setItem {id: 1, name: \"John Doe\"}\n\n\n\t\texpect UserStore._references?.profile\n\t\t.to",
"end": 3279,
"score": 0.9997988939285278,
"start": 3271,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "lize: () ->\n\t\t\t\tsuper\n\t\t\t\t@setItem {id: 1, name: \"John Doe\"}\n\n\t\tchanged = sinon.spy()\n\t\tuser.changed.add cha",
"end": 5065,
"score": 0.9997039437294006,
"start": 5057,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "lize: () ->\n\t\t\t\tsuper\n\t\t\t\t@setItem {id: 1, name: 'John Doe'}\n\n\t\tuser = new class UserStore extends EntitySto",
"end": 5796,
"score": 0.9998306035995483,
"start": 5788,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "lize: () ->\n\t\t\t\tsuper\n\t\t\t\t@setItem {id: 1, name: 'John Doe'}\n\n\t\tuser = new class UserStore extends EntitySto",
"end": 6207,
"score": 0.9998303651809692,
"start": 6199,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "lize: () ->\n\t\t\t\tsuper\n\t\t\t\t@setItem {id: 1, name: \"John Doe\"}\n\n\t\texpect Immutable.List.isList user.getItem(1)",
"end": 6986,
"score": 0.999815046787262,
"start": 6978,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "lize: () ->\n\t\t\t\tsuper\n\t\t\t\t@setItem {id: 1, name: 'John Doe'}\n\n\t\tarticle = new class ArticleStore extends Ent",
"end": 7397,
"score": 0.9998116493225098,
"start": 7389,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "lize: () ->\n\t\t\t\tsuper\n\t\t\t\t@setItem {id: 1, name: 'John Doe'}\n\n\t\tarticle = new class ArticleStore extends Ent",
"end": 8794,
"score": 0.9996667504310608,
"start": 8786,
"tag": "NAME",
"value": "John Doe"
},
{
"context": ">\n\t\t\t\tsuper\n\t\t\t\t@setItem {\n\t\t\t\t\tid: 1\n\t\t\t\t\tname: 'Test User'\n\t\t\t\t}\n\n\t\t\texpect () => @hasMany('articles')",
"end": 10999,
"score": 0.7527444958686829,
"start": 10995,
"tag": "NAME",
"value": "Test"
},
{
"context": "\t\tsuper\n\t\t\t\t@setItem {\n\t\t\t\t\tid: 1\n\t\t\t\t\tname: 'Test User'\n\t\t\t\t}\n\n\t\t\texpect () => @hasMany('articles').thro",
"end": 11004,
"score": 0.8370969891548157,
"start": 11000,
"tag": "USERNAME",
"value": "User"
},
{
"context": ">\n\t\t\t\tsuper\n\t\t\t\t@setItem {\n\t\t\t\t\tid: 1\n\t\t\t\t\tname: \"Test User\"\n\t\t\t\t}\n\n\t\t\texpect () => @hasMany('articles',",
"end": 12088,
"score": 0.7044702172279358,
"start": 12084,
"tag": "NAME",
"value": "Test"
},
{
"context": "\t\tsuper\n\t\t\t\t@setItem {\n\t\t\t\t\tid: 1\n\t\t\t\t\tname: \"Test User\"\n\t\t\t\t}\n\n\t\t\texpect () => @hasMany('articles', rand",
"end": 12093,
"score": 0.83684903383255,
"start": 12089,
"tag": "USERNAME",
"value": "User"
}
] | test/integration/entity-store.coffee | miklschmidt/capacitor.js | 9 | EntityStore = require '../../src/entity-store'
IndexedListStore = require '../../src/indexed-list-store'
ListStore = require '../../src/list-store'
IndexedSetStore = require '../../src/indexed-set-store'
SetStore = require '../../src/set-store'
Store = require '../../src/store'
ActionCreator = require '../../src/action-creator'
actionManager = require '../../src/action-manager'
invariant = require '../../src/invariant'
InvariantError = require '../../src/invariant-error'
{expect} = require 'chai'
Immutable = require 'immutable'
sinon = require 'sinon'
describe 'EntityStore', () ->
it 'should be able to define a one to one relationship', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, name: 'John Doe'}
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
expect UserStore._references?.profile
.to.exist
expect UserStore._references.profile.type
.to.equal 'entity'
expect UserStore._references.profile.store
.to.be.equal profile
it 'should throw when trying to define a one to one relationship without an EntityStore', () ->
profile = new class ProfileStore extends Store
user = new class UserStore extends EntityStore
expect () => @hasOne 'profile', profile
.to.throw InvariantError
it 'should be able to define a many to many relationship through an indexed list store', () ->
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'Test Article'}
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
@add 1, 1
user = new class UserStore extends EntityStore
@hasMany('articles').through(usersArticles)
initialize: () ->
super
@setItem {id: 1, email: "johndoe@mail.com"}
expect UserStore._references?.articles
.to.exist
expect UserStore._references.articles.type
.to.equal 'indexed-collection'
expect UserStore._references.articles.store
.to.be.equal usersArticles
it 'should throw when trying to define a many to many relationship without an IndexedListStore', () ->
article = new class ArticleStore extends EntityStore
randomArticles = new class ArticleListStore extends ListStore
containsEntity: article
user = new class UserStore extends EntityStore
expect () => @hasMany('articles').through(randomArticles)
.to.throw InvariantError
it 'should be able to define several relationships', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, value: 'test'}
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'test article'}
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
@add 1, 1
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
@hasOne 'profile2', profile
@hasMany('articles').through(usersArticles)
@hasMany('articles2').through(usersArticles)
initialize: () ->
super
@setItem {id: 1, name: "John Doe"}
expect UserStore._references?.profile
.to.exist
expect UserStore._references.profile.type
.to.equal 'entity'
expect UserStore._references.profile.store
.to.be.equal profile
expect UserStore._references?.profile2
.to.exist
expect UserStore._references.profile2.type
.to.equal 'entity'
expect UserStore._references.profile2.store
.to.be.equal profile
expect UserStore._references?.articles
.to.exist
expect UserStore._references.articles.type
.to.equal 'indexed-collection'
expect UserStore._references.articles.store
.to.be.equal usersArticles
expect UserStore._references?.articles2
.to.exist
expect UserStore._references.articles2.type
.to.equal 'indexed-collection'
expect UserStore._references.articles2.store
.to.be.equal usersArticles
it 'should change when relationships change', () ->
action = actionManager.create 'entity-store-relationship-change-test-action'
profile = new class ProfileStore extends EntityStore
@action action, () ->
@changed()
initialize: () ->
super
@setItem {id: 1, value: 'test'}
getInterface: () ->
obj = super
obj.dispatch = @changed.dispatch
obj
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'test article'}
usersArticles = new class UserArticleStore extends IndexedListStore
@action action, () ->
@changed()
containsEntity: article
initialize: () ->
super
@add 1, 1
getInterface: () ->
obj = super
obj.dispatch = @changed.dispatch
obj
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
@hasMany('articles').through(usersArticles)
initialize: () ->
super
@setItem {id: 1, name: "John Doe"}
changed = sinon.spy()
user.changed.add changed, user
profile.dispatch()
usersArticles.dispatch()
expect changed.callCount
.to.equal 2
changedViaAction = sinon.spy()
user.changed.add changedViaAction, user
creator = new class TestActionCreator extends ActionCreator
creator.dispatch action
# Batched change events so only 1 change event should be dispatched.
# Even though both the profile and the usersArticles are changed.
expect changedViaAction.callCount
.to.equal 1
it 'should return null when the property value for a one to one relationship is undefined', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, name: 'John Doe'}
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
initialize: () ->
super
@setItem {id: 1} # No profile
expect user.getItem(1).get('profile'), 'profile'
.to.be.null
it 'should be able to dereference a one to one relationship', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, name: 'John Doe'}
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
initialize: () ->
super
@setItem {id: 1, profile: 1}
expect user.getItem(1).get 'profile'
.to.be.equal profile.getItem(1)
it 'should be able to dereference a many to many relationship', () ->
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'test article'}
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
# User with id 1 has article with id 1
@add 1, 1
user = new class UserStore extends EntityStore
@hasMany('articles').through(usersArticles)
initialize: () ->
super
@setItem {id: 1, name: "John Doe"}
expect Immutable.List.isList user.getItem(1).get('articles')
.to.be.true
expect user.getItem(1).get('articles').get(0) # First entry in the list
.to.be.equal article.getItem(1)
it 'should return the same immutable for a dereferenced item if the item did not change', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, name: 'John Doe'}
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'test article'}
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
# User with id 1 has article with id 1
@add 1, 1
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
@hasMany('articles').through(usersArticles)
initialize: () ->
super
@setItem {id: 1, profile: 1, articles: 1}
first = user.getItem(1)
second = user.getItem(1)
expect first
.to.be.equal second
it 'should not attempt to dereference items that do not exist', () ->
article = new class ArticleStore extends EntityStore
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
@add 1, 1
profile = new class ProfileStore extends EntityStore
@hasMany('articles').through(usersArticles)
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
initialize: () ->
super
@setItem {id: 1, profile: 1, articles: 1}
expect user.getItem(1).get('profile')
.to.not.exist
it 'should not dereference when using Raw methods', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, name: 'John Doe'}
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'test article'}
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
# User with id 1 has article with id 1
@add 1, 1
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
@hasMany('articles').through(usersArticles)
dereference: sinon.spy()
initialize: () ->
super
@setItem {id: 1, profile: 1, articles: 1}
item = @getRawItem(1)
expect item
.to.exist
expect item.get('profile')
.to.equal 1
expect item.get('articles')
.to.equal 1
expect item.getIn ['profile', 'name']
.to.equal undefined
expect item.getIn ['articles', 0, 'title']
.to.equal undefined
expect @dereference.called
.to.equal false
list = @getRawItemsWithIds([1])
expect list
.to.exist
expect list.get(0)
.to.exist
expect list.get(0).get('profile')
.to.equal 1
expect list.get(0).get('articles')
.to.equal 1
expect list.get(0).getIn ['profile', 'name']
.to.equal undefined
expect list.get(0).getIn ['articles', 0, 'title']
.to.equal undefined
expect @dereference.called
.to.equal false
it 'should be able to define a many to many relationship with an IndexedListStore', () ->
article = new class ArticleStore extends EntityStore
randomArticles = new class ArticleListStore extends IndexedListStore
containsEntity: article
user = new class UserStore extends EntityStore
expect () => @hasMany('articles').through(randomArticles)
.to.not.throw Error
it 'should be able to define a many to many relationship with an IndexedSetStore', () ->
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {
id: 1
title: 'test'
}
randomArticles = new class ArticleListStore extends IndexedSetStore
containsEntity: article
initialize: () ->
super
@add 1, 1
user = new class UserStore extends EntityStore
initialize: () ->
super
@setItem {
id: 1
name: 'Test User'
}
expect () => @hasMany('articles').through(randomArticles)
.to.not.throw Error
expect user.getItem(1).get('articles').get(0).get('id')
.to.equal 1
expect user.getItem(1).get('articles').get(0).get('title')
.to.equal 'test'
it 'should be able to define a one to many relationship with a ListStore', () ->
article = new class ArticleStore extends EntityStore
randomArticles = new class ArticleListStore extends ListStore
containsEntity: article
test = new class TestStore extends EntityStore
expect () => @hasMany('articles', randomArticles)
.to.not.throw Error
it 'should be able to define a one to many relationship with a SetStore', () ->
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {
id: 1
title: 'test'
}
randomArticles = new class ArticleListStore extends SetStore
containsEntity: article
initialize: () ->
super
@add 1
user = new class UserStore extends EntityStore
initialize: () ->
super
@setItem {
id: 1
name: "Test User"
}
expect () => @hasMany('articles', randomArticles)
.to.not.throw Error
expect user.getItem(1).get('articles').get(0).get('id')
.to.equal 1
expect user.getItem(1).get('articles').get(0).get('title')
.to.equal 'test'
| 19758 | EntityStore = require '../../src/entity-store'
IndexedListStore = require '../../src/indexed-list-store'
ListStore = require '../../src/list-store'
IndexedSetStore = require '../../src/indexed-set-store'
SetStore = require '../../src/set-store'
Store = require '../../src/store'
ActionCreator = require '../../src/action-creator'
actionManager = require '../../src/action-manager'
invariant = require '../../src/invariant'
InvariantError = require '../../src/invariant-error'
{expect} = require 'chai'
Immutable = require 'immutable'
sinon = require 'sinon'
describe 'EntityStore', () ->
it 'should be able to define a one to one relationship', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, name: '<NAME>'}
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
expect UserStore._references?.profile
.to.exist
expect UserStore._references.profile.type
.to.equal 'entity'
expect UserStore._references.profile.store
.to.be.equal profile
it 'should throw when trying to define a one to one relationship without an EntityStore', () ->
profile = new class ProfileStore extends Store
user = new class UserStore extends EntityStore
expect () => @hasOne 'profile', profile
.to.throw InvariantError
it 'should be able to define a many to many relationship through an indexed list store', () ->
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'Test Article'}
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
@add 1, 1
user = new class UserStore extends EntityStore
@hasMany('articles').through(usersArticles)
initialize: () ->
super
@setItem {id: 1, email: "<EMAIL>"}
expect UserStore._references?.articles
.to.exist
expect UserStore._references.articles.type
.to.equal 'indexed-collection'
expect UserStore._references.articles.store
.to.be.equal usersArticles
it 'should throw when trying to define a many to many relationship without an IndexedListStore', () ->
article = new class ArticleStore extends EntityStore
randomArticles = new class ArticleListStore extends ListStore
containsEntity: article
user = new class UserStore extends EntityStore
expect () => @hasMany('articles').through(randomArticles)
.to.throw InvariantError
it 'should be able to define several relationships', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, value: 'test'}
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'test article'}
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
@add 1, 1
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
@hasOne 'profile2', profile
@hasMany('articles').through(usersArticles)
@hasMany('articles2').through(usersArticles)
initialize: () ->
super
@setItem {id: 1, name: "<NAME>"}
expect UserStore._references?.profile
.to.exist
expect UserStore._references.profile.type
.to.equal 'entity'
expect UserStore._references.profile.store
.to.be.equal profile
expect UserStore._references?.profile2
.to.exist
expect UserStore._references.profile2.type
.to.equal 'entity'
expect UserStore._references.profile2.store
.to.be.equal profile
expect UserStore._references?.articles
.to.exist
expect UserStore._references.articles.type
.to.equal 'indexed-collection'
expect UserStore._references.articles.store
.to.be.equal usersArticles
expect UserStore._references?.articles2
.to.exist
expect UserStore._references.articles2.type
.to.equal 'indexed-collection'
expect UserStore._references.articles2.store
.to.be.equal usersArticles
it 'should change when relationships change', () ->
action = actionManager.create 'entity-store-relationship-change-test-action'
profile = new class ProfileStore extends EntityStore
@action action, () ->
@changed()
initialize: () ->
super
@setItem {id: 1, value: 'test'}
getInterface: () ->
obj = super
obj.dispatch = @changed.dispatch
obj
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'test article'}
usersArticles = new class UserArticleStore extends IndexedListStore
@action action, () ->
@changed()
containsEntity: article
initialize: () ->
super
@add 1, 1
getInterface: () ->
obj = super
obj.dispatch = @changed.dispatch
obj
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
@hasMany('articles').through(usersArticles)
initialize: () ->
super
@setItem {id: 1, name: "<NAME>"}
changed = sinon.spy()
user.changed.add changed, user
profile.dispatch()
usersArticles.dispatch()
expect changed.callCount
.to.equal 2
changedViaAction = sinon.spy()
user.changed.add changedViaAction, user
creator = new class TestActionCreator extends ActionCreator
creator.dispatch action
# Batched change events so only 1 change event should be dispatched.
# Even though both the profile and the usersArticles are changed.
expect changedViaAction.callCount
.to.equal 1
it 'should return null when the property value for a one to one relationship is undefined', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, name: '<NAME>'}
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
initialize: () ->
super
@setItem {id: 1} # No profile
expect user.getItem(1).get('profile'), 'profile'
.to.be.null
it 'should be able to dereference a one to one relationship', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, name: '<NAME>'}
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
initialize: () ->
super
@setItem {id: 1, profile: 1}
expect user.getItem(1).get 'profile'
.to.be.equal profile.getItem(1)
it 'should be able to dereference a many to many relationship', () ->
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'test article'}
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
# User with id 1 has article with id 1
@add 1, 1
user = new class UserStore extends EntityStore
@hasMany('articles').through(usersArticles)
initialize: () ->
super
@setItem {id: 1, name: "<NAME>"}
expect Immutable.List.isList user.getItem(1).get('articles')
.to.be.true
expect user.getItem(1).get('articles').get(0) # First entry in the list
.to.be.equal article.getItem(1)
it 'should return the same immutable for a dereferenced item if the item did not change', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, name: '<NAME>'}
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'test article'}
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
# User with id 1 has article with id 1
@add 1, 1
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
@hasMany('articles').through(usersArticles)
initialize: () ->
super
@setItem {id: 1, profile: 1, articles: 1}
first = user.getItem(1)
second = user.getItem(1)
expect first
.to.be.equal second
it 'should not attempt to dereference items that do not exist', () ->
article = new class ArticleStore extends EntityStore
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
@add 1, 1
profile = new class ProfileStore extends EntityStore
@hasMany('articles').through(usersArticles)
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
initialize: () ->
super
@setItem {id: 1, profile: 1, articles: 1}
expect user.getItem(1).get('profile')
.to.not.exist
it 'should not dereference when using Raw methods', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, name: '<NAME>'}
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'test article'}
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
# User with id 1 has article with id 1
@add 1, 1
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
@hasMany('articles').through(usersArticles)
dereference: sinon.spy()
initialize: () ->
super
@setItem {id: 1, profile: 1, articles: 1}
item = @getRawItem(1)
expect item
.to.exist
expect item.get('profile')
.to.equal 1
expect item.get('articles')
.to.equal 1
expect item.getIn ['profile', 'name']
.to.equal undefined
expect item.getIn ['articles', 0, 'title']
.to.equal undefined
expect @dereference.called
.to.equal false
list = @getRawItemsWithIds([1])
expect list
.to.exist
expect list.get(0)
.to.exist
expect list.get(0).get('profile')
.to.equal 1
expect list.get(0).get('articles')
.to.equal 1
expect list.get(0).getIn ['profile', 'name']
.to.equal undefined
expect list.get(0).getIn ['articles', 0, 'title']
.to.equal undefined
expect @dereference.called
.to.equal false
it 'should be able to define a many to many relationship with an IndexedListStore', () ->
article = new class ArticleStore extends EntityStore
randomArticles = new class ArticleListStore extends IndexedListStore
containsEntity: article
user = new class UserStore extends EntityStore
expect () => @hasMany('articles').through(randomArticles)
.to.not.throw Error
it 'should be able to define a many to many relationship with an IndexedSetStore', () ->
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {
id: 1
title: 'test'
}
randomArticles = new class ArticleListStore extends IndexedSetStore
containsEntity: article
initialize: () ->
super
@add 1, 1
user = new class UserStore extends EntityStore
initialize: () ->
super
@setItem {
id: 1
name: '<NAME> User'
}
expect () => @hasMany('articles').through(randomArticles)
.to.not.throw Error
expect user.getItem(1).get('articles').get(0).get('id')
.to.equal 1
expect user.getItem(1).get('articles').get(0).get('title')
.to.equal 'test'
it 'should be able to define a one to many relationship with a ListStore', () ->
article = new class ArticleStore extends EntityStore
randomArticles = new class ArticleListStore extends ListStore
containsEntity: article
test = new class TestStore extends EntityStore
expect () => @hasMany('articles', randomArticles)
.to.not.throw Error
it 'should be able to define a one to many relationship with a SetStore', () ->
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {
id: 1
title: 'test'
}
randomArticles = new class ArticleListStore extends SetStore
containsEntity: article
initialize: () ->
super
@add 1
user = new class UserStore extends EntityStore
initialize: () ->
super
@setItem {
id: 1
name: "<NAME> User"
}
expect () => @hasMany('articles', randomArticles)
.to.not.throw Error
expect user.getItem(1).get('articles').get(0).get('id')
.to.equal 1
expect user.getItem(1).get('articles').get(0).get('title')
.to.equal 'test'
| true | EntityStore = require '../../src/entity-store'
IndexedListStore = require '../../src/indexed-list-store'
ListStore = require '../../src/list-store'
IndexedSetStore = require '../../src/indexed-set-store'
SetStore = require '../../src/set-store'
Store = require '../../src/store'
ActionCreator = require '../../src/action-creator'
actionManager = require '../../src/action-manager'
invariant = require '../../src/invariant'
InvariantError = require '../../src/invariant-error'
{expect} = require 'chai'
Immutable = require 'immutable'
sinon = require 'sinon'
describe 'EntityStore', () ->
it 'should be able to define a one to one relationship', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, name: 'PI:NAME:<NAME>END_PI'}
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
expect UserStore._references?.profile
.to.exist
expect UserStore._references.profile.type
.to.equal 'entity'
expect UserStore._references.profile.store
.to.be.equal profile
it 'should throw when trying to define a one to one relationship without an EntityStore', () ->
profile = new class ProfileStore extends Store
user = new class UserStore extends EntityStore
expect () => @hasOne 'profile', profile
.to.throw InvariantError
it 'should be able to define a many to many relationship through an indexed list store', () ->
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'Test Article'}
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
@add 1, 1
user = new class UserStore extends EntityStore
@hasMany('articles').through(usersArticles)
initialize: () ->
super
@setItem {id: 1, email: "PI:EMAIL:<EMAIL>END_PI"}
expect UserStore._references?.articles
.to.exist
expect UserStore._references.articles.type
.to.equal 'indexed-collection'
expect UserStore._references.articles.store
.to.be.equal usersArticles
it 'should throw when trying to define a many to many relationship without an IndexedListStore', () ->
article = new class ArticleStore extends EntityStore
randomArticles = new class ArticleListStore extends ListStore
containsEntity: article
user = new class UserStore extends EntityStore
expect () => @hasMany('articles').through(randomArticles)
.to.throw InvariantError
it 'should be able to define several relationships', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, value: 'test'}
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'test article'}
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
@add 1, 1
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
@hasOne 'profile2', profile
@hasMany('articles').through(usersArticles)
@hasMany('articles2').through(usersArticles)
initialize: () ->
super
@setItem {id: 1, name: "PI:NAME:<NAME>END_PI"}
expect UserStore._references?.profile
.to.exist
expect UserStore._references.profile.type
.to.equal 'entity'
expect UserStore._references.profile.store
.to.be.equal profile
expect UserStore._references?.profile2
.to.exist
expect UserStore._references.profile2.type
.to.equal 'entity'
expect UserStore._references.profile2.store
.to.be.equal profile
expect UserStore._references?.articles
.to.exist
expect UserStore._references.articles.type
.to.equal 'indexed-collection'
expect UserStore._references.articles.store
.to.be.equal usersArticles
expect UserStore._references?.articles2
.to.exist
expect UserStore._references.articles2.type
.to.equal 'indexed-collection'
expect UserStore._references.articles2.store
.to.be.equal usersArticles
it 'should change when relationships change', () ->
action = actionManager.create 'entity-store-relationship-change-test-action'
profile = new class ProfileStore extends EntityStore
@action action, () ->
@changed()
initialize: () ->
super
@setItem {id: 1, value: 'test'}
getInterface: () ->
obj = super
obj.dispatch = @changed.dispatch
obj
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'test article'}
usersArticles = new class UserArticleStore extends IndexedListStore
@action action, () ->
@changed()
containsEntity: article
initialize: () ->
super
@add 1, 1
getInterface: () ->
obj = super
obj.dispatch = @changed.dispatch
obj
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
@hasMany('articles').through(usersArticles)
initialize: () ->
super
@setItem {id: 1, name: "PI:NAME:<NAME>END_PI"}
changed = sinon.spy()
user.changed.add changed, user
profile.dispatch()
usersArticles.dispatch()
expect changed.callCount
.to.equal 2
changedViaAction = sinon.spy()
user.changed.add changedViaAction, user
creator = new class TestActionCreator extends ActionCreator
creator.dispatch action
# Batched change events so only 1 change event should be dispatched.
# Even though both the profile and the usersArticles are changed.
expect changedViaAction.callCount
.to.equal 1
it 'should return null when the property value for a one to one relationship is undefined', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, name: 'PI:NAME:<NAME>END_PI'}
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
initialize: () ->
super
@setItem {id: 1} # No profile
expect user.getItem(1).get('profile'), 'profile'
.to.be.null
it 'should be able to dereference a one to one relationship', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, name: 'PI:NAME:<NAME>END_PI'}
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
initialize: () ->
super
@setItem {id: 1, profile: 1}
expect user.getItem(1).get 'profile'
.to.be.equal profile.getItem(1)
it 'should be able to dereference a many to many relationship', () ->
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'test article'}
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
# User with id 1 has article with id 1
@add 1, 1
user = new class UserStore extends EntityStore
@hasMany('articles').through(usersArticles)
initialize: () ->
super
@setItem {id: 1, name: "PI:NAME:<NAME>END_PI"}
expect Immutable.List.isList user.getItem(1).get('articles')
.to.be.true
expect user.getItem(1).get('articles').get(0) # First entry in the list
.to.be.equal article.getItem(1)
it 'should return the same immutable for a dereferenced item if the item did not change', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, name: 'PI:NAME:<NAME>END_PI'}
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'test article'}
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
# User with id 1 has article with id 1
@add 1, 1
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
@hasMany('articles').through(usersArticles)
initialize: () ->
super
@setItem {id: 1, profile: 1, articles: 1}
first = user.getItem(1)
second = user.getItem(1)
expect first
.to.be.equal second
it 'should not attempt to dereference items that do not exist', () ->
article = new class ArticleStore extends EntityStore
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
@add 1, 1
profile = new class ProfileStore extends EntityStore
@hasMany('articles').through(usersArticles)
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
initialize: () ->
super
@setItem {id: 1, profile: 1, articles: 1}
expect user.getItem(1).get('profile')
.to.not.exist
it 'should not dereference when using Raw methods', () ->
profile = new class ProfileStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, name: 'PI:NAME:<NAME>END_PI'}
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {id: 1, title: 'test article'}
usersArticles = new class UserArticleStore extends IndexedListStore
containsEntity: article
initialize: () ->
super
# User with id 1 has article with id 1
@add 1, 1
user = new class UserStore extends EntityStore
@hasOne 'profile', profile
@hasMany('articles').through(usersArticles)
dereference: sinon.spy()
initialize: () ->
super
@setItem {id: 1, profile: 1, articles: 1}
item = @getRawItem(1)
expect item
.to.exist
expect item.get('profile')
.to.equal 1
expect item.get('articles')
.to.equal 1
expect item.getIn ['profile', 'name']
.to.equal undefined
expect item.getIn ['articles', 0, 'title']
.to.equal undefined
expect @dereference.called
.to.equal false
list = @getRawItemsWithIds([1])
expect list
.to.exist
expect list.get(0)
.to.exist
expect list.get(0).get('profile')
.to.equal 1
expect list.get(0).get('articles')
.to.equal 1
expect list.get(0).getIn ['profile', 'name']
.to.equal undefined
expect list.get(0).getIn ['articles', 0, 'title']
.to.equal undefined
expect @dereference.called
.to.equal false
it 'should be able to define a many to many relationship with an IndexedListStore', () ->
article = new class ArticleStore extends EntityStore
randomArticles = new class ArticleListStore extends IndexedListStore
containsEntity: article
user = new class UserStore extends EntityStore
expect () => @hasMany('articles').through(randomArticles)
.to.not.throw Error
it 'should be able to define a many to many relationship with an IndexedSetStore', () ->
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {
id: 1
title: 'test'
}
randomArticles = new class ArticleListStore extends IndexedSetStore
containsEntity: article
initialize: () ->
super
@add 1, 1
user = new class UserStore extends EntityStore
initialize: () ->
super
@setItem {
id: 1
name: 'PI:NAME:<NAME>END_PI User'
}
expect () => @hasMany('articles').through(randomArticles)
.to.not.throw Error
expect user.getItem(1).get('articles').get(0).get('id')
.to.equal 1
expect user.getItem(1).get('articles').get(0).get('title')
.to.equal 'test'
it 'should be able to define a one to many relationship with a ListStore', () ->
article = new class ArticleStore extends EntityStore
randomArticles = new class ArticleListStore extends ListStore
containsEntity: article
test = new class TestStore extends EntityStore
expect () => @hasMany('articles', randomArticles)
.to.not.throw Error
it 'should be able to define a one to many relationship with a SetStore', () ->
article = new class ArticleStore extends EntityStore
initialize: () ->
super
@setItem {
id: 1
title: 'test'
}
randomArticles = new class ArticleListStore extends SetStore
containsEntity: article
initialize: () ->
super
@add 1
user = new class UserStore extends EntityStore
initialize: () ->
super
@setItem {
id: 1
name: "PI:NAME:<NAME>END_PI User"
}
expect () => @hasMany('articles', randomArticles)
.to.not.throw Error
expect user.getItem(1).get('articles').get(0).get('id')
.to.equal 1
expect user.getItem(1).get('articles').get(0).get('title')
.to.equal 'test'
|
[
{
"context": "\n getRefreshCmd: (all) ->\n key = if all then 'clojure-plus.refreshAllCmd' else 'clojure-plus.refreshCmd'\n atom.config.g",
"end": 3589,
"score": 0.9256846308708191,
"start": 3563,
"tag": "KEY",
"value": "clojure-plus.refreshAllCmd"
},
{
"context": " = if all then 'clojure-plus.refreshAllCmd' else 'clojure-plus.refreshCmd'\n atom.config.get(key)\n\n # TODO: Move me to M",
"end": 3620,
"score": 0.9105550646781921,
"start": 3597,
"tag": "KEY",
"value": "clojure-plus.refreshCmd"
}
] | lib/clj-commands.coffee | mauricioszabo/clojure-plus | 9 | fs = require 'fs'
process = require 'process'
PromisedRepl = require './promised-repl'
MarkerCollection = require './marker-collection'
module.exports = class CljCommands
cljs: false
constructor: (@watches, @repl) ->
@promisedRepl = new PromisedRepl(@repl)
@markers = new MarkerCollection(@watches)
prepareCljs: ->
if !@cljs
code = atom.config.get('clojure-plus.cljsCommand')
protoRepl.info("Preparing ClojureScript REPL...")
@promisedRepl.clear()
@promisedRepl.syncRun(code, 'user', session: 'cljs').then (e) =>
protoRepl.info("REPL code evaluated. Waiting for results...")
@promisedRepl.syncRun("(ns clj.--check-deps--)", 'clj.--check-deps--', session: 'cljs')
@promisedRepl.syncRun("(def last-exception (atom nil))", 'clj.--check-deps--', session: 'cljs')
@promisedRepl.syncRun("(def watches (atom {}))", 'clj.--check-deps--', session: 'cljs')
if e.value
if atom.config.get('clojure-plus.notify')
atom.notifications.addSuccess("Loaded ClojureScript REPL")
else
atom.notifications.addError("Error loading ClojureScript", detail: e.error)
@cljs = true
prepare: ->
code = @getFile("~/lib/clj/__check_deps__.clj")
@cljs = false
@promisedRepl.clear()
@promisedRepl.syncRun(code, 'user')
runRefresh: (all) ->
simple = atom.config.get('clojure-plus.simpleRefresh')
@prepare()
@runBefore()
if simple
@runSimpleRefresh(all)
else
@runFullRefresh(all)
@runAfter()
runBefore: ->
before = atom.config.get('clojure-plus.beforeRefreshCmd')
@promisedRepl.syncRun(before, "user")
runAfter: ->
after = atom.config.get('clojure-plus.afterRefreshCmd')
@promisedRepl.syncRun(after,"user")
runSimpleRefresh: (all) ->
return if all
notify = atom.config.get('clojure-plus.notify')
ns = @repl.EditorUtils.findNsDeclaration(atom.workspace.getActiveTextEditor())
return unless ns
refreshCmd = "(require '#{ns} :reload)"
@promisedRepl.syncRun(refreshCmd).then (result) =>
if result.value
atom.notifications.addSuccess("Refresh successful.") if notify
@repl.info("Refresh successful.")
@assignWatches()
else
atom.notifications.addError("Error refreshing.", detail: result.error) if notify
@repl.stderr("Error refreshing. CAUSE: #{result.error}\n")
runFullRefresh: (all) ->
shouldRefreshAll = all || !@lastRefreshSucceeded
refreshCmd = @getRefreshCmd(shouldRefreshAll)
notify = atom.config.get('clojure-plus.notify')
@promisedRepl.syncRun(refreshCmd, "user").then (result) =>
if result.value
value = @repl.parseEdn(result.value)
if !value.cause
@lastRefreshSucceeded = true
atom.notifications.addSuccess("Refresh successful.") if notify
@repl.info("Refresh successful.")
@assignWatches()
else
@lastRefreshSucceeded = false
causes = value.via.map (e) -> e.message
causes = "#{value.cause}\n#{causes.join("\n")}"
atom.notifications.addError("Error refreshing.", detail: causes) if notify
@repl.stderr("Error refreshing. CAUSE: #{value.cause}\n")
@repl.stderr(result.value)
else if !shouldRefreshAll
@runRefresh(true)
else
atom.notifications.addError("Error refreshing.", detail: result.error) if notify
@repl.stderr("Error refreshing. CAUSE: #{result.error}\n")
getRefreshCmd: (all) ->
key = if all then 'clojure-plus.refreshAllCmd' else 'clojure-plus.refreshCmd'
atom.config.get(key)
# TODO: Move me to MarkerCollection
assignWatches: ->
@runBefore()
@promisedRepl.syncRun("(reset! clj.--check-deps--/watches {})", 'user').then =>
for id, mark of @watches
delete @watches[id] unless mark.isValid()
ns = @repl.EditorUtils.findNsDeclaration(mark.editor)
range = @markers.getTopLevelForMark(mark)
@promisedRepl.syncRun(@markers.updatedCodeInRange(mark.editor, range), ns)
@runAfter()
openFileContainingVar: (varName) ->
tmpPath = '"' +
atom.config.get('clojure-plus.tempDir').replace(/\\/g, "\\\\").replace(/"/g, "\\\"") +
'"'
if varName
text = "(clj.--check-deps--/goto-var '#{varName} #{tmpPath})"
@promisedRepl.runCodeInCurrentNS(text).then (result) =>
if result.value
[file, line] = @repl.parseEdn(result.value)
pending = atom.config.get('clojure-plus.openPending')
atom.workspace.open(file, initialLine: line-1, searchAllPanes: true, pending: pending)
else
@repl.stderr("Error trying to open: #{result.error}")
getFile: (file) ->
fileName = file.replace("~", atom.packages.getActivePackage('clojure-plus').path)
fs.readFileSync(fileName).toString()
unusedImports: (filePath) ->
filePath = filePath.replace(/"/g, '\\\\').replace(/\\/g, '\\\\')
@promisedRepl.runCodeInCurrentNS("(clj.--check-deps--/unused-namespaces \"#{filePath}\")")
getSymbolsInEditor: (editor) ->
@promisedRepl.runCodeInCurrentNS("(clj.--check-deps--/symbols-from-ns-in-json *ns*)").then (result) =>
return unless result.value
JSON.parse(result.value)
| 125952 | fs = require 'fs'
process = require 'process'
PromisedRepl = require './promised-repl'
MarkerCollection = require './marker-collection'
module.exports = class CljCommands
cljs: false
constructor: (@watches, @repl) ->
@promisedRepl = new PromisedRepl(@repl)
@markers = new MarkerCollection(@watches)
prepareCljs: ->
if !@cljs
code = atom.config.get('clojure-plus.cljsCommand')
protoRepl.info("Preparing ClojureScript REPL...")
@promisedRepl.clear()
@promisedRepl.syncRun(code, 'user', session: 'cljs').then (e) =>
protoRepl.info("REPL code evaluated. Waiting for results...")
@promisedRepl.syncRun("(ns clj.--check-deps--)", 'clj.--check-deps--', session: 'cljs')
@promisedRepl.syncRun("(def last-exception (atom nil))", 'clj.--check-deps--', session: 'cljs')
@promisedRepl.syncRun("(def watches (atom {}))", 'clj.--check-deps--', session: 'cljs')
if e.value
if atom.config.get('clojure-plus.notify')
atom.notifications.addSuccess("Loaded ClojureScript REPL")
else
atom.notifications.addError("Error loading ClojureScript", detail: e.error)
@cljs = true
prepare: ->
code = @getFile("~/lib/clj/__check_deps__.clj")
@cljs = false
@promisedRepl.clear()
@promisedRepl.syncRun(code, 'user')
runRefresh: (all) ->
simple = atom.config.get('clojure-plus.simpleRefresh')
@prepare()
@runBefore()
if simple
@runSimpleRefresh(all)
else
@runFullRefresh(all)
@runAfter()
runBefore: ->
before = atom.config.get('clojure-plus.beforeRefreshCmd')
@promisedRepl.syncRun(before, "user")
runAfter: ->
after = atom.config.get('clojure-plus.afterRefreshCmd')
@promisedRepl.syncRun(after,"user")
runSimpleRefresh: (all) ->
return if all
notify = atom.config.get('clojure-plus.notify')
ns = @repl.EditorUtils.findNsDeclaration(atom.workspace.getActiveTextEditor())
return unless ns
refreshCmd = "(require '#{ns} :reload)"
@promisedRepl.syncRun(refreshCmd).then (result) =>
if result.value
atom.notifications.addSuccess("Refresh successful.") if notify
@repl.info("Refresh successful.")
@assignWatches()
else
atom.notifications.addError("Error refreshing.", detail: result.error) if notify
@repl.stderr("Error refreshing. CAUSE: #{result.error}\n")
runFullRefresh: (all) ->
shouldRefreshAll = all || !@lastRefreshSucceeded
refreshCmd = @getRefreshCmd(shouldRefreshAll)
notify = atom.config.get('clojure-plus.notify')
@promisedRepl.syncRun(refreshCmd, "user").then (result) =>
if result.value
value = @repl.parseEdn(result.value)
if !value.cause
@lastRefreshSucceeded = true
atom.notifications.addSuccess("Refresh successful.") if notify
@repl.info("Refresh successful.")
@assignWatches()
else
@lastRefreshSucceeded = false
causes = value.via.map (e) -> e.message
causes = "#{value.cause}\n#{causes.join("\n")}"
atom.notifications.addError("Error refreshing.", detail: causes) if notify
@repl.stderr("Error refreshing. CAUSE: #{value.cause}\n")
@repl.stderr(result.value)
else if !shouldRefreshAll
@runRefresh(true)
else
atom.notifications.addError("Error refreshing.", detail: result.error) if notify
@repl.stderr("Error refreshing. CAUSE: #{result.error}\n")
getRefreshCmd: (all) ->
key = if all then '<KEY>' else '<KEY>'
atom.config.get(key)
# TODO: Move me to MarkerCollection
assignWatches: ->
@runBefore()
@promisedRepl.syncRun("(reset! clj.--check-deps--/watches {})", 'user').then =>
for id, mark of @watches
delete @watches[id] unless mark.isValid()
ns = @repl.EditorUtils.findNsDeclaration(mark.editor)
range = @markers.getTopLevelForMark(mark)
@promisedRepl.syncRun(@markers.updatedCodeInRange(mark.editor, range), ns)
@runAfter()
openFileContainingVar: (varName) ->
tmpPath = '"' +
atom.config.get('clojure-plus.tempDir').replace(/\\/g, "\\\\").replace(/"/g, "\\\"") +
'"'
if varName
text = "(clj.--check-deps--/goto-var '#{varName} #{tmpPath})"
@promisedRepl.runCodeInCurrentNS(text).then (result) =>
if result.value
[file, line] = @repl.parseEdn(result.value)
pending = atom.config.get('clojure-plus.openPending')
atom.workspace.open(file, initialLine: line-1, searchAllPanes: true, pending: pending)
else
@repl.stderr("Error trying to open: #{result.error}")
getFile: (file) ->
fileName = file.replace("~", atom.packages.getActivePackage('clojure-plus').path)
fs.readFileSync(fileName).toString()
unusedImports: (filePath) ->
filePath = filePath.replace(/"/g, '\\\\').replace(/\\/g, '\\\\')
@promisedRepl.runCodeInCurrentNS("(clj.--check-deps--/unused-namespaces \"#{filePath}\")")
getSymbolsInEditor: (editor) ->
@promisedRepl.runCodeInCurrentNS("(clj.--check-deps--/symbols-from-ns-in-json *ns*)").then (result) =>
return unless result.value
JSON.parse(result.value)
| true | fs = require 'fs'
process = require 'process'
PromisedRepl = require './promised-repl'
MarkerCollection = require './marker-collection'
module.exports = class CljCommands
cljs: false
constructor: (@watches, @repl) ->
@promisedRepl = new PromisedRepl(@repl)
@markers = new MarkerCollection(@watches)
prepareCljs: ->
if !@cljs
code = atom.config.get('clojure-plus.cljsCommand')
protoRepl.info("Preparing ClojureScript REPL...")
@promisedRepl.clear()
@promisedRepl.syncRun(code, 'user', session: 'cljs').then (e) =>
protoRepl.info("REPL code evaluated. Waiting for results...")
@promisedRepl.syncRun("(ns clj.--check-deps--)", 'clj.--check-deps--', session: 'cljs')
@promisedRepl.syncRun("(def last-exception (atom nil))", 'clj.--check-deps--', session: 'cljs')
@promisedRepl.syncRun("(def watches (atom {}))", 'clj.--check-deps--', session: 'cljs')
if e.value
if atom.config.get('clojure-plus.notify')
atom.notifications.addSuccess("Loaded ClojureScript REPL")
else
atom.notifications.addError("Error loading ClojureScript", detail: e.error)
@cljs = true
prepare: ->
code = @getFile("~/lib/clj/__check_deps__.clj")
@cljs = false
@promisedRepl.clear()
@promisedRepl.syncRun(code, 'user')
runRefresh: (all) ->
simple = atom.config.get('clojure-plus.simpleRefresh')
@prepare()
@runBefore()
if simple
@runSimpleRefresh(all)
else
@runFullRefresh(all)
@runAfter()
runBefore: ->
before = atom.config.get('clojure-plus.beforeRefreshCmd')
@promisedRepl.syncRun(before, "user")
runAfter: ->
after = atom.config.get('clojure-plus.afterRefreshCmd')
@promisedRepl.syncRun(after,"user")
runSimpleRefresh: (all) ->
return if all
notify = atom.config.get('clojure-plus.notify')
ns = @repl.EditorUtils.findNsDeclaration(atom.workspace.getActiveTextEditor())
return unless ns
refreshCmd = "(require '#{ns} :reload)"
@promisedRepl.syncRun(refreshCmd).then (result) =>
if result.value
atom.notifications.addSuccess("Refresh successful.") if notify
@repl.info("Refresh successful.")
@assignWatches()
else
atom.notifications.addError("Error refreshing.", detail: result.error) if notify
@repl.stderr("Error refreshing. CAUSE: #{result.error}\n")
runFullRefresh: (all) ->
shouldRefreshAll = all || !@lastRefreshSucceeded
refreshCmd = @getRefreshCmd(shouldRefreshAll)
notify = atom.config.get('clojure-plus.notify')
@promisedRepl.syncRun(refreshCmd, "user").then (result) =>
if result.value
value = @repl.parseEdn(result.value)
if !value.cause
@lastRefreshSucceeded = true
atom.notifications.addSuccess("Refresh successful.") if notify
@repl.info("Refresh successful.")
@assignWatches()
else
@lastRefreshSucceeded = false
causes = value.via.map (e) -> e.message
causes = "#{value.cause}\n#{causes.join("\n")}"
atom.notifications.addError("Error refreshing.", detail: causes) if notify
@repl.stderr("Error refreshing. CAUSE: #{value.cause}\n")
@repl.stderr(result.value)
else if !shouldRefreshAll
@runRefresh(true)
else
atom.notifications.addError("Error refreshing.", detail: result.error) if notify
@repl.stderr("Error refreshing. CAUSE: #{result.error}\n")
getRefreshCmd: (all) ->
key = if all then 'PI:KEY:<KEY>END_PI' else 'PI:KEY:<KEY>END_PI'
atom.config.get(key)
# TODO: Move me to MarkerCollection
assignWatches: ->
@runBefore()
@promisedRepl.syncRun("(reset! clj.--check-deps--/watches {})", 'user').then =>
for id, mark of @watches
delete @watches[id] unless mark.isValid()
ns = @repl.EditorUtils.findNsDeclaration(mark.editor)
range = @markers.getTopLevelForMark(mark)
@promisedRepl.syncRun(@markers.updatedCodeInRange(mark.editor, range), ns)
@runAfter()
openFileContainingVar: (varName) ->
tmpPath = '"' +
atom.config.get('clojure-plus.tempDir').replace(/\\/g, "\\\\").replace(/"/g, "\\\"") +
'"'
if varName
text = "(clj.--check-deps--/goto-var '#{varName} #{tmpPath})"
@promisedRepl.runCodeInCurrentNS(text).then (result) =>
if result.value
[file, line] = @repl.parseEdn(result.value)
pending = atom.config.get('clojure-plus.openPending')
atom.workspace.open(file, initialLine: line-1, searchAllPanes: true, pending: pending)
else
@repl.stderr("Error trying to open: #{result.error}")
getFile: (file) ->
fileName = file.replace("~", atom.packages.getActivePackage('clojure-plus').path)
fs.readFileSync(fileName).toString()
unusedImports: (filePath) ->
filePath = filePath.replace(/"/g, '\\\\').replace(/\\/g, '\\\\')
@promisedRepl.runCodeInCurrentNS("(clj.--check-deps--/unused-namespaces \"#{filePath}\")")
getSymbolsInEditor: (editor) ->
@promisedRepl.runCodeInCurrentNS("(clj.--check-deps--/symbols-from-ns-in-json *ns*)").then (result) =>
return unless result.value
JSON.parse(result.value)
|
[
{
"context": "# Made with Framer\n# by Benjamin den Boer\n# www.framerjs.com\n\n# Sketch Import\nsketch = Fram",
"end": 41,
"score": 0.9998842477798462,
"start": 24,
"tag": "NAME",
"value": "Benjamin den Boer"
}
] | examples/ios-music-player.framer/framer/backups/backup-1442397285.coffee | RaffaelSilvado/MUZIK | 109 | # Made with Framer
# by Benjamin den Boer
# www.framerjs.com
# Sketch Import
sketch = Framer.Importer.load "imported/music"
# Include the module
{AudioPlayer} = require "audio"
# Set-up
new BackgroundLayer
audio = new AudioPlayer audio: "audio.mp3", width: 80, height: 80
# Copy the frame (x,y, width, height) of the audioPlayer
# Customize play and pause buttons
audio.frame = sketch.play.frame
audio.controls.showPlay = -> @image = sketch.play.image
audio.controls.showPause = -> @image = sketch.pause.image
# Progress Bar
audio.showProgress = true
audio.progressBar.props =
width: 556, height: 14
y: sketch.screen.maxY - 432
backgroundColor: "e7e7e7"
borderRadius: 0
audio.progressBar.fill.backgroundColor = "transparent"
audio.progressBar.centerX()
audio.progressBar.knob.props =
backgroundColor: "#FF2D55",
width: 3, height: 30
borderRadius: 4
# Visualize time
audio.showTime = true
audio.time.x = audio.progressBar.x - 56
audio.time.centerY(280)
audio.showTimeLeft = true
audio.timeLeft.x = audio.progressBar.maxX + 16
audio.timeLeft.centerY(278)
# Volume Bar
audio.showVolume = true
audio.volumeBar.props =
width: 540, height: 6
y: sketch.screen.height - 117
value: 0.75, knobSize: 35
audio.volumeBar.knob.style.boxShadow = "0 0 0 1px rgba(0,0,0,0.075), 0 3px 4px rgba(0,0,0,0.3)"
audio.volumeBar.centerX() | 4652 | # Made with Framer
# by <NAME>
# www.framerjs.com
# Sketch Import
sketch = Framer.Importer.load "imported/music"
# Include the module
{AudioPlayer} = require "audio"
# Set-up
new BackgroundLayer
audio = new AudioPlayer audio: "audio.mp3", width: 80, height: 80
# Copy the frame (x,y, width, height) of the audioPlayer
# Customize play and pause buttons
audio.frame = sketch.play.frame
audio.controls.showPlay = -> @image = sketch.play.image
audio.controls.showPause = -> @image = sketch.pause.image
# Progress Bar
audio.showProgress = true
audio.progressBar.props =
width: 556, height: 14
y: sketch.screen.maxY - 432
backgroundColor: "e7e7e7"
borderRadius: 0
audio.progressBar.fill.backgroundColor = "transparent"
audio.progressBar.centerX()
audio.progressBar.knob.props =
backgroundColor: "#FF2D55",
width: 3, height: 30
borderRadius: 4
# Visualize time
audio.showTime = true
audio.time.x = audio.progressBar.x - 56
audio.time.centerY(280)
audio.showTimeLeft = true
audio.timeLeft.x = audio.progressBar.maxX + 16
audio.timeLeft.centerY(278)
# Volume Bar
audio.showVolume = true
audio.volumeBar.props =
width: 540, height: 6
y: sketch.screen.height - 117
value: 0.75, knobSize: 35
audio.volumeBar.knob.style.boxShadow = "0 0 0 1px rgba(0,0,0,0.075), 0 3px 4px rgba(0,0,0,0.3)"
audio.volumeBar.centerX() | true | # Made with Framer
# by PI:NAME:<NAME>END_PI
# www.framerjs.com
# Sketch Import
sketch = Framer.Importer.load "imported/music"
# Include the module
{AudioPlayer} = require "audio"
# Set-up
new BackgroundLayer
audio = new AudioPlayer audio: "audio.mp3", width: 80, height: 80
# Copy the frame (x,y, width, height) of the audioPlayer
# Customize play and pause buttons
audio.frame = sketch.play.frame
audio.controls.showPlay = -> @image = sketch.play.image
audio.controls.showPause = -> @image = sketch.pause.image
# Progress Bar
audio.showProgress = true
audio.progressBar.props =
width: 556, height: 14
y: sketch.screen.maxY - 432
backgroundColor: "e7e7e7"
borderRadius: 0
audio.progressBar.fill.backgroundColor = "transparent"
audio.progressBar.centerX()
audio.progressBar.knob.props =
backgroundColor: "#FF2D55",
width: 3, height: 30
borderRadius: 4
# Visualize time
audio.showTime = true
audio.time.x = audio.progressBar.x - 56
audio.time.centerY(280)
audio.showTimeLeft = true
audio.timeLeft.x = audio.progressBar.maxX + 16
audio.timeLeft.centerY(278)
# Volume Bar
audio.showVolume = true
audio.volumeBar.props =
width: 540, height: 6
y: sketch.screen.height - 117
value: 0.75, knobSize: 35
audio.volumeBar.knob.style.boxShadow = "0 0 0 1px rgba(0,0,0,0.075), 0 3px 4px rgba(0,0,0,0.3)"
audio.volumeBar.centerX() |
[
{
"context": "t) ->\n result = helper.extend {\n name: 'name'\n },\n {\n age: 10\n }\n tes",
"end": 143,
"score": 0.6618530750274658,
"start": 139,
"tag": "NAME",
"value": "name"
}
] | test/utils/helper_test.coffee | mcfung/GoldenParserJS | 4 | helper = require '../../src/utils/helper'
exports.helper =
'test extend objects': (test) ->
result = helper.extend {
name: 'name'
},
{
age: 10
}
test.deepEqual result, {name: 'name', age: 10}
test.done()
'test null target': (test) ->
result = helper.extend(null, {
name: 'name'
})
test.deepEqual result, {name: 'name'}
result = helper.extend(undefined, {
name: 'name'
})
test.deepEqual result, {name: 'name'}
test.done()
'test no extendee': (test) ->
result = helper.extend({name: 'name'})
test.deepEqual result, {name: 'name'}
test.done() | 151185 | helper = require '../../src/utils/helper'
exports.helper =
'test extend objects': (test) ->
result = helper.extend {
name: '<NAME>'
},
{
age: 10
}
test.deepEqual result, {name: 'name', age: 10}
test.done()
'test null target': (test) ->
result = helper.extend(null, {
name: 'name'
})
test.deepEqual result, {name: 'name'}
result = helper.extend(undefined, {
name: 'name'
})
test.deepEqual result, {name: 'name'}
test.done()
'test no extendee': (test) ->
result = helper.extend({name: 'name'})
test.deepEqual result, {name: 'name'}
test.done() | true | helper = require '../../src/utils/helper'
exports.helper =
'test extend objects': (test) ->
result = helper.extend {
name: 'PI:NAME:<NAME>END_PI'
},
{
age: 10
}
test.deepEqual result, {name: 'name', age: 10}
test.done()
'test null target': (test) ->
result = helper.extend(null, {
name: 'name'
})
test.deepEqual result, {name: 'name'}
result = helper.extend(undefined, {
name: 'name'
})
test.deepEqual result, {name: 'name'}
test.done()
'test no extendee': (test) ->
result = helper.extend({name: 'name'})
test.deepEqual result, {name: 'name'}
test.done() |
[
{
"context": "essions\", {\n email: email\n password: password\n callbackUrl: callbackUrl\n }\n .t",
"end": 389,
"score": 0.9989757537841797,
"start": 381,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "devices\", {\n email: email\n password: password\n callbackUrl: callbackUrl\n }\n .t",
"end": 693,
"score": 0.998761773109436,
"start": 685,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "es: (password, confirmPassword) =>\n password != confirmPassword\n\n forgotPassword: (email) =>\n @http.p",
"end": 920,
"score": 0.7875839471817017,
"start": 913,
"tag": "PASSWORD",
"value": "confirm"
},
{
"context": "I}/reset\", device: device, token: token, password: password)\n .then (result) =>\n return result.da",
"end": 1212,
"score": 0.995941162109375,
"start": 1204,
"tag": "PASSWORD",
"value": "password"
}
] | app/authenticator-service.coffee | octoblu/email-password-site | 1 | class AuthenticatorService
# @HOST: "https://email-password.octoblu.com"
# @HOST: "http://localhost:3003"
constructor: ($q, $http, AUTHENTICATOR_URI) ->
@q = $q
@http = $http
@AUTHENTICATOR_URI = AUTHENTICATOR_URI
authenticate: (email, password, callbackUrl) =>
@http
.post "#{@AUTHENTICATOR_URI}/sessions", {
email: email
password: password
callbackUrl: callbackUrl
}
.then (result) =>
result.data.callbackUrl
.catch (result) =>
@q.reject result.data
register: (email, password, callbackUrl) =>
@http
.post "#{@AUTHENTICATOR_URI}/devices", {
email: email
password: password
callbackUrl: callbackUrl
}
.then (result) =>
result.data.callbackUrl
.catch (result) =>
@q.reject result.data
passwordMatches: (password, confirmPassword) =>
password != confirmPassword
forgotPassword: (email) =>
@http.post("#{@AUTHENTICATOR_URI}/forgot", email: email)
.then (result) =>
return result.data
resetPassword: (device, token, password) =>
@http.post("#{@AUTHENTICATOR_URI}/reset", device: device, token: token, password: password)
.then (result) =>
return result.data
angular.module('email-password').service 'AuthenticatorService', AuthenticatorService
| 133189 | class AuthenticatorService
# @HOST: "https://email-password.octoblu.com"
# @HOST: "http://localhost:3003"
constructor: ($q, $http, AUTHENTICATOR_URI) ->
@q = $q
@http = $http
@AUTHENTICATOR_URI = AUTHENTICATOR_URI
authenticate: (email, password, callbackUrl) =>
@http
.post "#{@AUTHENTICATOR_URI}/sessions", {
email: email
password: <PASSWORD>
callbackUrl: callbackUrl
}
.then (result) =>
result.data.callbackUrl
.catch (result) =>
@q.reject result.data
register: (email, password, callbackUrl) =>
@http
.post "#{@AUTHENTICATOR_URI}/devices", {
email: email
password: <PASSWORD>
callbackUrl: callbackUrl
}
.then (result) =>
result.data.callbackUrl
.catch (result) =>
@q.reject result.data
passwordMatches: (password, confirmPassword) =>
password != <PASSWORD>Password
forgotPassword: (email) =>
@http.post("#{@AUTHENTICATOR_URI}/forgot", email: email)
.then (result) =>
return result.data
resetPassword: (device, token, password) =>
@http.post("#{@AUTHENTICATOR_URI}/reset", device: device, token: token, password: <PASSWORD>)
.then (result) =>
return result.data
angular.module('email-password').service 'AuthenticatorService', AuthenticatorService
| true | class AuthenticatorService
# @HOST: "https://email-password.octoblu.com"
# @HOST: "http://localhost:3003"
constructor: ($q, $http, AUTHENTICATOR_URI) ->
@q = $q
@http = $http
@AUTHENTICATOR_URI = AUTHENTICATOR_URI
authenticate: (email, password, callbackUrl) =>
@http
.post "#{@AUTHENTICATOR_URI}/sessions", {
email: email
password: PI:PASSWORD:<PASSWORD>END_PI
callbackUrl: callbackUrl
}
.then (result) =>
result.data.callbackUrl
.catch (result) =>
@q.reject result.data
register: (email, password, callbackUrl) =>
@http
.post "#{@AUTHENTICATOR_URI}/devices", {
email: email
password: PI:PASSWORD:<PASSWORD>END_PI
callbackUrl: callbackUrl
}
.then (result) =>
result.data.callbackUrl
.catch (result) =>
@q.reject result.data
passwordMatches: (password, confirmPassword) =>
password != PI:PASSWORD:<PASSWORD>END_PIPassword
forgotPassword: (email) =>
@http.post("#{@AUTHENTICATOR_URI}/forgot", email: email)
.then (result) =>
return result.data
resetPassword: (device, token, password) =>
@http.post("#{@AUTHENTICATOR_URI}/reset", device: device, token: token, password: PI:PASSWORD:<PASSWORD>END_PI)
.then (result) =>
return result.data
angular.module('email-password').service 'AuthenticatorService', AuthenticatorService
|
[
{
"context": "g.internal[appOrRb].client.css.imports\n\tkey = \"#{paths.root}#{paths.abs}/#{paths.rel}\"\n\tunless imports.length\n\t\tdelete cImports[key] if ",
"end": 3403,
"score": 0.992233395576477,
"start": 3363,
"tag": "KEY",
"value": "\"#{paths.root}#{paths.abs}/#{paths.rel}\""
}
] | src/plugins/gulp-absolute-css-urls.coffee | rapid-build/rapid-build | 5 | path = require 'path'
through = require 'through2'
PluginError = require 'plugin-error'
PLUGIN_NAME = 'gulp-absolute-css-urls'
# for find and replace - added negative lookahead to not match comments
urlRegX = /url\s*\(\s*['"]?(.*?)['"]?\s*\)(?![^\*]*?\*\/)/g
importNoUrlRegX = /@import\s*?['"]+?(.*?)['"]+?(?![^\*]*?\*\/)/g
# Helpers
# =======
pathHelp =
isWin: (_path) ->
_path.indexOf('\\') isnt -1
isWinAbs: (_path) ->
_path.indexOf(':\\') isnt -1
removeDrive: (_path) ->
return _path unless @isWinAbs _path
i = _path.indexOf(':\\') + 1
_path = _path.substr i
swapBackslashes: (_path) ->
regx = /\\/g
_path.replace regx, '/'
format: (_path) ->
return _path unless @isWin _path
_path = @removeDrive _path
_path = @swapBackslashes _path
_path
hasTrailingSlash: (_path) ->
_path[_path.length-1] is '/'
isAbsolute: (urlPath) ->
urlPath[0] is '/'
isExternal: (urlPath) -> # like from http
urlPath.indexOf('//') isnt -1
isImport: (_path) ->
path.extname(_path) is '.css'
getRelative: (paths) ->
_path = path.resolve paths.abs, paths.url
pathHelp.format _path
getAbsolute: (paths, opts) ->
prependPath = opts.prependPath isnt false
base = paths.base # /Users/xxx/app/dist/client/libs/
rel = paths.rel # build/styles/x.css
# console.log "Base: #{base} | Rel: #{rel}"
base = base.split '/'
# console.log base
base = base[base.length-1]
base = "/#{base}" # /libs
# console.log "Base: #{base}"
rel = rel.split '/'
rel = rel[0] # build
rel = "/#{rel}"
# console.log "Rel: #{rel}"
_path = ''
_path = "#{base}#{rel}" if prependPath
_path = "/#{opts.rbDistDir}#{_path}" if paths.isRbPath
_path = "#{_path}#{paths.url}" # /libs/build/images/x.png
# console.log _path
_path
getCssUrl: (_path) ->
_path = @format _path
url = "url('#{_path}')" # url('/libs/build/images/x.png')
getCssImport: (_path) ->
_path = @format _path
_import = "@import '#{_path}'" # @import '/styles/imports/x.css'
getImport: (_path, paths) ->
return unless @isImport _path
_path = "#{paths.root}#{_path}"
formatCssUrl: (match, formatTask, config, paths={}, opts={}) ->
isExternal = @isExternal paths.url
return url: match if isExternal
isAbsolute = @isAbsolute paths.url
msg = if isAbsolute then 'absolute' else 'relative'
_path = if isAbsolute then @getAbsolute paths, opts else @getRelative paths
_import = @getImport _path, paths
# console.log "#{msg}: #{_path}"
url = pathHelp[formatTask] _path
{ url, _import }
format =
root: (_path) -> # need a beginning / and no trailing /
return null unless _path
_path = _path.trim()
_path = pathHelp.swapBackslashes _path
_path = _path.slice 0, -1 if _path.length > 1 and pathHelp.hasTrailingSlash _path
return null if _path.length is 1 and _path[0] is '/'
return _path if _path.indexOf('/') is 0
_path = "/#{_path}"
absPath: (file, root) ->
_path = file.path.replace file.cwd, ''
_path = pathHelp.swapBackslashes _path
_path = _path.replace root, ''
_path = path.dirname _path
addConfigImports = (imports, config, paths) ->
appOrRb = if paths.isRbPath then 'rb' else 'app'
cImports = config.internal[appOrRb].client.css.imports
key = "#{paths.root}#{paths.abs}/#{paths.rel}"
unless imports.length
delete cImports[key] if cImports[key]
return
cImports[key] = imports
findAndReplace = (css, config, paths, opts, imports, formatTask, regX) ->
css.replace regX, (match, urlPath) ->
paths.url = urlPath
_css = pathHelp.formatCssUrl match, formatTask, config, paths, opts
imports.push _css._import if _css._import
_css.url
# Main (replace relative urls with absolute urls)
# ===============================================
replaceCssUrls = (file, root, config, opts={}) ->
css = file.contents.toString()
_root = format.root root
abs = format.absPath file, _root
base = pathHelp.format file.base
rel = pathHelp.format file.relative
rbDistPath = pathHelp.format opts.rbDistPath
isRbPath = base.indexOf(rbDistPath) isnt -1
paths = { root, abs, base, rel, isRbPath }
imports = []
# urlPath = ../images/superheroes.png | /images/superheroes.png
css = findAndReplace css, config, paths, opts, imports, 'getCssUrl', urlRegX # match = url('../images/x.png')
css = findAndReplace css, config, paths, opts, imports, 'getCssImport', importNoUrlRegX # match = @import 'imports/x.css'
addConfigImports imports, config, paths
css
# Plugin level function(dealing with files)
# root is the path to resolve urls from
# =========================================
gulpAbsoluteCssUrls = (root, config, opts) ->
through.obj (file, enc, cb) ->
return cb null, file if file.isNull() # return empty file
return cb new PluginError PLUGIN_NAME, 'streaming not supported' if file.isStream()
if file.isBuffer()
contents = replaceCssUrls file, root, config, opts
file.contents = new Buffer contents
cb null, file
module.exports = gulpAbsoluteCssUrls
| 48969 | path = require 'path'
through = require 'through2'
PluginError = require 'plugin-error'
PLUGIN_NAME = 'gulp-absolute-css-urls'
# for find and replace - added negative lookahead to not match comments
urlRegX = /url\s*\(\s*['"]?(.*?)['"]?\s*\)(?![^\*]*?\*\/)/g
importNoUrlRegX = /@import\s*?['"]+?(.*?)['"]+?(?![^\*]*?\*\/)/g
# Helpers
# =======
pathHelp =
isWin: (_path) ->
_path.indexOf('\\') isnt -1
isWinAbs: (_path) ->
_path.indexOf(':\\') isnt -1
removeDrive: (_path) ->
return _path unless @isWinAbs _path
i = _path.indexOf(':\\') + 1
_path = _path.substr i
swapBackslashes: (_path) ->
regx = /\\/g
_path.replace regx, '/'
format: (_path) ->
return _path unless @isWin _path
_path = @removeDrive _path
_path = @swapBackslashes _path
_path
hasTrailingSlash: (_path) ->
_path[_path.length-1] is '/'
isAbsolute: (urlPath) ->
urlPath[0] is '/'
isExternal: (urlPath) -> # like from http
urlPath.indexOf('//') isnt -1
isImport: (_path) ->
path.extname(_path) is '.css'
getRelative: (paths) ->
_path = path.resolve paths.abs, paths.url
pathHelp.format _path
getAbsolute: (paths, opts) ->
prependPath = opts.prependPath isnt false
base = paths.base # /Users/xxx/app/dist/client/libs/
rel = paths.rel # build/styles/x.css
# console.log "Base: #{base} | Rel: #{rel}"
base = base.split '/'
# console.log base
base = base[base.length-1]
base = "/#{base}" # /libs
# console.log "Base: #{base}"
rel = rel.split '/'
rel = rel[0] # build
rel = "/#{rel}"
# console.log "Rel: #{rel}"
_path = ''
_path = "#{base}#{rel}" if prependPath
_path = "/#{opts.rbDistDir}#{_path}" if paths.isRbPath
_path = "#{_path}#{paths.url}" # /libs/build/images/x.png
# console.log _path
_path
getCssUrl: (_path) ->
_path = @format _path
url = "url('#{_path}')" # url('/libs/build/images/x.png')
getCssImport: (_path) ->
_path = @format _path
_import = "@import '#{_path}'" # @import '/styles/imports/x.css'
getImport: (_path, paths) ->
return unless @isImport _path
_path = "#{paths.root}#{_path}"
formatCssUrl: (match, formatTask, config, paths={}, opts={}) ->
isExternal = @isExternal paths.url
return url: match if isExternal
isAbsolute = @isAbsolute paths.url
msg = if isAbsolute then 'absolute' else 'relative'
_path = if isAbsolute then @getAbsolute paths, opts else @getRelative paths
_import = @getImport _path, paths
# console.log "#{msg}: #{_path}"
url = pathHelp[formatTask] _path
{ url, _import }
format =
root: (_path) -> # need a beginning / and no trailing /
return null unless _path
_path = _path.trim()
_path = pathHelp.swapBackslashes _path
_path = _path.slice 0, -1 if _path.length > 1 and pathHelp.hasTrailingSlash _path
return null if _path.length is 1 and _path[0] is '/'
return _path if _path.indexOf('/') is 0
_path = "/#{_path}"
absPath: (file, root) ->
_path = file.path.replace file.cwd, ''
_path = pathHelp.swapBackslashes _path
_path = _path.replace root, ''
_path = path.dirname _path
addConfigImports = (imports, config, paths) ->
appOrRb = if paths.isRbPath then 'rb' else 'app'
cImports = config.internal[appOrRb].client.css.imports
key = <KEY>
unless imports.length
delete cImports[key] if cImports[key]
return
cImports[key] = imports
findAndReplace = (css, config, paths, opts, imports, formatTask, regX) ->
css.replace regX, (match, urlPath) ->
paths.url = urlPath
_css = pathHelp.formatCssUrl match, formatTask, config, paths, opts
imports.push _css._import if _css._import
_css.url
# Main (replace relative urls with absolute urls)
# ===============================================
replaceCssUrls = (file, root, config, opts={}) ->
css = file.contents.toString()
_root = format.root root
abs = format.absPath file, _root
base = pathHelp.format file.base
rel = pathHelp.format file.relative
rbDistPath = pathHelp.format opts.rbDistPath
isRbPath = base.indexOf(rbDistPath) isnt -1
paths = { root, abs, base, rel, isRbPath }
imports = []
# urlPath = ../images/superheroes.png | /images/superheroes.png
css = findAndReplace css, config, paths, opts, imports, 'getCssUrl', urlRegX # match = url('../images/x.png')
css = findAndReplace css, config, paths, opts, imports, 'getCssImport', importNoUrlRegX # match = @import 'imports/x.css'
addConfigImports imports, config, paths
css
# Plugin level function(dealing with files)
# root is the path to resolve urls from
# =========================================
gulpAbsoluteCssUrls = (root, config, opts) ->
through.obj (file, enc, cb) ->
return cb null, file if file.isNull() # return empty file
return cb new PluginError PLUGIN_NAME, 'streaming not supported' if file.isStream()
if file.isBuffer()
contents = replaceCssUrls file, root, config, opts
file.contents = new Buffer contents
cb null, file
module.exports = gulpAbsoluteCssUrls
| true | path = require 'path'
through = require 'through2'
PluginError = require 'plugin-error'
PLUGIN_NAME = 'gulp-absolute-css-urls'
# for find and replace - added negative lookahead to not match comments
urlRegX = /url\s*\(\s*['"]?(.*?)['"]?\s*\)(?![^\*]*?\*\/)/g
importNoUrlRegX = /@import\s*?['"]+?(.*?)['"]+?(?![^\*]*?\*\/)/g
# Helpers
# =======
pathHelp =
isWin: (_path) ->
_path.indexOf('\\') isnt -1
isWinAbs: (_path) ->
_path.indexOf(':\\') isnt -1
removeDrive: (_path) ->
return _path unless @isWinAbs _path
i = _path.indexOf(':\\') + 1
_path = _path.substr i
swapBackslashes: (_path) ->
regx = /\\/g
_path.replace regx, '/'
format: (_path) ->
return _path unless @isWin _path
_path = @removeDrive _path
_path = @swapBackslashes _path
_path
hasTrailingSlash: (_path) ->
_path[_path.length-1] is '/'
isAbsolute: (urlPath) ->
urlPath[0] is '/'
isExternal: (urlPath) -> # like from http
urlPath.indexOf('//') isnt -1
isImport: (_path) ->
path.extname(_path) is '.css'
getRelative: (paths) ->
_path = path.resolve paths.abs, paths.url
pathHelp.format _path
getAbsolute: (paths, opts) ->
prependPath = opts.prependPath isnt false
base = paths.base # /Users/xxx/app/dist/client/libs/
rel = paths.rel # build/styles/x.css
# console.log "Base: #{base} | Rel: #{rel}"
base = base.split '/'
# console.log base
base = base[base.length-1]
base = "/#{base}" # /libs
# console.log "Base: #{base}"
rel = rel.split '/'
rel = rel[0] # build
rel = "/#{rel}"
# console.log "Rel: #{rel}"
_path = ''
_path = "#{base}#{rel}" if prependPath
_path = "/#{opts.rbDistDir}#{_path}" if paths.isRbPath
_path = "#{_path}#{paths.url}" # /libs/build/images/x.png
# console.log _path
_path
getCssUrl: (_path) ->
_path = @format _path
url = "url('#{_path}')" # url('/libs/build/images/x.png')
getCssImport: (_path) ->
_path = @format _path
_import = "@import '#{_path}'" # @import '/styles/imports/x.css'
getImport: (_path, paths) ->
return unless @isImport _path
_path = "#{paths.root}#{_path}"
formatCssUrl: (match, formatTask, config, paths={}, opts={}) ->
isExternal = @isExternal paths.url
return url: match if isExternal
isAbsolute = @isAbsolute paths.url
msg = if isAbsolute then 'absolute' else 'relative'
_path = if isAbsolute then @getAbsolute paths, opts else @getRelative paths
_import = @getImport _path, paths
# console.log "#{msg}: #{_path}"
url = pathHelp[formatTask] _path
{ url, _import }
format =
root: (_path) -> # need a beginning / and no trailing /
return null unless _path
_path = _path.trim()
_path = pathHelp.swapBackslashes _path
_path = _path.slice 0, -1 if _path.length > 1 and pathHelp.hasTrailingSlash _path
return null if _path.length is 1 and _path[0] is '/'
return _path if _path.indexOf('/') is 0
_path = "/#{_path}"
absPath: (file, root) ->
_path = file.path.replace file.cwd, ''
_path = pathHelp.swapBackslashes _path
_path = _path.replace root, ''
_path = path.dirname _path
addConfigImports = (imports, config, paths) ->
appOrRb = if paths.isRbPath then 'rb' else 'app'
cImports = config.internal[appOrRb].client.css.imports
key = PI:KEY:<KEY>END_PI
unless imports.length
delete cImports[key] if cImports[key]
return
cImports[key] = imports
findAndReplace = (css, config, paths, opts, imports, formatTask, regX) ->
css.replace regX, (match, urlPath) ->
paths.url = urlPath
_css = pathHelp.formatCssUrl match, formatTask, config, paths, opts
imports.push _css._import if _css._import
_css.url
# Main (replace relative urls with absolute urls)
# ===============================================
replaceCssUrls = (file, root, config, opts={}) ->
css = file.contents.toString()
_root = format.root root
abs = format.absPath file, _root
base = pathHelp.format file.base
rel = pathHelp.format file.relative
rbDistPath = pathHelp.format opts.rbDistPath
isRbPath = base.indexOf(rbDistPath) isnt -1
paths = { root, abs, base, rel, isRbPath }
imports = []
# urlPath = ../images/superheroes.png | /images/superheroes.png
css = findAndReplace css, config, paths, opts, imports, 'getCssUrl', urlRegX # match = url('../images/x.png')
css = findAndReplace css, config, paths, opts, imports, 'getCssImport', importNoUrlRegX # match = @import 'imports/x.css'
addConfigImports imports, config, paths
css
# Plugin level function(dealing with files)
# root is the path to resolve urls from
# =========================================
gulpAbsoluteCssUrls = (root, config, opts) ->
through.obj (file, enc, cb) ->
return cb null, file if file.isNull() # return empty file
return cb new PluginError PLUGIN_NAME, 'streaming not supported' if file.isStream()
if file.isBuffer()
contents = replaceCssUrls file, root, config, opts
file.contents = new Buffer contents
cb null, file
module.exports = gulpAbsoluteCssUrls
|
[
{
"context": "# Copyright 2012 Joshua Carver \n# \n# Licensed under the Apache License, Versio",
"end": 30,
"score": 0.9998703002929688,
"start": 17,
"tag": "NAME",
"value": "Joshua Carver"
}
] | src/coffeescript/charts/line_bar.coffee | jcarver989/raphy-charts | 5 | # Copyright 2012 Joshua Carver
#
# 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.
# renders bars instead of lines
# @import scaling.coffee
# @import tooltip.coffee
class LineBar
constructor: (@r, @raw_points, @scaled_points, @height, @width, @options = {}) ->
@effective_height = @height - @options.y_padding
# 1st param to rect is top left corner
# point.x should be the midpoint of the bar
# hence x = point.x - x_offset
@x_offset = @options.bar_width / 2
draw: ->
@draw_bars()
draw_bars: ->
set = @r.set()
tooltips = []
max_point = 0
min_point = 0
for point, i in @scaled_points
x = point.x - @x_offset
rect = @r.rect(x, point.y, @options.bar_width, @effective_height - point.y)
set.push rect
tooltips.push new Tooltip(@r, rect, @raw_points[i].y)
max_point = i if @raw_points[i].y >= @raw_points[max_point].y
min_point = i if @raw_points[i].y < @raw_points[min_point].y
set.attr({
"fill" : @options.line_color
"stroke" : "none"
})
if @options.label_max
tooltips[max_point].show()
if @options.label_min
tooltips[min_point].show()
| 225687 | # Copyright 2012 <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.
# renders bars instead of lines
# @import scaling.coffee
# @import tooltip.coffee
class LineBar
constructor: (@r, @raw_points, @scaled_points, @height, @width, @options = {}) ->
@effective_height = @height - @options.y_padding
# 1st param to rect is top left corner
# point.x should be the midpoint of the bar
# hence x = point.x - x_offset
@x_offset = @options.bar_width / 2
draw: ->
@draw_bars()
draw_bars: ->
set = @r.set()
tooltips = []
max_point = 0
min_point = 0
for point, i in @scaled_points
x = point.x - @x_offset
rect = @r.rect(x, point.y, @options.bar_width, @effective_height - point.y)
set.push rect
tooltips.push new Tooltip(@r, rect, @raw_points[i].y)
max_point = i if @raw_points[i].y >= @raw_points[max_point].y
min_point = i if @raw_points[i].y < @raw_points[min_point].y
set.attr({
"fill" : @options.line_color
"stroke" : "none"
})
if @options.label_max
tooltips[max_point].show()
if @options.label_min
tooltips[min_point].show()
| true | # Copyright 2012 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.
# renders bars instead of lines
# @import scaling.coffee
# @import tooltip.coffee
class LineBar
constructor: (@r, @raw_points, @scaled_points, @height, @width, @options = {}) ->
@effective_height = @height - @options.y_padding
# 1st param to rect is top left corner
# point.x should be the midpoint of the bar
# hence x = point.x - x_offset
@x_offset = @options.bar_width / 2
draw: ->
@draw_bars()
draw_bars: ->
set = @r.set()
tooltips = []
max_point = 0
min_point = 0
for point, i in @scaled_points
x = point.x - @x_offset
rect = @r.rect(x, point.y, @options.bar_width, @effective_height - point.y)
set.push rect
tooltips.push new Tooltip(@r, rect, @raw_points[i].y)
max_point = i if @raw_points[i].y >= @raw_points[max_point].y
min_point = i if @raw_points[i].y < @raw_points[min_point].y
set.attr({
"fill" : @options.line_color
"stroke" : "none"
})
if @options.label_max
tooltips[max_point].show()
if @options.label_min
tooltips[min_point].show()
|
[
{
"context": "###\n X-Wing Squad Builder\n Geordan Rosario <geordan@gmail.com>\n https://github.com/georda",
"end": 48,
"score": 0.9998860359191895,
"start": 33,
"tag": "NAME",
"value": "Geordan Rosario"
},
{
"context": "###\n X-Wing Squad Builder\n Geordan Rosario <geordan@gmail.com>\n https://github.com/geordanr/xwing\n###\nDFL_LA",
"end": 67,
"score": 0.9999240040779114,
"start": 50,
"tag": "EMAIL",
"value": "geordan@gmail.com"
},
{
"context": "osario <geordan@gmail.com>\n https://github.com/geordanr/xwing\n###\nDFL_LANGUAGE = 'English'\n\nbuilders = []",
"end": 100,
"score": 0.9988563656806946,
"start": 92,
"tag": "USERNAME",
"value": "geordanr"
}
] | coffeescripts/translate.coffee | michigun/xwing | 100 | ###
X-Wing Squad Builder
Geordan Rosario <geordan@gmail.com>
https://github.com/geordanr/xwing
###
DFL_LANGUAGE = 'English'
builders = []
exportObj = exports ? this
exportObj.loadCards = (language) ->
exportObj.cardLoaders[language]()
exportObj.translate = (language, category, what, args...) ->
translation = exportObj.translations[language][category][what]
if translation?
if translation instanceof Function
# pass this function in case we need to do further translation inside the function
translation exportObj.translate, language, args...
else
translation
else
what
exportObj.setupTranslationSupport = ->
do (builders) ->
$(exportObj).on 'xwing:languageChanged', (e, language, cb=$.noop) =>
if language of exportObj.translations
$('.language-placeholder').text language
for builder in builders
await builder.container.trigger 'xwing:beforeLanguageLoad', defer()
exportObj.loadCards language
for own selector, html of exportObj.translations[language].byCSSSelector
$(selector).html html
for builder in builders
builder.container.trigger 'xwing:afterLanguageLoad', language
exportObj.loadCards DFL_LANGUAGE
$(exportObj).trigger 'xwing:languageChanged', DFL_LANGUAGE
exportObj.setupTranslationUI = (backend) ->
for language in Object.keys(exportObj.cardLoaders).sort()
li = $ document.createElement 'LI'
li.text language
do (language, backend) ->
li.click (e) ->
backend.set('language', language) if backend?
$(exportObj).trigger 'xwing:languageChanged', language
$('ul.dropdown-menu').append li
exportObj.registerBuilderForTranslation = (builder) ->
builders.push(builder) if builder not in builders
| 224118 | ###
X-Wing Squad Builder
<NAME> <<EMAIL>>
https://github.com/geordanr/xwing
###
DFL_LANGUAGE = 'English'
builders = []
exportObj = exports ? this
exportObj.loadCards = (language) ->
exportObj.cardLoaders[language]()
exportObj.translate = (language, category, what, args...) ->
translation = exportObj.translations[language][category][what]
if translation?
if translation instanceof Function
# pass this function in case we need to do further translation inside the function
translation exportObj.translate, language, args...
else
translation
else
what
exportObj.setupTranslationSupport = ->
do (builders) ->
$(exportObj).on 'xwing:languageChanged', (e, language, cb=$.noop) =>
if language of exportObj.translations
$('.language-placeholder').text language
for builder in builders
await builder.container.trigger 'xwing:beforeLanguageLoad', defer()
exportObj.loadCards language
for own selector, html of exportObj.translations[language].byCSSSelector
$(selector).html html
for builder in builders
builder.container.trigger 'xwing:afterLanguageLoad', language
exportObj.loadCards DFL_LANGUAGE
$(exportObj).trigger 'xwing:languageChanged', DFL_LANGUAGE
exportObj.setupTranslationUI = (backend) ->
for language in Object.keys(exportObj.cardLoaders).sort()
li = $ document.createElement 'LI'
li.text language
do (language, backend) ->
li.click (e) ->
backend.set('language', language) if backend?
$(exportObj).trigger 'xwing:languageChanged', language
$('ul.dropdown-menu').append li
exportObj.registerBuilderForTranslation = (builder) ->
builders.push(builder) if builder not in builders
| true | ###
X-Wing Squad Builder
PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
https://github.com/geordanr/xwing
###
DFL_LANGUAGE = 'English'
builders = []
exportObj = exports ? this
exportObj.loadCards = (language) ->
exportObj.cardLoaders[language]()
exportObj.translate = (language, category, what, args...) ->
translation = exportObj.translations[language][category][what]
if translation?
if translation instanceof Function
# pass this function in case we need to do further translation inside the function
translation exportObj.translate, language, args...
else
translation
else
what
exportObj.setupTranslationSupport = ->
do (builders) ->
$(exportObj).on 'xwing:languageChanged', (e, language, cb=$.noop) =>
if language of exportObj.translations
$('.language-placeholder').text language
for builder in builders
await builder.container.trigger 'xwing:beforeLanguageLoad', defer()
exportObj.loadCards language
for own selector, html of exportObj.translations[language].byCSSSelector
$(selector).html html
for builder in builders
builder.container.trigger 'xwing:afterLanguageLoad', language
exportObj.loadCards DFL_LANGUAGE
$(exportObj).trigger 'xwing:languageChanged', DFL_LANGUAGE
exportObj.setupTranslationUI = (backend) ->
for language in Object.keys(exportObj.cardLoaders).sort()
li = $ document.createElement 'LI'
li.text language
do (language, backend) ->
li.click (e) ->
backend.set('language', language) if backend?
$(exportObj).trigger 'xwing:languageChanged', language
$('ul.dropdown-menu').append li
exportObj.registerBuilderForTranslation = (builder) ->
builders.push(builder) if builder not in builders
|
[
{
"context": "= require 'path'\n\nmodule.exports =\n url: 'http://127.0.0.1:5444'\n database: 'mongodb://localhost:27017/port",
"end": 66,
"score": 0.8288466930389404,
"start": 57,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "l-test'\n port: 5444\n mongo:\n url: 'mongodb://127.0.0.1:27017/portal-test'\n host: '127.0.0.1'\n port",
"end": 176,
"score": 0.9997084736824036,
"start": 167,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "mongodb://127.0.0.1:27017/portal-test'\n host: '127.0.0.1'\n port: 27017\n name: 'porttal'\n token:\n ",
"end": 216,
"score": 0.9997058510780334,
"start": 207,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": ": 27017\n name: 'porttal'\n token:\n secret: 'IhoiUHyu6gtghj'\n\n debug: false\n plugins:\n path: join __dirn",
"end": 290,
"score": 0.9985313415527344,
"start": 276,
"tag": "KEY",
"value": "IhoiUHyu6gtghj"
}
] | server/config/testing.coffee | stevelacy/portal | 0 | {join} = require 'path'
module.exports =
url: 'http://127.0.0.1:5444'
database: 'mongodb://localhost:27017/portal-test'
port: 5444
mongo:
url: 'mongodb://127.0.0.1:27017/portal-test'
host: '127.0.0.1'
port: 27017
name: 'porttal'
token:
secret: 'IhoiUHyu6gtghj'
debug: false
plugins:
path: join __dirname, '../../server/test/fixtures/plugins'
| 106619 | {join} = require 'path'
module.exports =
url: 'http://127.0.0.1:5444'
database: 'mongodb://localhost:27017/portal-test'
port: 5444
mongo:
url: 'mongodb://127.0.0.1:27017/portal-test'
host: '127.0.0.1'
port: 27017
name: 'porttal'
token:
secret: '<KEY>'
debug: false
plugins:
path: join __dirname, '../../server/test/fixtures/plugins'
| true | {join} = require 'path'
module.exports =
url: 'http://127.0.0.1:5444'
database: 'mongodb://localhost:27017/portal-test'
port: 5444
mongo:
url: 'mongodb://127.0.0.1:27017/portal-test'
host: '127.0.0.1'
port: 27017
name: 'porttal'
token:
secret: 'PI:KEY:<KEY>END_PI'
debug: false
plugins:
path: join __dirname, '../../server/test/fixtures/plugins'
|
[
{
"context": "s.ColladaModel extends Entity\n\n\tentity :\n\t\tname: \"ColladaModel\"\n\t\ttype: \"a-collada-model\"\n\n\t# ------------------",
"end": 135,
"score": 0.620562732219696,
"start": 123,
"tag": "NAME",
"value": "ColladaModel"
}
] | src/ColladaModel.coffee | etiennepinchon/hologram | 89 | {Entity} = require "./Entity"
{Events} = require "./Events"
class exports.ColladaModel extends Entity
entity :
name: "ColladaModel"
type: "a-collada-model"
# ----------------------------------------------------------------------------
# PROPERTIES
onLoad : (cb)-> @on Events.ModelLoad, cb
| 55040 | {Entity} = require "./Entity"
{Events} = require "./Events"
class exports.ColladaModel extends Entity
entity :
name: "<NAME>"
type: "a-collada-model"
# ----------------------------------------------------------------------------
# PROPERTIES
onLoad : (cb)-> @on Events.ModelLoad, cb
| true | {Entity} = require "./Entity"
{Events} = require "./Events"
class exports.ColladaModel extends Entity
entity :
name: "PI:NAME:<NAME>END_PI"
type: "a-collada-model"
# ----------------------------------------------------------------------------
# PROPERTIES
onLoad : (cb)-> @on Events.ModelLoad, cb
|
[
{
"context": "# @author mr.doob / http://mrdoob.com/\n# @author alteredq / ht",
"end": 12,
"score": 0.9386895895004272,
"start": 10,
"tag": "USERNAME",
"value": "mr"
},
{
"context": "# @author mr.doob / http://mrdoob.com/\n# @author alteredq / http://",
"end": 17,
"score": 0.7588107585906982,
"start": 13,
"tag": "NAME",
"value": "doob"
},
{
"context": "# @author mr.doob / http://mrdoob.com/\n# @author alteredq / http://alteredqualia.com/\n# @author aladjev.and",
"end": 57,
"score": 0.9988666772842407,
"start": 49,
"tag": "USERNAME",
"value": "alteredq"
},
{
"context": "hor alteredq / http://alteredqualia.com/\n# @author aladjev.andrew@gmail.com\n\n#= require new_src/core/color\n#= require new_src",
"end": 120,
"score": 0.9999134540557861,
"start": 96,
"tag": "EMAIL",
"value": "aladjev.andrew@gmail.com"
}
] | source/javascripts/new_src/core/face_4.coffee | andrew-aladev/three.js | 0 | # @author mr.doob / http://mrdoob.com/
# @author alteredq / http://alteredqualia.com/
# @author aladjev.andrew@gmail.com
#= require new_src/core/color
#= require new_src/core/vector_3
class Face4
constructor: (a, b, c, d, normal, color, materialIndex) ->
@a = a
@b = b
@c = c
@d = d
if normal instanceof THREE.Vector3
@normal = normal
else
@normal = new THREE.Vector3()
if normal instanceof Array
@vertexNormals = normal
else
@vertexNormals = []
if color instanceof THREE.Color
@color = color
else
@color = new THREE.Color()
if color instanceof Array
@vertexColors = color
else
@vertexColors = []
@vertexTangents = []
@materialIndex = materialIndex
@centroid = new THREE.Vector3()
clone: ->
face = new Face4 @a, @b, @c, @d
face.normal.copy @normal
face.color.copy @color
face.centroid.copy @centroid
face.materialIndex = @materialIndex
length = @vertexNormals.length
for i in [0...length]
face.vertexNormals[i] = @vertexNormals[i].clone()
lenght = @vertexColors.length
for i in [0...length]
face.vertexColors[i] = @vertexColors[i].clone()
length = @vertexTangents.length
for i in [0...length]
face.vertexTangents[i] = @vertexTangents[i].clone()
face
namespace "THREE", (exports) ->
exports.Face4 = Face4 | 187991 | # @author mr.<NAME> / http://mrdoob.com/
# @author alteredq / http://alteredqualia.com/
# @author <EMAIL>
#= require new_src/core/color
#= require new_src/core/vector_3
class Face4
constructor: (a, b, c, d, normal, color, materialIndex) ->
@a = a
@b = b
@c = c
@d = d
if normal instanceof THREE.Vector3
@normal = normal
else
@normal = new THREE.Vector3()
if normal instanceof Array
@vertexNormals = normal
else
@vertexNormals = []
if color instanceof THREE.Color
@color = color
else
@color = new THREE.Color()
if color instanceof Array
@vertexColors = color
else
@vertexColors = []
@vertexTangents = []
@materialIndex = materialIndex
@centroid = new THREE.Vector3()
clone: ->
face = new Face4 @a, @b, @c, @d
face.normal.copy @normal
face.color.copy @color
face.centroid.copy @centroid
face.materialIndex = @materialIndex
length = @vertexNormals.length
for i in [0...length]
face.vertexNormals[i] = @vertexNormals[i].clone()
lenght = @vertexColors.length
for i in [0...length]
face.vertexColors[i] = @vertexColors[i].clone()
length = @vertexTangents.length
for i in [0...length]
face.vertexTangents[i] = @vertexTangents[i].clone()
face
namespace "THREE", (exports) ->
exports.Face4 = Face4 | true | # @author mr.PI:NAME:<NAME>END_PI / http://mrdoob.com/
# @author alteredq / http://alteredqualia.com/
# @author PI:EMAIL:<EMAIL>END_PI
#= require new_src/core/color
#= require new_src/core/vector_3
class Face4
constructor: (a, b, c, d, normal, color, materialIndex) ->
@a = a
@b = b
@c = c
@d = d
if normal instanceof THREE.Vector3
@normal = normal
else
@normal = new THREE.Vector3()
if normal instanceof Array
@vertexNormals = normal
else
@vertexNormals = []
if color instanceof THREE.Color
@color = color
else
@color = new THREE.Color()
if color instanceof Array
@vertexColors = color
else
@vertexColors = []
@vertexTangents = []
@materialIndex = materialIndex
@centroid = new THREE.Vector3()
clone: ->
face = new Face4 @a, @b, @c, @d
face.normal.copy @normal
face.color.copy @color
face.centroid.copy @centroid
face.materialIndex = @materialIndex
length = @vertexNormals.length
for i in [0...length]
face.vertexNormals[i] = @vertexNormals[i].clone()
lenght = @vertexColors.length
for i in [0...length]
face.vertexColors[i] = @vertexColors[i].clone()
length = @vertexTangents.length
for i in [0...length]
face.vertexTangents[i] = @vertexTangents[i].clone()
face
namespace "THREE", (exports) ->
exports.Face4 = Face4 |
[
{
"context": ", \"13\", \"2016\"],\n\t\t\t[\"April\", \"14\", \"2017\"],\n\t\t\t[\"May\", \"15\", \"2018\"]\n\t\t]\n\n\t\t@picker = new Layer\n\t\t\tpar",
"end": 2890,
"score": 0.9835489988327026,
"start": 2887,
"tag": "NAME",
"value": "May"
}
] | Controls/Pickers/DatePicker.coffee | Mattlk13/windows-framer-toolkit | 182 | # DatePicker requires these modules. Please include them in your /modules directory
{Type} = require "Type"
{SystemColor} = require "SystemColor"
class exports.DatePicker extends Layer
constructor: (@options={}) ->
@options.header ?= "Control header"
@options.month ?= "January"
@options.date ?= "11"
@options.year ?= "2014"
@options.enabled ?= true
@options.width ?= 296
@options.height ?= 60
@options.backgroundColor ?= SystemColor.transparent
super @options
@createLayers()
@define "header",
get: ->
@options.header
set: (value) ->
@options.header = value
if @container?
@createLayers()
@define "month",
get: ->
@options.month
set: (value) ->
@options.month = value
if @container?
@createLayers()
@define "date",
get: ->
@options.date
set: (value) ->
@options.date = value
if @container?
@createLayers()
@define "year",
get: ->
@options.year
set: (value) ->
@options.year = value
if @container?
@createLayers()
@define "enabled",
get: ->
@options.enabled
set: (value) ->
@options.enabled = value
if @container?
@createLayers()
createLayers: ->
if @container?
@container.destroy()
if @picker?
@picker.destroy()
@container = new Layer
parent: @
name: "Container"
backgroundColor: SystemColor.transparent
width: @options.width
height: @options.height
@headerText = new Type
parent: @container
name: "Header"
text: @options.header
whiteSpace: "nowrap"
padding:
top: 3
bottom: 6
@box = new Layer
parent: @container
name: "Box"
width: @options.width
height: 32
y: @headerText.maxY
backgroundColor: SystemColor.altMediumLow
borderColor: SystemColor.baseMediumLow
borderWidth: 2
@monthText = new Type
parent: @box
name: "Month Text"
textAlign: "center"
x: 2
width: 132
text: @options.month
padding:
top: 4
bottom: 9
@divider1 = new Layer
parent: @box
name: "Divider"
height: @box.height - 4
width: 2
x: @monthText.maxX
backgroundColor: SystemColor.baseLow
@dateText = new Type
parent: @box
name: "Date Text"
textAlign: "center"
width: 78
x: @divider1.maxX
text: @options.date
padding:
top: 4
bottom: 9
@divider2 = new Layer
parent: @box
name: "Divider"
height: @box.height - 4
width: 2
x: @dateText.maxX
backgroundColor: SystemColor.baseLow
@yearText = new Type
parent: @box
name: "Year Text"
textAlign: "center"
width: 78
x: @divider2.maxX
text: @options.year
padding:
top: 4
bottom: 9
datePickerItems = [
["September", "7", "2010"],
["October", "8", "2011"],
["November", "9", "2012"],
["December", "10", "2013"],
["January", "11", "2014"],
["February", "12", "2015"],
["March", "13", "2016"],
["April", "14", "2017"],
["May", "15", "2018"]
]
@picker = new Layer
parent: @
name: "Picker"
width: @box.width
height: (datePickerItems.length - 1) * 44 + 46
backgroundColor: SystemColor.chromeMediumLow
borderColor: SystemColor.chromeHigh
borderWidth: 1
visible: false
clip: true
@picker.centerX()
@picker.centerY(36)
if @picker.screenFrame.y < Framer.Device.screen.y
@picker.y = Framer.Device.screen.y - @container.screenFrame.y
@divider1 = new Layer
parent: @picker
name: "Divider"
width: 2
height: (datePickerItems.length - 1) * 44
backgroundColor: SystemColor.baseLow
x: 135
@divider2 = new Layer
parent: @picker
name: "Divider"
width: 2
height: (datePickerItems.length - 1) * 44
backgroundColor: SystemColor.baseLow
x: 215
@items = new Layer
parent: @picker
name: "Items"
width: @picker.width
height: (datePickerItems.length - 1) * 44
backgroundColor: SystemColor.transparent
clip: true
for i in [0..datePickerItems.length - 1]
itemContainer = new Layer
parent: @items
name: "Item Container"
backgroundColor: SystemColor.transparent
width: @picker.width
height: 44
y: (i * 44) - 22
monthText = new Type
parent: itemContainer
name: "Month Text"
text: datePickerItems[i][0]
width: 134
height: 44
x: 2
textAlign: "center"
padding:
top: 12
bottom: 12
dateText = new Type
parent: itemContainer
name: "Date Text"
text: datePickerItems[i][1]
width: 78
height: 44
textAlign: "center"
x: monthText.maxX + 1
padding:
top: 12
bottom: 12
yearText = new Type
parent: itemContainer
name: "Year Text"
text: datePickerItems[i][2]
width: 80
height: 44
textAlign: "center"
x: dateText.maxX + 1
padding:
top: 12
bottom: 12
if i is 0 or i is datePickerItems.length - 1
monthText.color = dateText.color = yearText.color = SystemColor.baseMediumLow
else if i is 4
monthText.color = dateText.color = yearText.color = SystemColor.baseHigh
itemContainer.backgroundColor = SystemColor.listAccentLow
else
monthText.color = dateText.color = yearText.color = SystemColor.baseMedium
@bottomDivider = new Layer
parent: @picker
name: "Bottom Divider"
width: @picker.width - 2
height: 2
backgroundColor: SystemColor.baseLow
y: (datePickerItems.length - 1) * 44
@bottomButtons = new Layer
parent: @picker
name: "Bottom Buttons"
width: @picker.width - 2
height: 44
backgroundColor: SystemColor.transparent
y: @bottomDivider.maxY
@acceptButton = new Type
parent: @bottomButtons
name: "Accept Button"
text: "\uE0E7"
uwpStyle: "glyph"
fontSize: 16
textAlign: "center"
width: @bottomButtons.width / 2
padding:
top: 14
bottom: 14
@cancelButton = new Type
parent: @bottomButtons
name: "Cancel Button"
text: "\uE10A"
uwpStyle: "glyph"
fontSize: 16
textAlign: "center"
width: @bottomButtons.width / 2
x: @bottomButtons.width / 2
padding:
top: 14
bottom: 14
@updateVisuals()
# EVENTS
@box.onMouseUp ->
@.parent.parent.updateVisuals("mouseup")
@box.onMouseDown ->
@.parent.parent.updateVisuals("mousedown")
@box.onMouseOver ->
@.parent.parent.updateVisuals("mouseover")
@box.onMouseOut ->
@.parent.parent.updateVisuals("mouseout")
@bottomButtons.onClick ->
@.parent.visible = false
updateVisuals: (curEvent) ->
if @options.enabled
dateColor = SystemColor.baseHigh
headerColor = SystemColor.baseHigh
switch curEvent
when "mouseup"
boxBorderColor = SystemColor.baseMedium
boxBackgroundColor = SystemColor.altMedium
@picker.visible = @picker.visible is false ? true : false
when "mousedown"
boxBorderColor = SystemColor.baseMediumLow
boxBackgroundColor = SystemColor.baseLow
when "mouseover"
boxBorderColor = SystemColor.baseMedium
boxBackgroundColor = SystemColor.altMedium
else
boxBorderColor = SystemColor.baseMediumLow
boxBackgroundColor = SystemColor.altMediumLow
else
headerColor = SystemColor.baseMediumLow
dateColor = SystemColor.baseMediumLow
boxBorderColor = SystemColor.transparent
boxBackgroundColor = SystemColor.baseLow
@headerText.color = headerColor
@monthText.color = @dateText.color = @yearText.color = dateColor
@box.backgroundColor = boxBackgroundColor
@box.borderColor = boxBorderColor
| 183558 | # DatePicker requires these modules. Please include them in your /modules directory
{Type} = require "Type"
{SystemColor} = require "SystemColor"
class exports.DatePicker extends Layer
constructor: (@options={}) ->
@options.header ?= "Control header"
@options.month ?= "January"
@options.date ?= "11"
@options.year ?= "2014"
@options.enabled ?= true
@options.width ?= 296
@options.height ?= 60
@options.backgroundColor ?= SystemColor.transparent
super @options
@createLayers()
@define "header",
get: ->
@options.header
set: (value) ->
@options.header = value
if @container?
@createLayers()
@define "month",
get: ->
@options.month
set: (value) ->
@options.month = value
if @container?
@createLayers()
@define "date",
get: ->
@options.date
set: (value) ->
@options.date = value
if @container?
@createLayers()
@define "year",
get: ->
@options.year
set: (value) ->
@options.year = value
if @container?
@createLayers()
@define "enabled",
get: ->
@options.enabled
set: (value) ->
@options.enabled = value
if @container?
@createLayers()
createLayers: ->
if @container?
@container.destroy()
if @picker?
@picker.destroy()
@container = new Layer
parent: @
name: "Container"
backgroundColor: SystemColor.transparent
width: @options.width
height: @options.height
@headerText = new Type
parent: @container
name: "Header"
text: @options.header
whiteSpace: "nowrap"
padding:
top: 3
bottom: 6
@box = new Layer
parent: @container
name: "Box"
width: @options.width
height: 32
y: @headerText.maxY
backgroundColor: SystemColor.altMediumLow
borderColor: SystemColor.baseMediumLow
borderWidth: 2
@monthText = new Type
parent: @box
name: "Month Text"
textAlign: "center"
x: 2
width: 132
text: @options.month
padding:
top: 4
bottom: 9
@divider1 = new Layer
parent: @box
name: "Divider"
height: @box.height - 4
width: 2
x: @monthText.maxX
backgroundColor: SystemColor.baseLow
@dateText = new Type
parent: @box
name: "Date Text"
textAlign: "center"
width: 78
x: @divider1.maxX
text: @options.date
padding:
top: 4
bottom: 9
@divider2 = new Layer
parent: @box
name: "Divider"
height: @box.height - 4
width: 2
x: @dateText.maxX
backgroundColor: SystemColor.baseLow
@yearText = new Type
parent: @box
name: "Year Text"
textAlign: "center"
width: 78
x: @divider2.maxX
text: @options.year
padding:
top: 4
bottom: 9
datePickerItems = [
["September", "7", "2010"],
["October", "8", "2011"],
["November", "9", "2012"],
["December", "10", "2013"],
["January", "11", "2014"],
["February", "12", "2015"],
["March", "13", "2016"],
["April", "14", "2017"],
["<NAME>", "15", "2018"]
]
@picker = new Layer
parent: @
name: "Picker"
width: @box.width
height: (datePickerItems.length - 1) * 44 + 46
backgroundColor: SystemColor.chromeMediumLow
borderColor: SystemColor.chromeHigh
borderWidth: 1
visible: false
clip: true
@picker.centerX()
@picker.centerY(36)
if @picker.screenFrame.y < Framer.Device.screen.y
@picker.y = Framer.Device.screen.y - @container.screenFrame.y
@divider1 = new Layer
parent: @picker
name: "Divider"
width: 2
height: (datePickerItems.length - 1) * 44
backgroundColor: SystemColor.baseLow
x: 135
@divider2 = new Layer
parent: @picker
name: "Divider"
width: 2
height: (datePickerItems.length - 1) * 44
backgroundColor: SystemColor.baseLow
x: 215
@items = new Layer
parent: @picker
name: "Items"
width: @picker.width
height: (datePickerItems.length - 1) * 44
backgroundColor: SystemColor.transparent
clip: true
for i in [0..datePickerItems.length - 1]
itemContainer = new Layer
parent: @items
name: "Item Container"
backgroundColor: SystemColor.transparent
width: @picker.width
height: 44
y: (i * 44) - 22
monthText = new Type
parent: itemContainer
name: "Month Text"
text: datePickerItems[i][0]
width: 134
height: 44
x: 2
textAlign: "center"
padding:
top: 12
bottom: 12
dateText = new Type
parent: itemContainer
name: "Date Text"
text: datePickerItems[i][1]
width: 78
height: 44
textAlign: "center"
x: monthText.maxX + 1
padding:
top: 12
bottom: 12
yearText = new Type
parent: itemContainer
name: "Year Text"
text: datePickerItems[i][2]
width: 80
height: 44
textAlign: "center"
x: dateText.maxX + 1
padding:
top: 12
bottom: 12
if i is 0 or i is datePickerItems.length - 1
monthText.color = dateText.color = yearText.color = SystemColor.baseMediumLow
else if i is 4
monthText.color = dateText.color = yearText.color = SystemColor.baseHigh
itemContainer.backgroundColor = SystemColor.listAccentLow
else
monthText.color = dateText.color = yearText.color = SystemColor.baseMedium
@bottomDivider = new Layer
parent: @picker
name: "Bottom Divider"
width: @picker.width - 2
height: 2
backgroundColor: SystemColor.baseLow
y: (datePickerItems.length - 1) * 44
@bottomButtons = new Layer
parent: @picker
name: "Bottom Buttons"
width: @picker.width - 2
height: 44
backgroundColor: SystemColor.transparent
y: @bottomDivider.maxY
@acceptButton = new Type
parent: @bottomButtons
name: "Accept Button"
text: "\uE0E7"
uwpStyle: "glyph"
fontSize: 16
textAlign: "center"
width: @bottomButtons.width / 2
padding:
top: 14
bottom: 14
@cancelButton = new Type
parent: @bottomButtons
name: "Cancel Button"
text: "\uE10A"
uwpStyle: "glyph"
fontSize: 16
textAlign: "center"
width: @bottomButtons.width / 2
x: @bottomButtons.width / 2
padding:
top: 14
bottom: 14
@updateVisuals()
# EVENTS
@box.onMouseUp ->
@.parent.parent.updateVisuals("mouseup")
@box.onMouseDown ->
@.parent.parent.updateVisuals("mousedown")
@box.onMouseOver ->
@.parent.parent.updateVisuals("mouseover")
@box.onMouseOut ->
@.parent.parent.updateVisuals("mouseout")
@bottomButtons.onClick ->
@.parent.visible = false
updateVisuals: (curEvent) ->
if @options.enabled
dateColor = SystemColor.baseHigh
headerColor = SystemColor.baseHigh
switch curEvent
when "mouseup"
boxBorderColor = SystemColor.baseMedium
boxBackgroundColor = SystemColor.altMedium
@picker.visible = @picker.visible is false ? true : false
when "mousedown"
boxBorderColor = SystemColor.baseMediumLow
boxBackgroundColor = SystemColor.baseLow
when "mouseover"
boxBorderColor = SystemColor.baseMedium
boxBackgroundColor = SystemColor.altMedium
else
boxBorderColor = SystemColor.baseMediumLow
boxBackgroundColor = SystemColor.altMediumLow
else
headerColor = SystemColor.baseMediumLow
dateColor = SystemColor.baseMediumLow
boxBorderColor = SystemColor.transparent
boxBackgroundColor = SystemColor.baseLow
@headerText.color = headerColor
@monthText.color = @dateText.color = @yearText.color = dateColor
@box.backgroundColor = boxBackgroundColor
@box.borderColor = boxBorderColor
| true | # DatePicker requires these modules. Please include them in your /modules directory
{Type} = require "Type"
{SystemColor} = require "SystemColor"
class exports.DatePicker extends Layer
constructor: (@options={}) ->
@options.header ?= "Control header"
@options.month ?= "January"
@options.date ?= "11"
@options.year ?= "2014"
@options.enabled ?= true
@options.width ?= 296
@options.height ?= 60
@options.backgroundColor ?= SystemColor.transparent
super @options
@createLayers()
@define "header",
get: ->
@options.header
set: (value) ->
@options.header = value
if @container?
@createLayers()
@define "month",
get: ->
@options.month
set: (value) ->
@options.month = value
if @container?
@createLayers()
@define "date",
get: ->
@options.date
set: (value) ->
@options.date = value
if @container?
@createLayers()
@define "year",
get: ->
@options.year
set: (value) ->
@options.year = value
if @container?
@createLayers()
@define "enabled",
get: ->
@options.enabled
set: (value) ->
@options.enabled = value
if @container?
@createLayers()
createLayers: ->
if @container?
@container.destroy()
if @picker?
@picker.destroy()
@container = new Layer
parent: @
name: "Container"
backgroundColor: SystemColor.transparent
width: @options.width
height: @options.height
@headerText = new Type
parent: @container
name: "Header"
text: @options.header
whiteSpace: "nowrap"
padding:
top: 3
bottom: 6
@box = new Layer
parent: @container
name: "Box"
width: @options.width
height: 32
y: @headerText.maxY
backgroundColor: SystemColor.altMediumLow
borderColor: SystemColor.baseMediumLow
borderWidth: 2
@monthText = new Type
parent: @box
name: "Month Text"
textAlign: "center"
x: 2
width: 132
text: @options.month
padding:
top: 4
bottom: 9
@divider1 = new Layer
parent: @box
name: "Divider"
height: @box.height - 4
width: 2
x: @monthText.maxX
backgroundColor: SystemColor.baseLow
@dateText = new Type
parent: @box
name: "Date Text"
textAlign: "center"
width: 78
x: @divider1.maxX
text: @options.date
padding:
top: 4
bottom: 9
@divider2 = new Layer
parent: @box
name: "Divider"
height: @box.height - 4
width: 2
x: @dateText.maxX
backgroundColor: SystemColor.baseLow
@yearText = new Type
parent: @box
name: "Year Text"
textAlign: "center"
width: 78
x: @divider2.maxX
text: @options.year
padding:
top: 4
bottom: 9
datePickerItems = [
["September", "7", "2010"],
["October", "8", "2011"],
["November", "9", "2012"],
["December", "10", "2013"],
["January", "11", "2014"],
["February", "12", "2015"],
["March", "13", "2016"],
["April", "14", "2017"],
["PI:NAME:<NAME>END_PI", "15", "2018"]
]
@picker = new Layer
parent: @
name: "Picker"
width: @box.width
height: (datePickerItems.length - 1) * 44 + 46
backgroundColor: SystemColor.chromeMediumLow
borderColor: SystemColor.chromeHigh
borderWidth: 1
visible: false
clip: true
@picker.centerX()
@picker.centerY(36)
if @picker.screenFrame.y < Framer.Device.screen.y
@picker.y = Framer.Device.screen.y - @container.screenFrame.y
@divider1 = new Layer
parent: @picker
name: "Divider"
width: 2
height: (datePickerItems.length - 1) * 44
backgroundColor: SystemColor.baseLow
x: 135
@divider2 = new Layer
parent: @picker
name: "Divider"
width: 2
height: (datePickerItems.length - 1) * 44
backgroundColor: SystemColor.baseLow
x: 215
@items = new Layer
parent: @picker
name: "Items"
width: @picker.width
height: (datePickerItems.length - 1) * 44
backgroundColor: SystemColor.transparent
clip: true
for i in [0..datePickerItems.length - 1]
itemContainer = new Layer
parent: @items
name: "Item Container"
backgroundColor: SystemColor.transparent
width: @picker.width
height: 44
y: (i * 44) - 22
monthText = new Type
parent: itemContainer
name: "Month Text"
text: datePickerItems[i][0]
width: 134
height: 44
x: 2
textAlign: "center"
padding:
top: 12
bottom: 12
dateText = new Type
parent: itemContainer
name: "Date Text"
text: datePickerItems[i][1]
width: 78
height: 44
textAlign: "center"
x: monthText.maxX + 1
padding:
top: 12
bottom: 12
yearText = new Type
parent: itemContainer
name: "Year Text"
text: datePickerItems[i][2]
width: 80
height: 44
textAlign: "center"
x: dateText.maxX + 1
padding:
top: 12
bottom: 12
if i is 0 or i is datePickerItems.length - 1
monthText.color = dateText.color = yearText.color = SystemColor.baseMediumLow
else if i is 4
monthText.color = dateText.color = yearText.color = SystemColor.baseHigh
itemContainer.backgroundColor = SystemColor.listAccentLow
else
monthText.color = dateText.color = yearText.color = SystemColor.baseMedium
@bottomDivider = new Layer
parent: @picker
name: "Bottom Divider"
width: @picker.width - 2
height: 2
backgroundColor: SystemColor.baseLow
y: (datePickerItems.length - 1) * 44
@bottomButtons = new Layer
parent: @picker
name: "Bottom Buttons"
width: @picker.width - 2
height: 44
backgroundColor: SystemColor.transparent
y: @bottomDivider.maxY
@acceptButton = new Type
parent: @bottomButtons
name: "Accept Button"
text: "\uE0E7"
uwpStyle: "glyph"
fontSize: 16
textAlign: "center"
width: @bottomButtons.width / 2
padding:
top: 14
bottom: 14
@cancelButton = new Type
parent: @bottomButtons
name: "Cancel Button"
text: "\uE10A"
uwpStyle: "glyph"
fontSize: 16
textAlign: "center"
width: @bottomButtons.width / 2
x: @bottomButtons.width / 2
padding:
top: 14
bottom: 14
@updateVisuals()
# EVENTS
@box.onMouseUp ->
@.parent.parent.updateVisuals("mouseup")
@box.onMouseDown ->
@.parent.parent.updateVisuals("mousedown")
@box.onMouseOver ->
@.parent.parent.updateVisuals("mouseover")
@box.onMouseOut ->
@.parent.parent.updateVisuals("mouseout")
@bottomButtons.onClick ->
@.parent.visible = false
updateVisuals: (curEvent) ->
if @options.enabled
dateColor = SystemColor.baseHigh
headerColor = SystemColor.baseHigh
switch curEvent
when "mouseup"
boxBorderColor = SystemColor.baseMedium
boxBackgroundColor = SystemColor.altMedium
@picker.visible = @picker.visible is false ? true : false
when "mousedown"
boxBorderColor = SystemColor.baseMediumLow
boxBackgroundColor = SystemColor.baseLow
when "mouseover"
boxBorderColor = SystemColor.baseMedium
boxBackgroundColor = SystemColor.altMedium
else
boxBorderColor = SystemColor.baseMediumLow
boxBackgroundColor = SystemColor.altMediumLow
else
headerColor = SystemColor.baseMediumLow
dateColor = SystemColor.baseMediumLow
boxBorderColor = SystemColor.transparent
boxBackgroundColor = SystemColor.baseLow
@headerText.color = headerColor
@monthText.color = @dateText.color = @yearText.color = dateColor
@box.backgroundColor = boxBackgroundColor
@box.borderColor = boxBorderColor
|
[
{
"context": "ned in this module is based\n# on code developed by Nicolas Rougier as part of the Glumpy and Vispy projects.\n# The a",
"end": 282,
"score": 0.9998921751976013,
"start": 267,
"tag": "NAME",
"value": "Nicolas Rougier"
}
] | bokehjs/src/coffee/renderer/glyph/bokehgl.coffee | rothnic/bokeh | 1 | if global._bokehTest?
gloo2 = undefined # TODO Make work?
else
gloo2 = require "gloo2"
color = require "../../common/color"
color2rgba = color.color2rgba
# Copyright notice: many of the awesome GLSL code contained in this module is based
# on code developed by Nicolas Rougier as part of the Glumpy and Vispy projects.
# The algorithms are published in http://jcgt.org/published/0003/04/01/
# This module contains all gl-specific code to add gl support for the glyphs.
# By implementing it separetely, the GL functionality can be spun off in a
# separate library.
# Other locations where we work with GL, or prepare for GL-rendering:
# - plot.coffee
# - glyph.coffee
# - glyph_renderer.coffee
# - a few lines in each glyph-module that supports WebGL
line_width = (width) ->
# Increase small values to make it more similar to canvas
if width < 2
width = Math.sqrt(width*2)
return width
fill_array_with_float = (n, val) ->
a = new Float32Array(n)
for i in [0...n]
a[i] = val
return a
fill_array_with_vec = (n, m, val) ->
a = new Float32Array(n*m)
for i in [0...n]
for j in [0...m]
a[i*m+j] = val[j]
return a
attach_float = (prog, vbo, att_name, n, visual, name) ->
# Attach a float attribute to the program. Use singleton value if we can,
# otherwise use VBO to apply array.
vbo.used = true
if visual[name].fixed_value?
prog.set_attribute(att_name, 'float', null, visual[name].fixed_value)
vbo.used = false
else
a = new Float32Array(visual.cache[name + '_array'])
vbo.set_size(n*4)
vbo.set_data(0, a)
prog.set_attribute(att_name, 'float', [vbo, 0, 0])
return a
attach_color = (prog, vbo, att_name, n, visual) ->
# Attach the color attribute to the program. If there's just one color,
# then use this single color for all vertices (no VBO). Otherwise we
# create an array and upload that to the VBO, which we attahce to the prog.
m = 4
vbo.used = true
if visual.color.fixed_value? and visual.alpha.fixed_value?
rgba = color2rgba(visual.color.fixed_value, visual.alpha.fixed_value)
prog.set_attribute(att_name, 'vec4', null, rgba)
vbo.used = false
else
# Get array of colors
if visual.color.fixed_value?
colors = (visual.color.fixed_value for i in [0...n])
else
colors = visual.cache.color_array
# Get array of alphas
if visual.alpha.fixed_value?
alphas = fill_array_with_float(n, visual.alpha.fixed_value)
else
alphas = visual.cache.alpha_array
# Get array of rgbs
a = new Float32Array(n*m)
for i in [0...n]
rgba = color2rgba(colors[i], alphas[i])
for j in [0...m]
a[i*m+j] = rgba[j]
# Attach vbo
vbo.set_size(n*m*4)
vbo.set_data(0, a)
prog.set_attribute(att_name, 'vec4', [vbo, 0, 0])
return a
class BaseGLGlyph
GLYPH: '' # name of the glyph that this gl-glyph applies to
VERT: ''
FRAG: ''
constructor: (gl, glyph) ->
@gl = gl
@glyph = glyph
@nvertices = 0
@size_changed = false
@data_changed = false
@visuals_changed = false
@init()
set_data_changed: (n) ->
if n != @nvertices
@nvertices = n
@size_changed = true
@data_changed = true
set_visuals_changed: () ->
@visuals_changed = true
class LineGLGlyph extends BaseGLGlyph
GLYPH: 'line'
VERT: 'xxx'
FRAG: 'xxx'
class MarkerGLGlyph extends BaseGLGlyph
# Base class for markers. All markers share the same GLSL, except for one
# function that defines the marker geometry.
VERT: """
precision mediump float;
const float SQRT_2 = 1.4142135623730951;
//
uniform vec2 u_canvas_size;
uniform vec2 u_offset;
uniform vec2 u_scale;
uniform float u_antialias;
//
attribute float a_x;
attribute float a_y;
attribute float a_size;
attribute float a_angle; // in radians
attribute float a_linewidth;
attribute vec4 a_fg_color;
attribute vec4 a_bg_color;
//
varying float v_linewidth;
varying float v_size;
varying vec4 v_fg_color;
varying vec4 v_bg_color;
varying vec2 v_rotation;
void main (void)
{
v_size = a_size;
v_linewidth = a_linewidth;
v_fg_color = a_fg_color;
v_bg_color = a_bg_color;
v_rotation = vec2(cos(-a_angle), sin(-a_angle));
// Calculate position - the -0.5 is to correct for canvas origin
vec2 pos = vec2(a_x, a_y) * u_scale + u_offset - vec2(0.5, 0.5); // in pixels
pos /= u_canvas_size; // in 0..1
gl_Position = vec4(pos*2.0-1.0, 0.0, 1.0);
gl_Position.y *= -1.0;
gl_PointSize = SQRT_2 * v_size + 2.0 * (a_linewidth + 1.5*u_antialias);
}
"""
FRAG: """
precision mediump float;
const float SQRT_2 = 1.4142135623730951;
const float PI = 3.14159265358979323846264;
//
uniform float u_antialias;
//
varying vec4 v_fg_color;
varying vec4 v_bg_color;
varying float v_linewidth;
varying float v_size;
varying vec2 v_rotation;
MARKERCODE
vec4 outline(float distance, float linewidth, float antialias, vec4 fg_color, vec4 bg_color)
{
vec4 frag_color;
float t = linewidth/2.0 - antialias;
float signed_distance = distance;
float border_distance = abs(signed_distance) - t;
float alpha = border_distance/antialias;
alpha = exp(-alpha*alpha);
// If fg alpha is zero, it probably means no outline. To avoid a dark outline
// shining through due to aa, we set the fg color to the bg color. Avoid if (i.e. branching).
float select = float(bool(fg_color.a));
fg_color.rgb = select * fg_color.rgb + (1.0 - select) * bg_color.rgb;
// Similarly, if we want a transparent bg
select = float(bool(bg_color.a));
bg_color.rgb = select * bg_color.rgb + (1.0 - select) * fg_color.rgb;
if( border_distance < 0.0)
frag_color = fg_color;
else if( signed_distance < 0.0 ) {
frag_color = mix(bg_color, fg_color, sqrt(alpha));
} else {
if( abs(signed_distance) < (linewidth/2.0 + antialias) ) {
frag_color = vec4(fg_color.rgb, fg_color.a * alpha);
} else {
discard;
}
}
return frag_color;
}
void main()
{
vec2 P = gl_PointCoord.xy - vec2(0.5, 0.5);
P = vec2(v_rotation.x*P.x - v_rotation.y*P.y,
v_rotation.y*P.x + v_rotation.x*P.y);
float point_size = SQRT_2*v_size + 2.0 * (v_linewidth + 1.5*u_antialias);
float distance = marker(P*point_size, v_size);
gl_FragColor = outline(distance, v_linewidth, u_antialias, v_fg_color, v_bg_color);
//gl_FragColor.rgb *= gl_FragColor.a; // pre-multiply alpha
}
"""
MARKERCODE: "<defined in subclasses>"
init: () ->
gl = @gl
frag = @FRAG.replace /MARKERCODE/, @MARKERCODE
@last_trans = {} # Keep track of transform
# The program
@prog = new gloo2.Program(gl)
@prog.set_shaders(@VERT, frag)
@vbo_x = new gloo2.VertexBuffer(gl)
# Real attributes
@prog.set_attribute('a_x', 'float', [@vbo_x, 0, 0])
@vbo_y = new gloo2.VertexBuffer(gl)
@prog.set_attribute('a_y', 'float', [@vbo_y, 0, 0])
@vbo_s = new gloo2.VertexBuffer(gl)
@prog.set_attribute('a_size', 'float', [@vbo_s, 0, 0])
@vbo_a = new gloo2.VertexBuffer(gl)
@prog.set_attribute('a_angle', 'float', [@vbo_a, 0, 0])
# VBO's for attributes (they may not be used if value is singleton)
@vbo_linewidth = new gloo2.VertexBuffer(gl)
@vbo_fg_color = new gloo2.VertexBuffer(gl)
@vbo_bg_color = new gloo2.VertexBuffer(gl)
@index_buffer = new gloo2.IndexBuffer(gl)
draw: (indices, mainGlyph, trans) ->
# The main glyph has the data, *this* glyph has the visuals.
nvertices = mainGlyph.glglyph.nvertices
# Upload data if we must. Only happens for main glyph.
if @data_changed
@_set_data(nvertices)
@data_changed = false
else if @glyph.radius? and (trans.sx != @last_trans.sx or trans.sy != @last_trans.sy)
# Keep screen radius up-to-date for circle glyph. Only happens when a radius is given
@last_trans = trans
@vbo_s.set_data(0, new Float32Array((s*2 for s in @glyph.sradius)))
# Update visuals if we must. Can happen for all glyphs.
if @visuals_changed
@_set_visuals(nvertices)
@visuals_changed = false
# Handle transformation to device coordinates
@prog.set_uniform('u_canvas_size', 'vec2', [trans.width, trans.height])
@prog.set_uniform('u_offset', 'vec2', [trans.dx[0], trans.dy[0]])
@prog.set_uniform('u_scale', 'vec2', [trans.sx, trans.sy])
# Select buffers from main glyph
# (which may be this glyph but maybe not if this is a (non)selection glyph)
@prog.set_attribute('a_x', 'float', [mainGlyph.glglyph.vbo_x, 0, 0])
@prog.set_attribute('a_y', 'float', [mainGlyph.glglyph.vbo_y, 0, 0])
@prog.set_attribute('a_size', 'float', [mainGlyph.glglyph.vbo_s, 0, 0])
@prog.set_attribute('a_angle', 'float', [mainGlyph.glglyph.vbo_a, 0, 0])
# Draw directly or using indices. Do not handle indices if they do not
# fit in a uint16; WebGL 1.0 does not support uint32.
if indices.length == 0
return
else if indices.length == nvertices
@prog.draw(@gl.POINTS, [0, nvertices])
else if nvertices < 65535
@index_buffer.set_size(indices.length*2)
@index_buffer.set_data(0, new Uint16Array(indices))
@prog.draw(@gl.POINTS, @index_buffer)
else
# Work around the limit that the indexbuffer must be uint16. We draw in chunks.
# First collect indices in chunks
chunksize = 64000 # 65536
chunks = []
for i in [0...Math.ceil(nvertices/chunksize)]
chunks.push([])
for i in [0...indices.length]
uint16_index = indices[i] % chunksize
chunk = Math.floor(indices[i] / chunksize)
chunks[chunk].push(uint16_index)
# Then draw each chunk
for chunk in [0...chunks.length]
these_indices = new Uint16Array(chunks[chunk])
offset = chunk * chunksize * 4
if these_indices.length == 0
continue
@prog.set_attribute('a_x', 'float', [mainGlyph.glglyph.vbo_x, 0, offset])
@prog.set_attribute('a_y', 'float', [mainGlyph.glglyph.vbo_y, 0, offset])
@prog.set_attribute('a_size', 'float', [mainGlyph.glglyph.vbo_s, 0, offset])
@prog.set_attribute('a_angle', 'float', [mainGlyph.glglyph.vbo_a, 0, offset])
if @vbo_linewidth.used
@prog.set_attribute('a_linewidth', 'float', [@vbo_linewidth, 0, offset])
if @vbo_fg_color.used
@prog.set_attribute('a_fg_color', 'vec4', [@vbo_fg_color, 0, offset * 4])
if @vbo_bg_color.used
@prog.set_attribute('a_bg_color', 'vec4', [@vbo_bg_color, 0, offset * 4])
# The actual drawing
@index_buffer.set_size(these_indices.length*2)
@index_buffer.set_data(0, these_indices)
@prog.draw(@gl.POINTS, @index_buffer)
_set_data: (nvertices) ->
n = nvertices * 4 # in bytes
# Set buffer size
@vbo_x.set_size(n)
@vbo_y.set_size(n)
@vbo_a.set_size(n)
@vbo_s.set_size(n)
# Upload data for x and y
@vbo_x.set_data(0, new Float32Array(@glyph.x))
@vbo_y.set_data(0, new Float32Array(@glyph.y))
# Angle if available; circle does not have angle. If we don't set data, angle is default 0 in glsl
if @glyph.angle?
@vbo_a.set_data(0, new Float32Array(@glyph.angle))
# Radius is special; some markes allow radius in data-coords instead of screen coords
# @radius tells us that radius is in units, sradius is the pre-calculated screen radius
if @glyph.radius?
@vbo_s.set_data(0, new Float32Array((s*2 for s in @glyph.sradius)))
else
@vbo_s.set_data(0, new Float32Array(@glyph.size))
_set_visuals: (nvertices) ->
attach_float(@prog, @vbo_linewidth, 'a_linewidth', nvertices, @glyph.visuals.line, 'width')
attach_color(@prog, @vbo_fg_color, 'a_fg_color', nvertices, @glyph.visuals.line)
attach_color(@prog, @vbo_bg_color, 'a_bg_color', nvertices, @glyph.visuals.fill)
# Static value for antialias. Smaller aa-region to obtain crisper images
@prog.set_uniform('u_antialias', 'float', [0.9])
class CircleGLGlyph extends MarkerGLGlyph
GLYPH: 'circle'
MARKERCODE: """
// --- disc
float marker(vec2 P, float size)
{
return length(P) - size/2.0;
}
"""
class SquareGLGlyph extends MarkerGLGlyph
GLYPH: 'square'
MARKERCODE: """
// --- square
float marker(vec2 P, float size)
{
return max(abs(P.x), abs(P.y)) - size/2.0;
}
"""
module.exports =
CircleGLGlyph: CircleGLGlyph
SquareGLGlyph: SquareGLGlyph
| 46019 | if global._bokehTest?
gloo2 = undefined # TODO Make work?
else
gloo2 = require "gloo2"
color = require "../../common/color"
color2rgba = color.color2rgba
# Copyright notice: many of the awesome GLSL code contained in this module is based
# on code developed by <NAME> as part of the Glumpy and Vispy projects.
# The algorithms are published in http://jcgt.org/published/0003/04/01/
# This module contains all gl-specific code to add gl support for the glyphs.
# By implementing it separetely, the GL functionality can be spun off in a
# separate library.
# Other locations where we work with GL, or prepare for GL-rendering:
# - plot.coffee
# - glyph.coffee
# - glyph_renderer.coffee
# - a few lines in each glyph-module that supports WebGL
line_width = (width) ->
# Increase small values to make it more similar to canvas
if width < 2
width = Math.sqrt(width*2)
return width
fill_array_with_float = (n, val) ->
a = new Float32Array(n)
for i in [0...n]
a[i] = val
return a
fill_array_with_vec = (n, m, val) ->
a = new Float32Array(n*m)
for i in [0...n]
for j in [0...m]
a[i*m+j] = val[j]
return a
attach_float = (prog, vbo, att_name, n, visual, name) ->
# Attach a float attribute to the program. Use singleton value if we can,
# otherwise use VBO to apply array.
vbo.used = true
if visual[name].fixed_value?
prog.set_attribute(att_name, 'float', null, visual[name].fixed_value)
vbo.used = false
else
a = new Float32Array(visual.cache[name + '_array'])
vbo.set_size(n*4)
vbo.set_data(0, a)
prog.set_attribute(att_name, 'float', [vbo, 0, 0])
return a
attach_color = (prog, vbo, att_name, n, visual) ->
# Attach the color attribute to the program. If there's just one color,
# then use this single color for all vertices (no VBO). Otherwise we
# create an array and upload that to the VBO, which we attahce to the prog.
m = 4
vbo.used = true
if visual.color.fixed_value? and visual.alpha.fixed_value?
rgba = color2rgba(visual.color.fixed_value, visual.alpha.fixed_value)
prog.set_attribute(att_name, 'vec4', null, rgba)
vbo.used = false
else
# Get array of colors
if visual.color.fixed_value?
colors = (visual.color.fixed_value for i in [0...n])
else
colors = visual.cache.color_array
# Get array of alphas
if visual.alpha.fixed_value?
alphas = fill_array_with_float(n, visual.alpha.fixed_value)
else
alphas = visual.cache.alpha_array
# Get array of rgbs
a = new Float32Array(n*m)
for i in [0...n]
rgba = color2rgba(colors[i], alphas[i])
for j in [0...m]
a[i*m+j] = rgba[j]
# Attach vbo
vbo.set_size(n*m*4)
vbo.set_data(0, a)
prog.set_attribute(att_name, 'vec4', [vbo, 0, 0])
return a
class BaseGLGlyph
GLYPH: '' # name of the glyph that this gl-glyph applies to
VERT: ''
FRAG: ''
constructor: (gl, glyph) ->
@gl = gl
@glyph = glyph
@nvertices = 0
@size_changed = false
@data_changed = false
@visuals_changed = false
@init()
set_data_changed: (n) ->
if n != @nvertices
@nvertices = n
@size_changed = true
@data_changed = true
set_visuals_changed: () ->
@visuals_changed = true
class LineGLGlyph extends BaseGLGlyph
GLYPH: 'line'
VERT: 'xxx'
FRAG: 'xxx'
class MarkerGLGlyph extends BaseGLGlyph
# Base class for markers. All markers share the same GLSL, except for one
# function that defines the marker geometry.
VERT: """
precision mediump float;
const float SQRT_2 = 1.4142135623730951;
//
uniform vec2 u_canvas_size;
uniform vec2 u_offset;
uniform vec2 u_scale;
uniform float u_antialias;
//
attribute float a_x;
attribute float a_y;
attribute float a_size;
attribute float a_angle; // in radians
attribute float a_linewidth;
attribute vec4 a_fg_color;
attribute vec4 a_bg_color;
//
varying float v_linewidth;
varying float v_size;
varying vec4 v_fg_color;
varying vec4 v_bg_color;
varying vec2 v_rotation;
void main (void)
{
v_size = a_size;
v_linewidth = a_linewidth;
v_fg_color = a_fg_color;
v_bg_color = a_bg_color;
v_rotation = vec2(cos(-a_angle), sin(-a_angle));
// Calculate position - the -0.5 is to correct for canvas origin
vec2 pos = vec2(a_x, a_y) * u_scale + u_offset - vec2(0.5, 0.5); // in pixels
pos /= u_canvas_size; // in 0..1
gl_Position = vec4(pos*2.0-1.0, 0.0, 1.0);
gl_Position.y *= -1.0;
gl_PointSize = SQRT_2 * v_size + 2.0 * (a_linewidth + 1.5*u_antialias);
}
"""
FRAG: """
precision mediump float;
const float SQRT_2 = 1.4142135623730951;
const float PI = 3.14159265358979323846264;
//
uniform float u_antialias;
//
varying vec4 v_fg_color;
varying vec4 v_bg_color;
varying float v_linewidth;
varying float v_size;
varying vec2 v_rotation;
MARKERCODE
vec4 outline(float distance, float linewidth, float antialias, vec4 fg_color, vec4 bg_color)
{
vec4 frag_color;
float t = linewidth/2.0 - antialias;
float signed_distance = distance;
float border_distance = abs(signed_distance) - t;
float alpha = border_distance/antialias;
alpha = exp(-alpha*alpha);
// If fg alpha is zero, it probably means no outline. To avoid a dark outline
// shining through due to aa, we set the fg color to the bg color. Avoid if (i.e. branching).
float select = float(bool(fg_color.a));
fg_color.rgb = select * fg_color.rgb + (1.0 - select) * bg_color.rgb;
// Similarly, if we want a transparent bg
select = float(bool(bg_color.a));
bg_color.rgb = select * bg_color.rgb + (1.0 - select) * fg_color.rgb;
if( border_distance < 0.0)
frag_color = fg_color;
else if( signed_distance < 0.0 ) {
frag_color = mix(bg_color, fg_color, sqrt(alpha));
} else {
if( abs(signed_distance) < (linewidth/2.0 + antialias) ) {
frag_color = vec4(fg_color.rgb, fg_color.a * alpha);
} else {
discard;
}
}
return frag_color;
}
void main()
{
vec2 P = gl_PointCoord.xy - vec2(0.5, 0.5);
P = vec2(v_rotation.x*P.x - v_rotation.y*P.y,
v_rotation.y*P.x + v_rotation.x*P.y);
float point_size = SQRT_2*v_size + 2.0 * (v_linewidth + 1.5*u_antialias);
float distance = marker(P*point_size, v_size);
gl_FragColor = outline(distance, v_linewidth, u_antialias, v_fg_color, v_bg_color);
//gl_FragColor.rgb *= gl_FragColor.a; // pre-multiply alpha
}
"""
MARKERCODE: "<defined in subclasses>"
init: () ->
gl = @gl
frag = @FRAG.replace /MARKERCODE/, @MARKERCODE
@last_trans = {} # Keep track of transform
# The program
@prog = new gloo2.Program(gl)
@prog.set_shaders(@VERT, frag)
@vbo_x = new gloo2.VertexBuffer(gl)
# Real attributes
@prog.set_attribute('a_x', 'float', [@vbo_x, 0, 0])
@vbo_y = new gloo2.VertexBuffer(gl)
@prog.set_attribute('a_y', 'float', [@vbo_y, 0, 0])
@vbo_s = new gloo2.VertexBuffer(gl)
@prog.set_attribute('a_size', 'float', [@vbo_s, 0, 0])
@vbo_a = new gloo2.VertexBuffer(gl)
@prog.set_attribute('a_angle', 'float', [@vbo_a, 0, 0])
# VBO's for attributes (they may not be used if value is singleton)
@vbo_linewidth = new gloo2.VertexBuffer(gl)
@vbo_fg_color = new gloo2.VertexBuffer(gl)
@vbo_bg_color = new gloo2.VertexBuffer(gl)
@index_buffer = new gloo2.IndexBuffer(gl)
draw: (indices, mainGlyph, trans) ->
# The main glyph has the data, *this* glyph has the visuals.
nvertices = mainGlyph.glglyph.nvertices
# Upload data if we must. Only happens for main glyph.
if @data_changed
@_set_data(nvertices)
@data_changed = false
else if @glyph.radius? and (trans.sx != @last_trans.sx or trans.sy != @last_trans.sy)
# Keep screen radius up-to-date for circle glyph. Only happens when a radius is given
@last_trans = trans
@vbo_s.set_data(0, new Float32Array((s*2 for s in @glyph.sradius)))
# Update visuals if we must. Can happen for all glyphs.
if @visuals_changed
@_set_visuals(nvertices)
@visuals_changed = false
# Handle transformation to device coordinates
@prog.set_uniform('u_canvas_size', 'vec2', [trans.width, trans.height])
@prog.set_uniform('u_offset', 'vec2', [trans.dx[0], trans.dy[0]])
@prog.set_uniform('u_scale', 'vec2', [trans.sx, trans.sy])
# Select buffers from main glyph
# (which may be this glyph but maybe not if this is a (non)selection glyph)
@prog.set_attribute('a_x', 'float', [mainGlyph.glglyph.vbo_x, 0, 0])
@prog.set_attribute('a_y', 'float', [mainGlyph.glglyph.vbo_y, 0, 0])
@prog.set_attribute('a_size', 'float', [mainGlyph.glglyph.vbo_s, 0, 0])
@prog.set_attribute('a_angle', 'float', [mainGlyph.glglyph.vbo_a, 0, 0])
# Draw directly or using indices. Do not handle indices if they do not
# fit in a uint16; WebGL 1.0 does not support uint32.
if indices.length == 0
return
else if indices.length == nvertices
@prog.draw(@gl.POINTS, [0, nvertices])
else if nvertices < 65535
@index_buffer.set_size(indices.length*2)
@index_buffer.set_data(0, new Uint16Array(indices))
@prog.draw(@gl.POINTS, @index_buffer)
else
# Work around the limit that the indexbuffer must be uint16. We draw in chunks.
# First collect indices in chunks
chunksize = 64000 # 65536
chunks = []
for i in [0...Math.ceil(nvertices/chunksize)]
chunks.push([])
for i in [0...indices.length]
uint16_index = indices[i] % chunksize
chunk = Math.floor(indices[i] / chunksize)
chunks[chunk].push(uint16_index)
# Then draw each chunk
for chunk in [0...chunks.length]
these_indices = new Uint16Array(chunks[chunk])
offset = chunk * chunksize * 4
if these_indices.length == 0
continue
@prog.set_attribute('a_x', 'float', [mainGlyph.glglyph.vbo_x, 0, offset])
@prog.set_attribute('a_y', 'float', [mainGlyph.glglyph.vbo_y, 0, offset])
@prog.set_attribute('a_size', 'float', [mainGlyph.glglyph.vbo_s, 0, offset])
@prog.set_attribute('a_angle', 'float', [mainGlyph.glglyph.vbo_a, 0, offset])
if @vbo_linewidth.used
@prog.set_attribute('a_linewidth', 'float', [@vbo_linewidth, 0, offset])
if @vbo_fg_color.used
@prog.set_attribute('a_fg_color', 'vec4', [@vbo_fg_color, 0, offset * 4])
if @vbo_bg_color.used
@prog.set_attribute('a_bg_color', 'vec4', [@vbo_bg_color, 0, offset * 4])
# The actual drawing
@index_buffer.set_size(these_indices.length*2)
@index_buffer.set_data(0, these_indices)
@prog.draw(@gl.POINTS, @index_buffer)
_set_data: (nvertices) ->
n = nvertices * 4 # in bytes
# Set buffer size
@vbo_x.set_size(n)
@vbo_y.set_size(n)
@vbo_a.set_size(n)
@vbo_s.set_size(n)
# Upload data for x and y
@vbo_x.set_data(0, new Float32Array(@glyph.x))
@vbo_y.set_data(0, new Float32Array(@glyph.y))
# Angle if available; circle does not have angle. If we don't set data, angle is default 0 in glsl
if @glyph.angle?
@vbo_a.set_data(0, new Float32Array(@glyph.angle))
# Radius is special; some markes allow radius in data-coords instead of screen coords
# @radius tells us that radius is in units, sradius is the pre-calculated screen radius
if @glyph.radius?
@vbo_s.set_data(0, new Float32Array((s*2 for s in @glyph.sradius)))
else
@vbo_s.set_data(0, new Float32Array(@glyph.size))
_set_visuals: (nvertices) ->
attach_float(@prog, @vbo_linewidth, 'a_linewidth', nvertices, @glyph.visuals.line, 'width')
attach_color(@prog, @vbo_fg_color, 'a_fg_color', nvertices, @glyph.visuals.line)
attach_color(@prog, @vbo_bg_color, 'a_bg_color', nvertices, @glyph.visuals.fill)
# Static value for antialias. Smaller aa-region to obtain crisper images
@prog.set_uniform('u_antialias', 'float', [0.9])
class CircleGLGlyph extends MarkerGLGlyph
GLYPH: 'circle'
MARKERCODE: """
// --- disc
float marker(vec2 P, float size)
{
return length(P) - size/2.0;
}
"""
class SquareGLGlyph extends MarkerGLGlyph
GLYPH: 'square'
MARKERCODE: """
// --- square
float marker(vec2 P, float size)
{
return max(abs(P.x), abs(P.y)) - size/2.0;
}
"""
module.exports =
CircleGLGlyph: CircleGLGlyph
SquareGLGlyph: SquareGLGlyph
| true | if global._bokehTest?
gloo2 = undefined # TODO Make work?
else
gloo2 = require "gloo2"
color = require "../../common/color"
color2rgba = color.color2rgba
# Copyright notice: many of the awesome GLSL code contained in this module is based
# on code developed by PI:NAME:<NAME>END_PI as part of the Glumpy and Vispy projects.
# The algorithms are published in http://jcgt.org/published/0003/04/01/
# This module contains all gl-specific code to add gl support for the glyphs.
# By implementing it separetely, the GL functionality can be spun off in a
# separate library.
# Other locations where we work with GL, or prepare for GL-rendering:
# - plot.coffee
# - glyph.coffee
# - glyph_renderer.coffee
# - a few lines in each glyph-module that supports WebGL
line_width = (width) ->
# Increase small values to make it more similar to canvas
if width < 2
width = Math.sqrt(width*2)
return width
fill_array_with_float = (n, val) ->
a = new Float32Array(n)
for i in [0...n]
a[i] = val
return a
fill_array_with_vec = (n, m, val) ->
a = new Float32Array(n*m)
for i in [0...n]
for j in [0...m]
a[i*m+j] = val[j]
return a
attach_float = (prog, vbo, att_name, n, visual, name) ->
# Attach a float attribute to the program. Use singleton value if we can,
# otherwise use VBO to apply array.
vbo.used = true
if visual[name].fixed_value?
prog.set_attribute(att_name, 'float', null, visual[name].fixed_value)
vbo.used = false
else
a = new Float32Array(visual.cache[name + '_array'])
vbo.set_size(n*4)
vbo.set_data(0, a)
prog.set_attribute(att_name, 'float', [vbo, 0, 0])
return a
attach_color = (prog, vbo, att_name, n, visual) ->
# Attach the color attribute to the program. If there's just one color,
# then use this single color for all vertices (no VBO). Otherwise we
# create an array and upload that to the VBO, which we attahce to the prog.
m = 4
vbo.used = true
if visual.color.fixed_value? and visual.alpha.fixed_value?
rgba = color2rgba(visual.color.fixed_value, visual.alpha.fixed_value)
prog.set_attribute(att_name, 'vec4', null, rgba)
vbo.used = false
else
# Get array of colors
if visual.color.fixed_value?
colors = (visual.color.fixed_value for i in [0...n])
else
colors = visual.cache.color_array
# Get array of alphas
if visual.alpha.fixed_value?
alphas = fill_array_with_float(n, visual.alpha.fixed_value)
else
alphas = visual.cache.alpha_array
# Get array of rgbs
a = new Float32Array(n*m)
for i in [0...n]
rgba = color2rgba(colors[i], alphas[i])
for j in [0...m]
a[i*m+j] = rgba[j]
# Attach vbo
vbo.set_size(n*m*4)
vbo.set_data(0, a)
prog.set_attribute(att_name, 'vec4', [vbo, 0, 0])
return a
class BaseGLGlyph
GLYPH: '' # name of the glyph that this gl-glyph applies to
VERT: ''
FRAG: ''
constructor: (gl, glyph) ->
@gl = gl
@glyph = glyph
@nvertices = 0
@size_changed = false
@data_changed = false
@visuals_changed = false
@init()
set_data_changed: (n) ->
if n != @nvertices
@nvertices = n
@size_changed = true
@data_changed = true
set_visuals_changed: () ->
@visuals_changed = true
class LineGLGlyph extends BaseGLGlyph
GLYPH: 'line'
VERT: 'xxx'
FRAG: 'xxx'
class MarkerGLGlyph extends BaseGLGlyph
# Base class for markers. All markers share the same GLSL, except for one
# function that defines the marker geometry.
VERT: """
precision mediump float;
const float SQRT_2 = 1.4142135623730951;
//
uniform vec2 u_canvas_size;
uniform vec2 u_offset;
uniform vec2 u_scale;
uniform float u_antialias;
//
attribute float a_x;
attribute float a_y;
attribute float a_size;
attribute float a_angle; // in radians
attribute float a_linewidth;
attribute vec4 a_fg_color;
attribute vec4 a_bg_color;
//
varying float v_linewidth;
varying float v_size;
varying vec4 v_fg_color;
varying vec4 v_bg_color;
varying vec2 v_rotation;
void main (void)
{
v_size = a_size;
v_linewidth = a_linewidth;
v_fg_color = a_fg_color;
v_bg_color = a_bg_color;
v_rotation = vec2(cos(-a_angle), sin(-a_angle));
// Calculate position - the -0.5 is to correct for canvas origin
vec2 pos = vec2(a_x, a_y) * u_scale + u_offset - vec2(0.5, 0.5); // in pixels
pos /= u_canvas_size; // in 0..1
gl_Position = vec4(pos*2.0-1.0, 0.0, 1.0);
gl_Position.y *= -1.0;
gl_PointSize = SQRT_2 * v_size + 2.0 * (a_linewidth + 1.5*u_antialias);
}
"""
FRAG: """
precision mediump float;
const float SQRT_2 = 1.4142135623730951;
const float PI = 3.14159265358979323846264;
//
uniform float u_antialias;
//
varying vec4 v_fg_color;
varying vec4 v_bg_color;
varying float v_linewidth;
varying float v_size;
varying vec2 v_rotation;
MARKERCODE
vec4 outline(float distance, float linewidth, float antialias, vec4 fg_color, vec4 bg_color)
{
vec4 frag_color;
float t = linewidth/2.0 - antialias;
float signed_distance = distance;
float border_distance = abs(signed_distance) - t;
float alpha = border_distance/antialias;
alpha = exp(-alpha*alpha);
// If fg alpha is zero, it probably means no outline. To avoid a dark outline
// shining through due to aa, we set the fg color to the bg color. Avoid if (i.e. branching).
float select = float(bool(fg_color.a));
fg_color.rgb = select * fg_color.rgb + (1.0 - select) * bg_color.rgb;
// Similarly, if we want a transparent bg
select = float(bool(bg_color.a));
bg_color.rgb = select * bg_color.rgb + (1.0 - select) * fg_color.rgb;
if( border_distance < 0.0)
frag_color = fg_color;
else if( signed_distance < 0.0 ) {
frag_color = mix(bg_color, fg_color, sqrt(alpha));
} else {
if( abs(signed_distance) < (linewidth/2.0 + antialias) ) {
frag_color = vec4(fg_color.rgb, fg_color.a * alpha);
} else {
discard;
}
}
return frag_color;
}
void main()
{
vec2 P = gl_PointCoord.xy - vec2(0.5, 0.5);
P = vec2(v_rotation.x*P.x - v_rotation.y*P.y,
v_rotation.y*P.x + v_rotation.x*P.y);
float point_size = SQRT_2*v_size + 2.0 * (v_linewidth + 1.5*u_antialias);
float distance = marker(P*point_size, v_size);
gl_FragColor = outline(distance, v_linewidth, u_antialias, v_fg_color, v_bg_color);
//gl_FragColor.rgb *= gl_FragColor.a; // pre-multiply alpha
}
"""
MARKERCODE: "<defined in subclasses>"
init: () ->
gl = @gl
frag = @FRAG.replace /MARKERCODE/, @MARKERCODE
@last_trans = {} # Keep track of transform
# The program
@prog = new gloo2.Program(gl)
@prog.set_shaders(@VERT, frag)
@vbo_x = new gloo2.VertexBuffer(gl)
# Real attributes
@prog.set_attribute('a_x', 'float', [@vbo_x, 0, 0])
@vbo_y = new gloo2.VertexBuffer(gl)
@prog.set_attribute('a_y', 'float', [@vbo_y, 0, 0])
@vbo_s = new gloo2.VertexBuffer(gl)
@prog.set_attribute('a_size', 'float', [@vbo_s, 0, 0])
@vbo_a = new gloo2.VertexBuffer(gl)
@prog.set_attribute('a_angle', 'float', [@vbo_a, 0, 0])
# VBO's for attributes (they may not be used if value is singleton)
@vbo_linewidth = new gloo2.VertexBuffer(gl)
@vbo_fg_color = new gloo2.VertexBuffer(gl)
@vbo_bg_color = new gloo2.VertexBuffer(gl)
@index_buffer = new gloo2.IndexBuffer(gl)
draw: (indices, mainGlyph, trans) ->
# The main glyph has the data, *this* glyph has the visuals.
nvertices = mainGlyph.glglyph.nvertices
# Upload data if we must. Only happens for main glyph.
if @data_changed
@_set_data(nvertices)
@data_changed = false
else if @glyph.radius? and (trans.sx != @last_trans.sx or trans.sy != @last_trans.sy)
# Keep screen radius up-to-date for circle glyph. Only happens when a radius is given
@last_trans = trans
@vbo_s.set_data(0, new Float32Array((s*2 for s in @glyph.sradius)))
# Update visuals if we must. Can happen for all glyphs.
if @visuals_changed
@_set_visuals(nvertices)
@visuals_changed = false
# Handle transformation to device coordinates
@prog.set_uniform('u_canvas_size', 'vec2', [trans.width, trans.height])
@prog.set_uniform('u_offset', 'vec2', [trans.dx[0], trans.dy[0]])
@prog.set_uniform('u_scale', 'vec2', [trans.sx, trans.sy])
# Select buffers from main glyph
# (which may be this glyph but maybe not if this is a (non)selection glyph)
@prog.set_attribute('a_x', 'float', [mainGlyph.glglyph.vbo_x, 0, 0])
@prog.set_attribute('a_y', 'float', [mainGlyph.glglyph.vbo_y, 0, 0])
@prog.set_attribute('a_size', 'float', [mainGlyph.glglyph.vbo_s, 0, 0])
@prog.set_attribute('a_angle', 'float', [mainGlyph.glglyph.vbo_a, 0, 0])
# Draw directly or using indices. Do not handle indices if they do not
# fit in a uint16; WebGL 1.0 does not support uint32.
if indices.length == 0
return
else if indices.length == nvertices
@prog.draw(@gl.POINTS, [0, nvertices])
else if nvertices < 65535
@index_buffer.set_size(indices.length*2)
@index_buffer.set_data(0, new Uint16Array(indices))
@prog.draw(@gl.POINTS, @index_buffer)
else
# Work around the limit that the indexbuffer must be uint16. We draw in chunks.
# First collect indices in chunks
chunksize = 64000 # 65536
chunks = []
for i in [0...Math.ceil(nvertices/chunksize)]
chunks.push([])
for i in [0...indices.length]
uint16_index = indices[i] % chunksize
chunk = Math.floor(indices[i] / chunksize)
chunks[chunk].push(uint16_index)
# Then draw each chunk
for chunk in [0...chunks.length]
these_indices = new Uint16Array(chunks[chunk])
offset = chunk * chunksize * 4
if these_indices.length == 0
continue
@prog.set_attribute('a_x', 'float', [mainGlyph.glglyph.vbo_x, 0, offset])
@prog.set_attribute('a_y', 'float', [mainGlyph.glglyph.vbo_y, 0, offset])
@prog.set_attribute('a_size', 'float', [mainGlyph.glglyph.vbo_s, 0, offset])
@prog.set_attribute('a_angle', 'float', [mainGlyph.glglyph.vbo_a, 0, offset])
if @vbo_linewidth.used
@prog.set_attribute('a_linewidth', 'float', [@vbo_linewidth, 0, offset])
if @vbo_fg_color.used
@prog.set_attribute('a_fg_color', 'vec4', [@vbo_fg_color, 0, offset * 4])
if @vbo_bg_color.used
@prog.set_attribute('a_bg_color', 'vec4', [@vbo_bg_color, 0, offset * 4])
# The actual drawing
@index_buffer.set_size(these_indices.length*2)
@index_buffer.set_data(0, these_indices)
@prog.draw(@gl.POINTS, @index_buffer)
_set_data: (nvertices) ->
n = nvertices * 4 # in bytes
# Set buffer size
@vbo_x.set_size(n)
@vbo_y.set_size(n)
@vbo_a.set_size(n)
@vbo_s.set_size(n)
# Upload data for x and y
@vbo_x.set_data(0, new Float32Array(@glyph.x))
@vbo_y.set_data(0, new Float32Array(@glyph.y))
# Angle if available; circle does not have angle. If we don't set data, angle is default 0 in glsl
if @glyph.angle?
@vbo_a.set_data(0, new Float32Array(@glyph.angle))
# Radius is special; some markes allow radius in data-coords instead of screen coords
# @radius tells us that radius is in units, sradius is the pre-calculated screen radius
if @glyph.radius?
@vbo_s.set_data(0, new Float32Array((s*2 for s in @glyph.sradius)))
else
@vbo_s.set_data(0, new Float32Array(@glyph.size))
_set_visuals: (nvertices) ->
attach_float(@prog, @vbo_linewidth, 'a_linewidth', nvertices, @glyph.visuals.line, 'width')
attach_color(@prog, @vbo_fg_color, 'a_fg_color', nvertices, @glyph.visuals.line)
attach_color(@prog, @vbo_bg_color, 'a_bg_color', nvertices, @glyph.visuals.fill)
# Static value for antialias. Smaller aa-region to obtain crisper images
@prog.set_uniform('u_antialias', 'float', [0.9])
class CircleGLGlyph extends MarkerGLGlyph
GLYPH: 'circle'
MARKERCODE: """
// --- disc
float marker(vec2 P, float size)
{
return length(P) - size/2.0;
}
"""
class SquareGLGlyph extends MarkerGLGlyph
GLYPH: 'square'
MARKERCODE: """
// --- square
float marker(vec2 P, float size)
{
return max(abs(P.x), abs(P.y)) - size/2.0;
}
"""
module.exports =
CircleGLGlyph: CircleGLGlyph
SquareGLGlyph: SquareGLGlyph
|
[
{
"context": "[\n {\n type: \"text\"\n id: \"username\"\n floatingLabelText: \"Username\"\n ",
"end": 570,
"score": 0.9988459348678589,
"start": 562,
"tag": "USERNAME",
"value": "username"
},
{
"context": " id: \"username\"\n floatingLabelText: \"Username\"\n }, {\n type: \"password\"\n ",
"end": 610,
"score": 0.9938099980354309,
"start": 602,
"tag": "USERNAME",
"value": "Username"
},
{
"context": "belText: \"Username\"\n }, {\n type: \"password\"\n id: \"password\"\n floatingLabel",
"end": 650,
"score": 0.740675687789917,
"start": 642,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " id: \"password\"\n floatingLabelText: \"Password\"\n }, {\n type: \"hidden\"\n ",
"end": 715,
"score": 0.9979671835899353,
"start": 707,
"tag": "PASSWORD",
"value": "Password"
}
] | src/components/app/pages/user/login.coffee | dwetterau/base-node-app | 0 | React = require 'react'
Router = require 'react-router'
FormPage = require './form_page'
{userLoginRequest} = require '../../actions'
Notifier = require '../../utils/notifier'
Login = React.createClass
mixins: [Router.Navigation]
_onSubmit: (fields) ->
userLoginRequest(fields).then (response) =>
@transitionTo response.redirect_url
Notifier.info('Login successful!');
.catch Notifier.error
render: () ->
React.createElement FormPage,
pageHeader: 'Sign in'
inputs: [
{
type: "text"
id: "username"
floatingLabelText: "Username"
}, {
type: "password"
id: "password"
floatingLabelText: "Password"
}, {
type: "hidden"
id: "redirect"
value: @props.redirect || ""
}
]
submitLabel: 'Login'
onSubmit: @_onSubmit
module.exports = Login
| 124144 | React = require 'react'
Router = require 'react-router'
FormPage = require './form_page'
{userLoginRequest} = require '../../actions'
Notifier = require '../../utils/notifier'
Login = React.createClass
mixins: [Router.Navigation]
_onSubmit: (fields) ->
userLoginRequest(fields).then (response) =>
@transitionTo response.redirect_url
Notifier.info('Login successful!');
.catch Notifier.error
render: () ->
React.createElement FormPage,
pageHeader: 'Sign in'
inputs: [
{
type: "text"
id: "username"
floatingLabelText: "Username"
}, {
type: "<PASSWORD>"
id: "password"
floatingLabelText: "<PASSWORD>"
}, {
type: "hidden"
id: "redirect"
value: @props.redirect || ""
}
]
submitLabel: 'Login'
onSubmit: @_onSubmit
module.exports = Login
| true | React = require 'react'
Router = require 'react-router'
FormPage = require './form_page'
{userLoginRequest} = require '../../actions'
Notifier = require '../../utils/notifier'
Login = React.createClass
mixins: [Router.Navigation]
_onSubmit: (fields) ->
userLoginRequest(fields).then (response) =>
@transitionTo response.redirect_url
Notifier.info('Login successful!');
.catch Notifier.error
render: () ->
React.createElement FormPage,
pageHeader: 'Sign in'
inputs: [
{
type: "text"
id: "username"
floatingLabelText: "Username"
}, {
type: "PI:PASSWORD:<PASSWORD>END_PI"
id: "password"
floatingLabelText: "PI:PASSWORD:<PASSWORD>END_PI"
}, {
type: "hidden"
id: "redirect"
value: @props.redirect || ""
}
]
submitLabel: 'Login'
onSubmit: @_onSubmit
module.exports = Login
|
[
{
"context": "orts = lemon.Component {\n package: 'wg'\n name: 'ChemicAqua'\n class: 'webgradient'\n\n data: {\n pos",
"end": 176,
"score": 0.46995747089385986,
"start": 173,
"tag": "NAME",
"value": "Che"
}
] | ChemicAqua.coffee | lemon/lemonjs-wg | 0 |
# dependencies
Path = require 'path'
# stylesheet
require Path.resolve(__dirname, 'gradient.css')
# component
module.exports = lemon.Component {
package: 'wg'
name: 'ChemicAqua'
class: 'webgradient'
data: {
position: null
}
template: (data) ->
div class: data.position, style: "background-color: #CDDCDC; background-image: radial-gradient(at 50% 100%, rgba(255,255,255,0.50) 0%, rgba(0,0,0,0.50) 100%), linear-gradient(to bottom, rgba(255,255,255,0.25) 0%, rgba(0,0,0,0.25) 100%); background-blend-mode: screen, overlay;"
} | 206047 |
# dependencies
Path = require 'path'
# stylesheet
require Path.resolve(__dirname, 'gradient.css')
# component
module.exports = lemon.Component {
package: 'wg'
name: '<NAME>micAqua'
class: 'webgradient'
data: {
position: null
}
template: (data) ->
div class: data.position, style: "background-color: #CDDCDC; background-image: radial-gradient(at 50% 100%, rgba(255,255,255,0.50) 0%, rgba(0,0,0,0.50) 100%), linear-gradient(to bottom, rgba(255,255,255,0.25) 0%, rgba(0,0,0,0.25) 100%); background-blend-mode: screen, overlay;"
} | true |
# dependencies
Path = require 'path'
# stylesheet
require Path.resolve(__dirname, 'gradient.css')
# component
module.exports = lemon.Component {
package: 'wg'
name: 'PI:NAME:<NAME>END_PImicAqua'
class: 'webgradient'
data: {
position: null
}
template: (data) ->
div class: data.position, style: "background-color: #CDDCDC; background-image: radial-gradient(at 50% 100%, rgba(255,255,255,0.50) 0%, rgba(0,0,0,0.50) 100%), linear-gradient(to bottom, rgba(255,255,255,0.25) 0%, rgba(0,0,0,0.25) 100%); background-blend-mode: screen, overlay;"
} |
[
{
"context": "# Copyright (c) 2019, Daniel Andrade\n#\n# Permission to use, copy, modify, and/or distr",
"end": 36,
"score": 0.9998456239700317,
"start": 22,
"tag": "NAME",
"value": "Daniel Andrade"
}
] | grammars/tree-sitter-edl.cson | Andrade/language-edl | 0 | # Copyright (c) 2019, Daniel Andrade
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
name: 'Enclave Definition Language'
scopeName: 'source.edl'
type: 'tree-sitter'
parser: 'tree-sitter-edl'
fileTypes: ['edl']
scopes:
'source_file': 'source.edl'
'comments': 'comment.block'
'"from"': 'keyword.control.directive'
'"import"': 'keyword.control.directive'
'"include"': 'keyword.control.directive'
'header_name': 'string.quoted.other'
'''
"enclave",
"trusted",
"untrusted"
''': 'keyword.control.directive'
'''
import_list > identifier,
ecall_definition > identifier,
ocall_definition > identifier,
untrusted_suffix_allow > identifier
''': 'entity.name.function'
'''
trusted_prefix_public,
untrusted_suffix_allow > "allow",
suffix_propagate_errno,
suffix_transition_using_threads
''': 'keyword.control'
#'_pointer_attributes': 'variable.other.member'
'''
"in",
"out",
"user_check",
"string",
"wstring",
"size",
"count",
"isary",
"isptr",
"readonly"
''': 'variable.other.member'
'type_qualifier': 'storage.modifier'
'type_specifier': 'support.storage.type'
'''
"enum",
"struct",
"union"
''': 'keyword.control'
#'void_type': 'support.storage.type'
'"void"': 'support.storage.type'
'number': 'constant.numeric.decimal'
'";"': 'punctuation.terminator.statement'
'"["': 'punctuation.definition.begin.bracket.square'
'"]"': 'punctuation.definition.end.bracket.square'
'","': 'punctuation.separator.delimiter'
'"{"': 'punctuation.section.block.begin.bracket.curly'
'"}"': 'punctuation.section.block.end.bracket.curly'
'"("': 'punctuation.section.parens.begin.bracket.round'
'")"': 'punctuation.section.parens.end.bracket.round'
'"*"': 'storage.modifier'
'"="': 'keyword.operator'
folds: [
type: 'comment'
]
comments:
start: '// '
| 87980 | # Copyright (c) 2019, <NAME>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
name: 'Enclave Definition Language'
scopeName: 'source.edl'
type: 'tree-sitter'
parser: 'tree-sitter-edl'
fileTypes: ['edl']
scopes:
'source_file': 'source.edl'
'comments': 'comment.block'
'"from"': 'keyword.control.directive'
'"import"': 'keyword.control.directive'
'"include"': 'keyword.control.directive'
'header_name': 'string.quoted.other'
'''
"enclave",
"trusted",
"untrusted"
''': 'keyword.control.directive'
'''
import_list > identifier,
ecall_definition > identifier,
ocall_definition > identifier,
untrusted_suffix_allow > identifier
''': 'entity.name.function'
'''
trusted_prefix_public,
untrusted_suffix_allow > "allow",
suffix_propagate_errno,
suffix_transition_using_threads
''': 'keyword.control'
#'_pointer_attributes': 'variable.other.member'
'''
"in",
"out",
"user_check",
"string",
"wstring",
"size",
"count",
"isary",
"isptr",
"readonly"
''': 'variable.other.member'
'type_qualifier': 'storage.modifier'
'type_specifier': 'support.storage.type'
'''
"enum",
"struct",
"union"
''': 'keyword.control'
#'void_type': 'support.storage.type'
'"void"': 'support.storage.type'
'number': 'constant.numeric.decimal'
'";"': 'punctuation.terminator.statement'
'"["': 'punctuation.definition.begin.bracket.square'
'"]"': 'punctuation.definition.end.bracket.square'
'","': 'punctuation.separator.delimiter'
'"{"': 'punctuation.section.block.begin.bracket.curly'
'"}"': 'punctuation.section.block.end.bracket.curly'
'"("': 'punctuation.section.parens.begin.bracket.round'
'")"': 'punctuation.section.parens.end.bracket.round'
'"*"': 'storage.modifier'
'"="': 'keyword.operator'
folds: [
type: 'comment'
]
comments:
start: '// '
| true | # Copyright (c) 2019, PI:NAME:<NAME>END_PI
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
name: 'Enclave Definition Language'
scopeName: 'source.edl'
type: 'tree-sitter'
parser: 'tree-sitter-edl'
fileTypes: ['edl']
scopes:
'source_file': 'source.edl'
'comments': 'comment.block'
'"from"': 'keyword.control.directive'
'"import"': 'keyword.control.directive'
'"include"': 'keyword.control.directive'
'header_name': 'string.quoted.other'
'''
"enclave",
"trusted",
"untrusted"
''': 'keyword.control.directive'
'''
import_list > identifier,
ecall_definition > identifier,
ocall_definition > identifier,
untrusted_suffix_allow > identifier
''': 'entity.name.function'
'''
trusted_prefix_public,
untrusted_suffix_allow > "allow",
suffix_propagate_errno,
suffix_transition_using_threads
''': 'keyword.control'
#'_pointer_attributes': 'variable.other.member'
'''
"in",
"out",
"user_check",
"string",
"wstring",
"size",
"count",
"isary",
"isptr",
"readonly"
''': 'variable.other.member'
'type_qualifier': 'storage.modifier'
'type_specifier': 'support.storage.type'
'''
"enum",
"struct",
"union"
''': 'keyword.control'
#'void_type': 'support.storage.type'
'"void"': 'support.storage.type'
'number': 'constant.numeric.decimal'
'";"': 'punctuation.terminator.statement'
'"["': 'punctuation.definition.begin.bracket.square'
'"]"': 'punctuation.definition.end.bracket.square'
'","': 'punctuation.separator.delimiter'
'"{"': 'punctuation.section.block.begin.bracket.curly'
'"}"': 'punctuation.section.block.end.bracket.curly'
'"("': 'punctuation.section.parens.begin.bracket.round'
'")"': 'punctuation.section.parens.end.bracket.round'
'"*"': 'storage.modifier'
'"="': 'keyword.operator'
folds: [
type: 'comment'
]
comments:
start: '// '
|
[
{
"context": "rocess.exit()\n\nSTREAM1 =\n key: \"test1\"\n source_password: \"abc123\"\n root_route:",
"end": 437,
"score": 0.9961884617805481,
"start": 432,
"tag": "KEY",
"value": "test1"
},
{
"context": ": \"test1\"\n source_password: \"abc123\"\n root_route: true\n seconds: ",
"end": 470,
"score": 0.9993021488189697,
"start": 464,
"tag": "PASSWORD",
"value": "abc123"
}
] | test/master_stream.coffee | firebrandv2/FirebrandNetwork.ga | 342 | MasterMode = $src "modes/master"
Master = $src "master"
MasterStream = $src "master/stream"
SourceMount = $src "master/source_mount"
Logger = $src "logger"
FileSource = $src "sources/file"
RewindBuffer = $src "rewind_buffer"
HLSSegmenter = $src "rewind/hls_segmenter"
mp3 = $file "mp3/mp3-44100-64-m.mp3"
_ = require "underscore"
#process.exit()
STREAM1 =
key: "test1"
source_password: "abc123"
root_route: true
seconds: 60*60*4
format: "mp3"
describe "Master Stream", ->
logger = new Logger stdout:false
describe "Startup", ->
mount = new SourceMount "test1", logger, STREAM1
stream = new MasterStream "test1", logger, mount, STREAM1
it "creates a Rewind Buffer", (done) ->
expect(stream.rewind).to.be.an.instanceof RewindBuffer
done()
#----------
describe "HLS", ->
stream = null
source = null
before (done) ->
mount = new SourceMount "test1", logger, STREAM1
stream = new MasterStream "test1", logger, mount, _.extend {}, STREAM1, hls:{segment_duration:10}
source = new FileSource format:"mp3", filePath:mp3, chunkDuration:0.5, do_not_emit:true
stream.addSource source
source.once "_loaded", ->
# emit 45 seconds of data
# to make life easy to reason about, we'll put start_ts on a segment start.
start_ts = new Date( Math.round(start_ts / 10) * 10 )
for i in [0..90]
source._emitOnce new Date( start_ts + i*500 )
done()
it "should have created an HLS Segmenter", (done) ->
expect( stream.rewind.hls_segmenter ).to.be.instanceof HLSSegmenter
done()
it "should have loaded data into the RewindBuffer", (done) ->
expect( stream.rewind._rbuffer.length() ).to.be.gt 1
done()
it "should have created HLS segments", (done) ->
this.timeout 5000
stream.rewind.hls_segmenter.once "snapshot", (snapshot) =>
# depending on how our segment boundary falls, this could be
# three or four
expect(snapshot.segments).to.have.length.within 3,4
expect(snapshot.segment_duration).to.eq 10
done()
| 171038 | MasterMode = $src "modes/master"
Master = $src "master"
MasterStream = $src "master/stream"
SourceMount = $src "master/source_mount"
Logger = $src "logger"
FileSource = $src "sources/file"
RewindBuffer = $src "rewind_buffer"
HLSSegmenter = $src "rewind/hls_segmenter"
mp3 = $file "mp3/mp3-44100-64-m.mp3"
_ = require "underscore"
#process.exit()
STREAM1 =
key: "<KEY>"
source_password: "<PASSWORD>"
root_route: true
seconds: 60*60*4
format: "mp3"
describe "Master Stream", ->
logger = new Logger stdout:false
describe "Startup", ->
mount = new SourceMount "test1", logger, STREAM1
stream = new MasterStream "test1", logger, mount, STREAM1
it "creates a Rewind Buffer", (done) ->
expect(stream.rewind).to.be.an.instanceof RewindBuffer
done()
#----------
describe "HLS", ->
stream = null
source = null
before (done) ->
mount = new SourceMount "test1", logger, STREAM1
stream = new MasterStream "test1", logger, mount, _.extend {}, STREAM1, hls:{segment_duration:10}
source = new FileSource format:"mp3", filePath:mp3, chunkDuration:0.5, do_not_emit:true
stream.addSource source
source.once "_loaded", ->
# emit 45 seconds of data
# to make life easy to reason about, we'll put start_ts on a segment start.
start_ts = new Date( Math.round(start_ts / 10) * 10 )
for i in [0..90]
source._emitOnce new Date( start_ts + i*500 )
done()
it "should have created an HLS Segmenter", (done) ->
expect( stream.rewind.hls_segmenter ).to.be.instanceof HLSSegmenter
done()
it "should have loaded data into the RewindBuffer", (done) ->
expect( stream.rewind._rbuffer.length() ).to.be.gt 1
done()
it "should have created HLS segments", (done) ->
this.timeout 5000
stream.rewind.hls_segmenter.once "snapshot", (snapshot) =>
# depending on how our segment boundary falls, this could be
# three or four
expect(snapshot.segments).to.have.length.within 3,4
expect(snapshot.segment_duration).to.eq 10
done()
| true | MasterMode = $src "modes/master"
Master = $src "master"
MasterStream = $src "master/stream"
SourceMount = $src "master/source_mount"
Logger = $src "logger"
FileSource = $src "sources/file"
RewindBuffer = $src "rewind_buffer"
HLSSegmenter = $src "rewind/hls_segmenter"
mp3 = $file "mp3/mp3-44100-64-m.mp3"
_ = require "underscore"
#process.exit()
STREAM1 =
key: "PI:KEY:<KEY>END_PI"
source_password: "PI:PASSWORD:<PASSWORD>END_PI"
root_route: true
seconds: 60*60*4
format: "mp3"
describe "Master Stream", ->
logger = new Logger stdout:false
describe "Startup", ->
mount = new SourceMount "test1", logger, STREAM1
stream = new MasterStream "test1", logger, mount, STREAM1
it "creates a Rewind Buffer", (done) ->
expect(stream.rewind).to.be.an.instanceof RewindBuffer
done()
#----------
describe "HLS", ->
stream = null
source = null
before (done) ->
mount = new SourceMount "test1", logger, STREAM1
stream = new MasterStream "test1", logger, mount, _.extend {}, STREAM1, hls:{segment_duration:10}
source = new FileSource format:"mp3", filePath:mp3, chunkDuration:0.5, do_not_emit:true
stream.addSource source
source.once "_loaded", ->
# emit 45 seconds of data
# to make life easy to reason about, we'll put start_ts on a segment start.
start_ts = new Date( Math.round(start_ts / 10) * 10 )
for i in [0..90]
source._emitOnce new Date( start_ts + i*500 )
done()
it "should have created an HLS Segmenter", (done) ->
expect( stream.rewind.hls_segmenter ).to.be.instanceof HLSSegmenter
done()
it "should have loaded data into the RewindBuffer", (done) ->
expect( stream.rewind._rbuffer.length() ).to.be.gt 1
done()
it "should have created HLS segments", (done) ->
this.timeout 5000
stream.rewind.hls_segmenter.once "snapshot", (snapshot) =>
# depending on how our segment boundary falls, this could be
# three or four
expect(snapshot.segments).to.have.length.within 3,4
expect(snapshot.segment_duration).to.eq 10
done()
|
[
{
"context": " done(null, req.user)\n else if username == 'temp' || username == 'bot'\n debug(\"Creating tem",
"end": 724,
"score": 0.9992582201957703,
"start": 720,
"tag": "USERNAME",
"value": "temp"
},
{
"context": "\n else if username == 'temp' || username == 'bot'\n debug(\"Creating temp user as username is",
"end": 745,
"score": 0.9988593459129333,
"start": 742,
"tag": "USERNAME",
"value": "bot"
},
{
"context": "d user by username: \" + username + \" password: \" + password);\n User.findByUsernamePassword username, p",
"end": 1092,
"score": 0.5128912329673767,
"start": 1084,
"tag": "PASSWORD",
"value": "password"
}
] | lobby/lib/passport-helpers.coffee | towerstorm/game | 11 | tdb = require 'database'
User = tdb.models.User
netconfig = require 'config/netconfig'
passport = require 'passport'
LocalStrategy = require('passport-local').Strategy
log = require('logger')
debug = require('debug')('lib:passport-helpers');
LOBBY_URL = "http://" + netconfig.lobby.host + ":" + netconfig.lobby.port
formatUserForReq = (user) ->
return {id: user.get('id'), role: user.get('role')}
auth =
localStrategy: ->
return new LocalStrategy({
passReqToCallback: true
}, (req, username, password, done) ->
debug("Starting local strategy");
if req.user
debug("Returning from local strategy as we already have a user");
done(null, req.user)
else if username == 'temp' || username == 'bot'
debug("Creating temp user as username is: " + username);
User.createTempUser username, (err, user) ->
if err
log.error(err.message)
return done(err)
done(err, formatUserForReq(user))
else
debug("Attempting to find user by username: " + username + " password: " + password);
User.findByUsernamePassword username, password, (err, user) ->
if err
log.warn(err.message)
return done(err)
done(err, formatUserForReq(user))
)
###
How Social logins work:
- If a user is not logged in it tries to find them by their social account id.
- If it can find them it logs them in as that account
- If it cannot find them it creates a new account for them tying that social account to it.
- If a user is logged in it tries to find them by their social account
- If it can find them it logs them in as that account
- If it cannot find them it adds their social account to the exisiting account.
###
setupUser: (provider, profileId, profile, req, done) ->
if !req.user
User.findOrCreateOauthUser provider, profileId, profile, (err, user) ->
done(err, formatUserForReq(user))
else
User.findByProviderId provider, profileId, (err, user) ->
if !err? && user?
log.info("Found by providerid ", profileId)
done(err, formatUserForReq(user))
else
log.info("Did not find by providerid ", profileId)
User.findById req.user.id, (err, user) ->
if err then return done(err)
user.addOauthProvider provider, profileId, profile, (err, user) ->
log.info("Added oauth provider ", profileId)
done(err, formatUserForReq(user))
serializeUser: (user, done) ->
debug("(" + Date.now() + ") Serializing user: ", user)
userId = if user.get? then user.get('id') else user.id
done(null, userId);
deserializeUser: (id, done) ->
debug("(" + Date.now() + ") Deserializing id " + id)
User.findById id, (err, user) ->
if !user
log.warn("(" + Date.now() + ") Did not find user of id " + id)
return done(null, false)
debug("(" + Date.now() + ") Found user of id " + id)
done(err, formatUserForReq(user))
module.exports = auth
| 132852 | tdb = require 'database'
User = tdb.models.User
netconfig = require 'config/netconfig'
passport = require 'passport'
LocalStrategy = require('passport-local').Strategy
log = require('logger')
debug = require('debug')('lib:passport-helpers');
LOBBY_URL = "http://" + netconfig.lobby.host + ":" + netconfig.lobby.port
formatUserForReq = (user) ->
return {id: user.get('id'), role: user.get('role')}
auth =
localStrategy: ->
return new LocalStrategy({
passReqToCallback: true
}, (req, username, password, done) ->
debug("Starting local strategy");
if req.user
debug("Returning from local strategy as we already have a user");
done(null, req.user)
else if username == 'temp' || username == 'bot'
debug("Creating temp user as username is: " + username);
User.createTempUser username, (err, user) ->
if err
log.error(err.message)
return done(err)
done(err, formatUserForReq(user))
else
debug("Attempting to find user by username: " + username + " password: " + <PASSWORD>);
User.findByUsernamePassword username, password, (err, user) ->
if err
log.warn(err.message)
return done(err)
done(err, formatUserForReq(user))
)
###
How Social logins work:
- If a user is not logged in it tries to find them by their social account id.
- If it can find them it logs them in as that account
- If it cannot find them it creates a new account for them tying that social account to it.
- If a user is logged in it tries to find them by their social account
- If it can find them it logs them in as that account
- If it cannot find them it adds their social account to the exisiting account.
###
setupUser: (provider, profileId, profile, req, done) ->
if !req.user
User.findOrCreateOauthUser provider, profileId, profile, (err, user) ->
done(err, formatUserForReq(user))
else
User.findByProviderId provider, profileId, (err, user) ->
if !err? && user?
log.info("Found by providerid ", profileId)
done(err, formatUserForReq(user))
else
log.info("Did not find by providerid ", profileId)
User.findById req.user.id, (err, user) ->
if err then return done(err)
user.addOauthProvider provider, profileId, profile, (err, user) ->
log.info("Added oauth provider ", profileId)
done(err, formatUserForReq(user))
serializeUser: (user, done) ->
debug("(" + Date.now() + ") Serializing user: ", user)
userId = if user.get? then user.get('id') else user.id
done(null, userId);
deserializeUser: (id, done) ->
debug("(" + Date.now() + ") Deserializing id " + id)
User.findById id, (err, user) ->
if !user
log.warn("(" + Date.now() + ") Did not find user of id " + id)
return done(null, false)
debug("(" + Date.now() + ") Found user of id " + id)
done(err, formatUserForReq(user))
module.exports = auth
| true | tdb = require 'database'
User = tdb.models.User
netconfig = require 'config/netconfig'
passport = require 'passport'
LocalStrategy = require('passport-local').Strategy
log = require('logger')
debug = require('debug')('lib:passport-helpers');
LOBBY_URL = "http://" + netconfig.lobby.host + ":" + netconfig.lobby.port
formatUserForReq = (user) ->
return {id: user.get('id'), role: user.get('role')}
auth =
localStrategy: ->
return new LocalStrategy({
passReqToCallback: true
}, (req, username, password, done) ->
debug("Starting local strategy");
if req.user
debug("Returning from local strategy as we already have a user");
done(null, req.user)
else if username == 'temp' || username == 'bot'
debug("Creating temp user as username is: " + username);
User.createTempUser username, (err, user) ->
if err
log.error(err.message)
return done(err)
done(err, formatUserForReq(user))
else
debug("Attempting to find user by username: " + username + " password: " + PI:PASSWORD:<PASSWORD>END_PI);
User.findByUsernamePassword username, password, (err, user) ->
if err
log.warn(err.message)
return done(err)
done(err, formatUserForReq(user))
)
###
How Social logins work:
- If a user is not logged in it tries to find them by their social account id.
- If it can find them it logs them in as that account
- If it cannot find them it creates a new account for them tying that social account to it.
- If a user is logged in it tries to find them by their social account
- If it can find them it logs them in as that account
- If it cannot find them it adds their social account to the exisiting account.
###
setupUser: (provider, profileId, profile, req, done) ->
if !req.user
User.findOrCreateOauthUser provider, profileId, profile, (err, user) ->
done(err, formatUserForReq(user))
else
User.findByProviderId provider, profileId, (err, user) ->
if !err? && user?
log.info("Found by providerid ", profileId)
done(err, formatUserForReq(user))
else
log.info("Did not find by providerid ", profileId)
User.findById req.user.id, (err, user) ->
if err then return done(err)
user.addOauthProvider provider, profileId, profile, (err, user) ->
log.info("Added oauth provider ", profileId)
done(err, formatUserForReq(user))
serializeUser: (user, done) ->
debug("(" + Date.now() + ") Serializing user: ", user)
userId = if user.get? then user.get('id') else user.id
done(null, userId);
deserializeUser: (id, done) ->
debug("(" + Date.now() + ") Deserializing id " + id)
User.findById id, (err, user) ->
if !user
log.warn("(" + Date.now() + ") Did not find user of id " + id)
return done(null, false)
debug("(" + Date.now() + ") Found user of id " + id)
done(err, formatUserForReq(user))
module.exports = auth
|
[
{
"context": "mponent auth.user\n\t\t\tpassword = encodeURIComponent auth.password\n\t\t\t@_connectUrl = \"mongodb://#{user}:#{password}@",
"end": 762,
"score": 0.9539234638214111,
"start": 749,
"tag": "PASSWORD",
"value": "auth.password"
},
{
"context": "me\n\t* signature: params, [logger], [fn]\n\t*\t\thost: 127.0.0.1\n\t* \tport: 3002\n\t*\t\tdatabases:\n\t*\t\t\tdbname1:\n\t*\t\t\t",
"end": 3421,
"score": 0.9993703365325928,
"start": 3412,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | lib/main.coffee | tifroz/macmongo | 0 | ###*
* Database helpers to provide easy database access.
*
* Usage:
* db = require(thismodule)
* db.initialize(function(){
* db.dbname.createCollection(...)
* db.dbname.collectionname.find(...)
* })
###
_ = require('underscore')
mongodb = require('mongodb')
assert = require('assert')
util = require('util')
Seq = require('seq')
logger = console
dbperf = {}
class MongoClient
constructor: (dbname, host, port, auth, @_options) ->
if not dbname then throw new Error 'A database name must be provided to create a new db client'
logger.debug "Initializing MongoDb server #{@_host}:#{@_port} with options", @_options
if auth?.user and auth.password and auth.database
user = encodeURIComponent auth.user
password = encodeURIComponent auth.password
@_connectUrl = "mongodb://#{user}:#{password}@#{host}:#{port}/#{dbname}?authSource=#{auth.database}"
logger.debug "Created client for the '#{dbname}' db, authenticated as #{auth.user} (from db #{auth.database})."
else
@_connectUrl = "mongodb://#{host}:#{port}/#{dbname}"
logger.debug "Created client for the '#{dbname}' db (no authentication info provided)."
close: ->
@db.close()
shortCollectionName: (raw) ->
raw.split('.').pop()
addCollections: (cols, indexesDef) ->
@collections = {}
logger.debug util.format("indexesDef at %j", indexesDef)
for col in cols
name = col.collectionName
if name.substr(0,6) isnt 'system'
if @collections[name] is undefined
@collections[name] = col
logger.debug "OK looking at indexes for collection #{name}"
if indexesDef[name] isnt undefined
for indexDef in indexesDef[name]
ensureIndexCallback = (name)->
return (err, indexName)->
if err
logger.error("ensureIndex",err)
else
logger.debug util.format("Collection #{name} has index named #{indexName}")
col.ensureIndex indexDef, background: true, ensureIndexCallback(name)
else
throw Error('Can\'t override existing member '+name)
getAdmin: ->
return @db.admin()
getCollections: ->
return @collections
initialize: (params, fn) ->
names = _.keys params
connectUrl = @_connectUrl
client = @
logger.info("MongoClient.init: initializing #{names}")
Seq().seq ->
Client = mongodb.MongoClient
Client.connect connectUrl, {db: {w: 1}, server: client._options}, this
.seq (mongoClient)->
client.db = mongoClient.db()
client.db.collections(this)
.seq (cols) ->
client.addCollections(cols, params)
existing = _.pluck(cols, 'collectionName')
logger.debug("MongoClient.init: existing collections '#{existing}'")
missing = _.difference(names, existing)
if missing.length > 0
logger.info("MongoClient.init: missing collections #{missing}")
this(null, missing)
.flatten()
.parMap (name)->
logger.info "Creating missing collection '#{name}'"
client.db.createCollection name, this
.unflatten()
.seq (cols) ->
if cols.length > 0
logger.info("MongoClient.init: still missing collections #{_.pluck cols, 'collectionName'}")
client.addCollections(cols, params)
fn(null,@)
.catch (boo)->
logger.error("MongoClient.initialize #{boo}")
fn(boo)
###
* Connects the sysdb, local and shared databases to their respective databases
* and makes the collections available via thismodule.db.collectionname
* signature: params, [logger], [fn]
* host: 127.0.0.1
* port: 3002
* databases:
* dbname1:
* collection1: [<list of indexes>]
* collection2: []
* dbname2:
* collection: []
* etc..
###
class DB
initialize: (@params, lgger, fn) ->
if fn is undefined and lgger?.log is undefined
fn = lgger
else if lgger isnt undefined
logger = lgger
@_linkingInitiated = {}
@databases = {}
databases = @databases
db = @
params = @params
dbnames = _.keys params?.databases
logger.debug(util.format("MongoDB initializing databases #{dbnames} from params %j", params))
Seq(dbnames).flatten()
.seqEach (dbname)->
db.addDatabase dbname, params.databases[dbname], this
.seq ->
fn?()
.catch (err) ->
fn?(err)
close: (delay = 1000)->
db = @
Seq().seq ->
setTimeout this, delay
.seq ->
this(null, _(db.databases).values)
.flatten()
.seqEach (client)->
client.close(this)
.catch (err)->
if err
logger.error err.stack
###
* Links a database (a.k.a makes the database available via db[dbname], or db.databases[dbname]), and creates it if necessary with all specified collections and indexes
*
* signature: dbname, [collectionsDef], [fn]
* collectionsDef is a plain object, e.g
* collection1: [<list of indexes>]
* collection1: [<list of indexes>]
* etc..
*
###
addDatabase: (dbname, collectionsDef, fn)->
if fn is undefined
if _.isFunction collectionsDef
fn = collectionsDef
collectionsDef = {}
db = @
Seq().seq ->
db.linkDatabase dbname, collectionsDef, this
.seq ->
collections = db.databases[dbname].getCollections()
collectionNames = _.keys collections
intersect = _.intersection collectionNames, _.keys(db)
for collectionName in collectionNames
db.databases[dbname][collectionName] = collections[collectionName]
if collectionName in intersect
logger.warn "Conflicting collections name(s), db.#{collectionName} shortcut unavailable, use db.databases.#{dbname}.#{collectionName}"
else
logger.info "OK db.#{collectionName} is a valid shortcut for db.databases.#{dbname}.#{collectionName}"
db[collectionName] = db.databases[dbname][collectionName]
fn?()
.catch (boo)->
fn?(boo)
###
* Links a database (a.k.a makes the database available via db[dbname] if it already exists
###
linkDatabaseIfExists: (dbname, fn)->
db = @
logger.debug "OK linkDatabaseIfExists #{dbname}"
if db.databases[dbname]?.collections isnt undefined
logger.debug "OK database '#{dbname}' is already linked"
return fn?()
else if _.keys(db.databases).length is 0 and dontCreate
return fn?(new Error("MacMongo can't get an admin (no existing db to get an admin instance off of)"))
else
if @_linkingInitiated[dbname]
setTimeout fn, 500 # linking is in progress, just wait for a bit
else
@_linkingInitiated[dbname] = true
Seq().seq ->
firstDb = db.databases[_.keys(db.databases)[0]]
firstDb.getAdmin().listDatabases this
.seq (dbs)->
dbnames = _.pluck dbs.databases, "name"
if dbname.toLowerCase() not in dbnames
return fn?(new Error("#{dbname.toLowerCase()} not found amongst collections of #{dbname} (#{dbnames})"))
db.linkDatabase(dbname, this)
.seq ->
fn?()
.catch (boo)->
fn?(boo)
###
* Links a database (a.k.a makes the database available via db[dbname], or db.databases[dbname]), and creates it it doesn't already exists
###
linkDatabase: (dbname, collectionsDef, fn)->
if fn is undefined
if _.isFunction collectionsDef
fn = collectionsDef
collectionsDef = {}
db = @
if db.databases[dbname] isnt undefined
logger.debug "OK database '#{dbname}' is already linked"
return fn?()
Seq().seq ->
db.databases[dbname] = new MongoClient(dbname, db.params.host, db.params.port, db.params.auth, db.params.options)
if dbname in _.keys(db)
logger.error "Conflicting database name, db.#{dbname} shortcut is unavailable, use db.databases.#{dbname}"
else
db[dbname] = db.databases[dbname]
db.databases[dbname].initialize collectionsDef, this
.seq ->
fn?()
.catch (boo)->
fn?(boo)
###*
* A utility method to generate GUIDs on the fly
###
uid: ->
n = 4
uid = while n-=1
(Math.abs((Math.random() * 0xFFFFFFF) | 0)).toString(16)
ui = uid.join('')
return ui
###*
* Utility methods to escape dots from attribute names
###
escapeDot: (str) ->
return str.replace(/\./g, "#dot;")
unescapeDot: (o) ->
res = {}
if _.isObject(o) and not _.isArray(o) and not _.isDate(o)
for p of o
res[p.replace(/#dot;/g, ".")] = db.unescapeDot(o[p]) if o.hasOwnProperty(p)
else
res = o
return res
getCollectionNames: (dbname)->
collections = []
if dbname is undefined
for name, database of @databases
logger.info "#{database} has #{_.keys(database.getCollections())}"
collections = collections.concat _.keys(database.getCollections())
else
collections = _.keys(@databases[dbname].getCollections())
return collections
getLayout: ->
layout = {}
for dbname, database of @databases
if layout[dbname] is undefined
layout[dbname] = []
for colname, collection of database.getCollections()
layout[dbname].push colname
return layout
###*
* Logs db performance & explain
###
perfLog: (cursor) ->
cursor.explain (err, doc) ->
if err then console.error('db.perf',err)
if doc
collectionName = cursor.collection.collectionName
if doc.millis > 300
logger.warn("db.perf.#{collectionName}","Latency #{doc.millis}ms: #{doc.n} records returned, #{doc.nscanned} scanned")
logger.warn('db.perf.query', cursor.selector)
logger.warn('db.perf.explain', doc)
else
logger.debug("db.perf.#{collectionName}","#{doc.nscanned} records scanned, #{doc.n} returned in #{doc.millis}ms")
logger.debug('db.perf.query', cursor.selector)
logger.debug('db.perf.explain', doc)
stats = dbperf[collectionName] ?= {total: 0, min: 0, max: 0, count: 0, collection: collectionName}
stats.min = Math.min(stats.min, doc.millis)
stats.max = Math.max(stats.max, doc.millis)
stats.total += doc.millis
stats.count += 1
agg = dbperf.aggregate ?= {total: 0, min: 0, max: 0, count: 0, collection: 'aggregate'}
agg.min = Math.min(agg.min, doc.millis)
agg.max = Math.max(agg.max, doc.millis)
agg.total += doc.millis
agg.count += 1
dumpPerf: ->
return # Not doing it for now
now = new Date()
allStats = ( _.extend(stats,{timestamp: now}) for coll, stats of dbperf )
db.dbperf.insert allStats, (err, inserted) ->
if err
console.error('db.dumpPerf',err)
else if inserted
dbperf = {}
history: (hrs=24, collection='aggregate', fn)->
Seq() .seq ->
db.dbperf.find {collection: collection, timestamp: {$gt: (new Date(Date.now()-hrs*60*60*1000))}}, this
.seq (cursor)->
cursor.toArray(fn)
.catch (err)->
fn(err)
module.exports = new DB()
| 191342 | ###*
* Database helpers to provide easy database access.
*
* Usage:
* db = require(thismodule)
* db.initialize(function(){
* db.dbname.createCollection(...)
* db.dbname.collectionname.find(...)
* })
###
_ = require('underscore')
mongodb = require('mongodb')
assert = require('assert')
util = require('util')
Seq = require('seq')
logger = console
dbperf = {}
class MongoClient
constructor: (dbname, host, port, auth, @_options) ->
if not dbname then throw new Error 'A database name must be provided to create a new db client'
logger.debug "Initializing MongoDb server #{@_host}:#{@_port} with options", @_options
if auth?.user and auth.password and auth.database
user = encodeURIComponent auth.user
password = encodeURIComponent <PASSWORD>
@_connectUrl = "mongodb://#{user}:#{password}@#{host}:#{port}/#{dbname}?authSource=#{auth.database}"
logger.debug "Created client for the '#{dbname}' db, authenticated as #{auth.user} (from db #{auth.database})."
else
@_connectUrl = "mongodb://#{host}:#{port}/#{dbname}"
logger.debug "Created client for the '#{dbname}' db (no authentication info provided)."
close: ->
@db.close()
shortCollectionName: (raw) ->
raw.split('.').pop()
addCollections: (cols, indexesDef) ->
@collections = {}
logger.debug util.format("indexesDef at %j", indexesDef)
for col in cols
name = col.collectionName
if name.substr(0,6) isnt 'system'
if @collections[name] is undefined
@collections[name] = col
logger.debug "OK looking at indexes for collection #{name}"
if indexesDef[name] isnt undefined
for indexDef in indexesDef[name]
ensureIndexCallback = (name)->
return (err, indexName)->
if err
logger.error("ensureIndex",err)
else
logger.debug util.format("Collection #{name} has index named #{indexName}")
col.ensureIndex indexDef, background: true, ensureIndexCallback(name)
else
throw Error('Can\'t override existing member '+name)
getAdmin: ->
return @db.admin()
getCollections: ->
return @collections
initialize: (params, fn) ->
names = _.keys params
connectUrl = @_connectUrl
client = @
logger.info("MongoClient.init: initializing #{names}")
Seq().seq ->
Client = mongodb.MongoClient
Client.connect connectUrl, {db: {w: 1}, server: client._options}, this
.seq (mongoClient)->
client.db = mongoClient.db()
client.db.collections(this)
.seq (cols) ->
client.addCollections(cols, params)
existing = _.pluck(cols, 'collectionName')
logger.debug("MongoClient.init: existing collections '#{existing}'")
missing = _.difference(names, existing)
if missing.length > 0
logger.info("MongoClient.init: missing collections #{missing}")
this(null, missing)
.flatten()
.parMap (name)->
logger.info "Creating missing collection '#{name}'"
client.db.createCollection name, this
.unflatten()
.seq (cols) ->
if cols.length > 0
logger.info("MongoClient.init: still missing collections #{_.pluck cols, 'collectionName'}")
client.addCollections(cols, params)
fn(null,@)
.catch (boo)->
logger.error("MongoClient.initialize #{boo}")
fn(boo)
###
* Connects the sysdb, local and shared databases to their respective databases
* and makes the collections available via thismodule.db.collectionname
* signature: params, [logger], [fn]
* host: 127.0.0.1
* port: 3002
* databases:
* dbname1:
* collection1: [<list of indexes>]
* collection2: []
* dbname2:
* collection: []
* etc..
###
class DB
initialize: (@params, lgger, fn) ->
if fn is undefined and lgger?.log is undefined
fn = lgger
else if lgger isnt undefined
logger = lgger
@_linkingInitiated = {}
@databases = {}
databases = @databases
db = @
params = @params
dbnames = _.keys params?.databases
logger.debug(util.format("MongoDB initializing databases #{dbnames} from params %j", params))
Seq(dbnames).flatten()
.seqEach (dbname)->
db.addDatabase dbname, params.databases[dbname], this
.seq ->
fn?()
.catch (err) ->
fn?(err)
close: (delay = 1000)->
db = @
Seq().seq ->
setTimeout this, delay
.seq ->
this(null, _(db.databases).values)
.flatten()
.seqEach (client)->
client.close(this)
.catch (err)->
if err
logger.error err.stack
###
* Links a database (a.k.a makes the database available via db[dbname], or db.databases[dbname]), and creates it if necessary with all specified collections and indexes
*
* signature: dbname, [collectionsDef], [fn]
* collectionsDef is a plain object, e.g
* collection1: [<list of indexes>]
* collection1: [<list of indexes>]
* etc..
*
###
addDatabase: (dbname, collectionsDef, fn)->
if fn is undefined
if _.isFunction collectionsDef
fn = collectionsDef
collectionsDef = {}
db = @
Seq().seq ->
db.linkDatabase dbname, collectionsDef, this
.seq ->
collections = db.databases[dbname].getCollections()
collectionNames = _.keys collections
intersect = _.intersection collectionNames, _.keys(db)
for collectionName in collectionNames
db.databases[dbname][collectionName] = collections[collectionName]
if collectionName in intersect
logger.warn "Conflicting collections name(s), db.#{collectionName} shortcut unavailable, use db.databases.#{dbname}.#{collectionName}"
else
logger.info "OK db.#{collectionName} is a valid shortcut for db.databases.#{dbname}.#{collectionName}"
db[collectionName] = db.databases[dbname][collectionName]
fn?()
.catch (boo)->
fn?(boo)
###
* Links a database (a.k.a makes the database available via db[dbname] if it already exists
###
linkDatabaseIfExists: (dbname, fn)->
db = @
logger.debug "OK linkDatabaseIfExists #{dbname}"
if db.databases[dbname]?.collections isnt undefined
logger.debug "OK database '#{dbname}' is already linked"
return fn?()
else if _.keys(db.databases).length is 0 and dontCreate
return fn?(new Error("MacMongo can't get an admin (no existing db to get an admin instance off of)"))
else
if @_linkingInitiated[dbname]
setTimeout fn, 500 # linking is in progress, just wait for a bit
else
@_linkingInitiated[dbname] = true
Seq().seq ->
firstDb = db.databases[_.keys(db.databases)[0]]
firstDb.getAdmin().listDatabases this
.seq (dbs)->
dbnames = _.pluck dbs.databases, "name"
if dbname.toLowerCase() not in dbnames
return fn?(new Error("#{dbname.toLowerCase()} not found amongst collections of #{dbname} (#{dbnames})"))
db.linkDatabase(dbname, this)
.seq ->
fn?()
.catch (boo)->
fn?(boo)
###
* Links a database (a.k.a makes the database available via db[dbname], or db.databases[dbname]), and creates it it doesn't already exists
###
linkDatabase: (dbname, collectionsDef, fn)->
if fn is undefined
if _.isFunction collectionsDef
fn = collectionsDef
collectionsDef = {}
db = @
if db.databases[dbname] isnt undefined
logger.debug "OK database '#{dbname}' is already linked"
return fn?()
Seq().seq ->
db.databases[dbname] = new MongoClient(dbname, db.params.host, db.params.port, db.params.auth, db.params.options)
if dbname in _.keys(db)
logger.error "Conflicting database name, db.#{dbname} shortcut is unavailable, use db.databases.#{dbname}"
else
db[dbname] = db.databases[dbname]
db.databases[dbname].initialize collectionsDef, this
.seq ->
fn?()
.catch (boo)->
fn?(boo)
###*
* A utility method to generate GUIDs on the fly
###
uid: ->
n = 4
uid = while n-=1
(Math.abs((Math.random() * 0xFFFFFFF) | 0)).toString(16)
ui = uid.join('')
return ui
###*
* Utility methods to escape dots from attribute names
###
escapeDot: (str) ->
return str.replace(/\./g, "#dot;")
unescapeDot: (o) ->
res = {}
if _.isObject(o) and not _.isArray(o) and not _.isDate(o)
for p of o
res[p.replace(/#dot;/g, ".")] = db.unescapeDot(o[p]) if o.hasOwnProperty(p)
else
res = o
return res
getCollectionNames: (dbname)->
collections = []
if dbname is undefined
for name, database of @databases
logger.info "#{database} has #{_.keys(database.getCollections())}"
collections = collections.concat _.keys(database.getCollections())
else
collections = _.keys(@databases[dbname].getCollections())
return collections
getLayout: ->
layout = {}
for dbname, database of @databases
if layout[dbname] is undefined
layout[dbname] = []
for colname, collection of database.getCollections()
layout[dbname].push colname
return layout
###*
* Logs db performance & explain
###
perfLog: (cursor) ->
cursor.explain (err, doc) ->
if err then console.error('db.perf',err)
if doc
collectionName = cursor.collection.collectionName
if doc.millis > 300
logger.warn("db.perf.#{collectionName}","Latency #{doc.millis}ms: #{doc.n} records returned, #{doc.nscanned} scanned")
logger.warn('db.perf.query', cursor.selector)
logger.warn('db.perf.explain', doc)
else
logger.debug("db.perf.#{collectionName}","#{doc.nscanned} records scanned, #{doc.n} returned in #{doc.millis}ms")
logger.debug('db.perf.query', cursor.selector)
logger.debug('db.perf.explain', doc)
stats = dbperf[collectionName] ?= {total: 0, min: 0, max: 0, count: 0, collection: collectionName}
stats.min = Math.min(stats.min, doc.millis)
stats.max = Math.max(stats.max, doc.millis)
stats.total += doc.millis
stats.count += 1
agg = dbperf.aggregate ?= {total: 0, min: 0, max: 0, count: 0, collection: 'aggregate'}
agg.min = Math.min(agg.min, doc.millis)
agg.max = Math.max(agg.max, doc.millis)
agg.total += doc.millis
agg.count += 1
dumpPerf: ->
return # Not doing it for now
now = new Date()
allStats = ( _.extend(stats,{timestamp: now}) for coll, stats of dbperf )
db.dbperf.insert allStats, (err, inserted) ->
if err
console.error('db.dumpPerf',err)
else if inserted
dbperf = {}
history: (hrs=24, collection='aggregate', fn)->
Seq() .seq ->
db.dbperf.find {collection: collection, timestamp: {$gt: (new Date(Date.now()-hrs*60*60*1000))}}, this
.seq (cursor)->
cursor.toArray(fn)
.catch (err)->
fn(err)
module.exports = new DB()
| true | ###*
* Database helpers to provide easy database access.
*
* Usage:
* db = require(thismodule)
* db.initialize(function(){
* db.dbname.createCollection(...)
* db.dbname.collectionname.find(...)
* })
###
_ = require('underscore')
mongodb = require('mongodb')
assert = require('assert')
util = require('util')
Seq = require('seq')
logger = console
dbperf = {}
class MongoClient
constructor: (dbname, host, port, auth, @_options) ->
if not dbname then throw new Error 'A database name must be provided to create a new db client'
logger.debug "Initializing MongoDb server #{@_host}:#{@_port} with options", @_options
if auth?.user and auth.password and auth.database
user = encodeURIComponent auth.user
password = encodeURIComponent PI:PASSWORD:<PASSWORD>END_PI
@_connectUrl = "mongodb://#{user}:#{password}@#{host}:#{port}/#{dbname}?authSource=#{auth.database}"
logger.debug "Created client for the '#{dbname}' db, authenticated as #{auth.user} (from db #{auth.database})."
else
@_connectUrl = "mongodb://#{host}:#{port}/#{dbname}"
logger.debug "Created client for the '#{dbname}' db (no authentication info provided)."
close: ->
@db.close()
shortCollectionName: (raw) ->
raw.split('.').pop()
addCollections: (cols, indexesDef) ->
@collections = {}
logger.debug util.format("indexesDef at %j", indexesDef)
for col in cols
name = col.collectionName
if name.substr(0,6) isnt 'system'
if @collections[name] is undefined
@collections[name] = col
logger.debug "OK looking at indexes for collection #{name}"
if indexesDef[name] isnt undefined
for indexDef in indexesDef[name]
ensureIndexCallback = (name)->
return (err, indexName)->
if err
logger.error("ensureIndex",err)
else
logger.debug util.format("Collection #{name} has index named #{indexName}")
col.ensureIndex indexDef, background: true, ensureIndexCallback(name)
else
throw Error('Can\'t override existing member '+name)
getAdmin: ->
return @db.admin()
getCollections: ->
return @collections
initialize: (params, fn) ->
names = _.keys params
connectUrl = @_connectUrl
client = @
logger.info("MongoClient.init: initializing #{names}")
Seq().seq ->
Client = mongodb.MongoClient
Client.connect connectUrl, {db: {w: 1}, server: client._options}, this
.seq (mongoClient)->
client.db = mongoClient.db()
client.db.collections(this)
.seq (cols) ->
client.addCollections(cols, params)
existing = _.pluck(cols, 'collectionName')
logger.debug("MongoClient.init: existing collections '#{existing}'")
missing = _.difference(names, existing)
if missing.length > 0
logger.info("MongoClient.init: missing collections #{missing}")
this(null, missing)
.flatten()
.parMap (name)->
logger.info "Creating missing collection '#{name}'"
client.db.createCollection name, this
.unflatten()
.seq (cols) ->
if cols.length > 0
logger.info("MongoClient.init: still missing collections #{_.pluck cols, 'collectionName'}")
client.addCollections(cols, params)
fn(null,@)
.catch (boo)->
logger.error("MongoClient.initialize #{boo}")
fn(boo)
###
* Connects the sysdb, local and shared databases to their respective databases
* and makes the collections available via thismodule.db.collectionname
* signature: params, [logger], [fn]
* host: 127.0.0.1
* port: 3002
* databases:
* dbname1:
* collection1: [<list of indexes>]
* collection2: []
* dbname2:
* collection: []
* etc..
###
class DB
initialize: (@params, lgger, fn) ->
if fn is undefined and lgger?.log is undefined
fn = lgger
else if lgger isnt undefined
logger = lgger
@_linkingInitiated = {}
@databases = {}
databases = @databases
db = @
params = @params
dbnames = _.keys params?.databases
logger.debug(util.format("MongoDB initializing databases #{dbnames} from params %j", params))
Seq(dbnames).flatten()
.seqEach (dbname)->
db.addDatabase dbname, params.databases[dbname], this
.seq ->
fn?()
.catch (err) ->
fn?(err)
close: (delay = 1000)->
db = @
Seq().seq ->
setTimeout this, delay
.seq ->
this(null, _(db.databases).values)
.flatten()
.seqEach (client)->
client.close(this)
.catch (err)->
if err
logger.error err.stack
###
* Links a database (a.k.a makes the database available via db[dbname], or db.databases[dbname]), and creates it if necessary with all specified collections and indexes
*
* signature: dbname, [collectionsDef], [fn]
* collectionsDef is a plain object, e.g
* collection1: [<list of indexes>]
* collection1: [<list of indexes>]
* etc..
*
###
addDatabase: (dbname, collectionsDef, fn)->
if fn is undefined
if _.isFunction collectionsDef
fn = collectionsDef
collectionsDef = {}
db = @
Seq().seq ->
db.linkDatabase dbname, collectionsDef, this
.seq ->
collections = db.databases[dbname].getCollections()
collectionNames = _.keys collections
intersect = _.intersection collectionNames, _.keys(db)
for collectionName in collectionNames
db.databases[dbname][collectionName] = collections[collectionName]
if collectionName in intersect
logger.warn "Conflicting collections name(s), db.#{collectionName} shortcut unavailable, use db.databases.#{dbname}.#{collectionName}"
else
logger.info "OK db.#{collectionName} is a valid shortcut for db.databases.#{dbname}.#{collectionName}"
db[collectionName] = db.databases[dbname][collectionName]
fn?()
.catch (boo)->
fn?(boo)
###
* Links a database (a.k.a makes the database available via db[dbname] if it already exists
###
linkDatabaseIfExists: (dbname, fn)->
db = @
logger.debug "OK linkDatabaseIfExists #{dbname}"
if db.databases[dbname]?.collections isnt undefined
logger.debug "OK database '#{dbname}' is already linked"
return fn?()
else if _.keys(db.databases).length is 0 and dontCreate
return fn?(new Error("MacMongo can't get an admin (no existing db to get an admin instance off of)"))
else
if @_linkingInitiated[dbname]
setTimeout fn, 500 # linking is in progress, just wait for a bit
else
@_linkingInitiated[dbname] = true
Seq().seq ->
firstDb = db.databases[_.keys(db.databases)[0]]
firstDb.getAdmin().listDatabases this
.seq (dbs)->
dbnames = _.pluck dbs.databases, "name"
if dbname.toLowerCase() not in dbnames
return fn?(new Error("#{dbname.toLowerCase()} not found amongst collections of #{dbname} (#{dbnames})"))
db.linkDatabase(dbname, this)
.seq ->
fn?()
.catch (boo)->
fn?(boo)
###
* Links a database (a.k.a makes the database available via db[dbname], or db.databases[dbname]), and creates it it doesn't already exists
###
linkDatabase: (dbname, collectionsDef, fn)->
if fn is undefined
if _.isFunction collectionsDef
fn = collectionsDef
collectionsDef = {}
db = @
if db.databases[dbname] isnt undefined
logger.debug "OK database '#{dbname}' is already linked"
return fn?()
Seq().seq ->
db.databases[dbname] = new MongoClient(dbname, db.params.host, db.params.port, db.params.auth, db.params.options)
if dbname in _.keys(db)
logger.error "Conflicting database name, db.#{dbname} shortcut is unavailable, use db.databases.#{dbname}"
else
db[dbname] = db.databases[dbname]
db.databases[dbname].initialize collectionsDef, this
.seq ->
fn?()
.catch (boo)->
fn?(boo)
###*
* A utility method to generate GUIDs on the fly
###
uid: ->
n = 4
uid = while n-=1
(Math.abs((Math.random() * 0xFFFFFFF) | 0)).toString(16)
ui = uid.join('')
return ui
###*
* Utility methods to escape dots from attribute names
###
escapeDot: (str) ->
return str.replace(/\./g, "#dot;")
unescapeDot: (o) ->
res = {}
if _.isObject(o) and not _.isArray(o) and not _.isDate(o)
for p of o
res[p.replace(/#dot;/g, ".")] = db.unescapeDot(o[p]) if o.hasOwnProperty(p)
else
res = o
return res
getCollectionNames: (dbname)->
collections = []
if dbname is undefined
for name, database of @databases
logger.info "#{database} has #{_.keys(database.getCollections())}"
collections = collections.concat _.keys(database.getCollections())
else
collections = _.keys(@databases[dbname].getCollections())
return collections
getLayout: ->
layout = {}
for dbname, database of @databases
if layout[dbname] is undefined
layout[dbname] = []
for colname, collection of database.getCollections()
layout[dbname].push colname
return layout
###*
* Logs db performance & explain
###
perfLog: (cursor) ->
cursor.explain (err, doc) ->
if err then console.error('db.perf',err)
if doc
collectionName = cursor.collection.collectionName
if doc.millis > 300
logger.warn("db.perf.#{collectionName}","Latency #{doc.millis}ms: #{doc.n} records returned, #{doc.nscanned} scanned")
logger.warn('db.perf.query', cursor.selector)
logger.warn('db.perf.explain', doc)
else
logger.debug("db.perf.#{collectionName}","#{doc.nscanned} records scanned, #{doc.n} returned in #{doc.millis}ms")
logger.debug('db.perf.query', cursor.selector)
logger.debug('db.perf.explain', doc)
stats = dbperf[collectionName] ?= {total: 0, min: 0, max: 0, count: 0, collection: collectionName}
stats.min = Math.min(stats.min, doc.millis)
stats.max = Math.max(stats.max, doc.millis)
stats.total += doc.millis
stats.count += 1
agg = dbperf.aggregate ?= {total: 0, min: 0, max: 0, count: 0, collection: 'aggregate'}
agg.min = Math.min(agg.min, doc.millis)
agg.max = Math.max(agg.max, doc.millis)
agg.total += doc.millis
agg.count += 1
dumpPerf: ->
return # Not doing it for now
now = new Date()
allStats = ( _.extend(stats,{timestamp: now}) for coll, stats of dbperf )
db.dbperf.insert allStats, (err, inserted) ->
if err
console.error('db.dumpPerf',err)
else if inserted
dbperf = {}
history: (hrs=24, collection='aggregate', fn)->
Seq() .seq ->
db.dbperf.find {collection: collection, timestamp: {$gt: (new Date(Date.now()-hrs*60*60*1000))}}, this
.seq (cursor)->
cursor.toArray(fn)
.catch (err)->
fn(err)
module.exports = new DB()
|
[
{
"context": "color: \"Wizard Clothes Color\"\n# new_password: \"New Password\"\n# new_password_verify: \"Verify\"\n# email_su",
"end": 4007,
"score": 0.9993683099746704,
"start": 3995,
"tag": "PASSWORD",
"value": "New Password"
},
{
"context": "ssword: \"New Password\"\n# new_password_verify: \"Verify\"\n# email_subscriptions: \"Email Subscriptions\"\n",
"end": 4042,
"score": 0.9989892840385437,
"start": 4036,
"tag": "PASSWORD",
"value": "Verify"
},
{
"context": " saved: \"Changes Saved\"\n# password_mismatch: \"Password does not match.\"\n#\n# account_profile:\n# edit_settings: \"Edit S",
"end": 4651,
"score": 0.9821507334709167,
"start": 4628,
"tag": "PASSWORD",
"value": "Password does not match"
},
{
"context": "tar_websites: \"Websites\"\n# gravatar_accounts: \"As Seen On\"\n# gravatar_profile_link: \"Full Gravatar Profi",
"end": 5232,
"score": 0.9882887601852417,
"start": 5222,
"tag": "NAME",
"value": "As Seen On"
}
] | app/locale/fa.coffee | cochee/codecombat | 1 | module.exports = nativeDescription: "فارسی", englishDescription: "Persian", translation:
common:
loading: "Loading..."
# modal:
# close: "Close"
# okay: "Okay"
#
# not_found:
# page_not_found: "Page not found"
#
# nav:
# # Header
# sign_up: "Create Account"
# log_in: "Log In"
# log_out: "Log Out"
# play: "Play"
# editor: "Editor"
# blog: "Blog"
# forum: "Forum"
# admin: "Admin"
# # Footer
# home: "Home"
# contribute: "Contribute"
# legal: "Legal"
# about: "About"
# contact: "Contact"
# twitter_follow: "Follow"
#
# forms:
# name: "Name"
# email: "Email"
# message: "Message"
# cancel: "Cancel"
#
# login:
# log_in: "Log In"
# sign_up: "create new account"
# or: ", or "
# recover: "recover account"
#
# signup:
# description: "It's free. Just need a couple things and you'll be good to go:"
# email_announcements: "Receive announcements by email"
# coppa: "13+ or non-USA"
# coppa_why: "(Why?)"
# creating: "Creating Account..."
# sign_up: "Sign Up"
# or: "or "
# log_in: "log in with password"
#
# home:
# slogan: "Learn to Code JavaScript by Playing a Game"
# no_ie: "CodeCombat does not run in IE8 or older. Sorry!"
# no_mobile: "CodeCombat wasn't designed for mobile devices and may not work!"
# play: "Play"
#
# play:
# choose_your_level: "Choose Your Level"
# adventurer_prefix: "You can jump to any level below, or discuss the levels on "
# adventurer_forum: "the Adventurer forum"
# adventurer_suffix: "."
# campaign_beginner: "Beginner Campaign"
# campaign_beginner_description: "... in which you learn the wizardry of programming."
# campaign_dev: "Random Harder Levels"
# campaign_dev_description: "... in which you learn the interface while doing something a little harder."
# campaign_multiplayer: "Multiplayer Arenas"
# campaign_multiplayer_description: "... in which you code head-to-head against other players."
# campaign_player_created: "Player-Created"
# campaign_player_created_description: "... in which you battle against the creativity of your fellow <a href=\"/contribute#artisan\">Artisan Wizards</a>."
# level_difficulty: "Difficulty: "
#
# contact:
# contact_us: "Contact CodeCombat"
# welcome: "Good to hear from you! Use this form to send us email."
# contribute_prefix: "If you're interested in contributing, check out our "
# contribute_page: "contribute page"
# contribute_suffix: "!"
# forum_prefix: "For anything public, please try "
# forum_page: "our forum"
# forum_suffix: " instead."
# sending: "Sending..."
# send: "Send Feedback"
#
diplomat_suggestion:
# title: "Help translate CodeCombat!"
# sub_heading: "We need your language skills."
pitch_body: "We develop CodeCombat in English, but we already have players all over the world. Many of them want to play in Persian but don't speak English, so if you can speak both, please consider signing up to be a Diplomat and help translate both the CodeCombat website and all the levels into Persian."
missing_translations: "Until we can translate everything into Persian, you'll see English when Persian isn't available."
# learn_more: "Learn more about being a Diplomat"
# subscribe_as_diplomat: "Subscribe as a Diplomat"
#
# account_settings:
# title: "Account Settings"
# not_logged_in: "Log in or create an account to change your settings."
# autosave: "Changes Save Automatically"
# me_tab: "Me"
# picture_tab: "Picture"
# wizard_tab: "Wizard"
# password_tab: "Password"
# emails_tab: "Emails"
# language_tab: "Language"
# gravatar_select: "Select which Gravatar photo to use"
# gravatar_add_photos: "Add thumbnails and photos to a Gravatar account for your email to choose an image."
# gravatar_add_more_photos: "Add more photos to your Gravatar account to access them here."
# wizard_color: "Wizard Clothes Color"
# new_password: "New Password"
# new_password_verify: "Verify"
# email_subscriptions: "Email Subscriptions"
# email_announcements: "Announcements"
# email_announcements_description: "Get emails on the latest news and developments at CodeCombat."
# contributor_emails: "Contributor Class Emails"
# contribute_prefix: "We're looking for people to join our party! Check out the "
# contribute_page: "contribute page"
# contribute_suffix: " to find out more."
# email_toggle: "Toggle All"
# language: "Language"
# saving: "Saving..."
# error_saving: "Error Saving"
# saved: "Changes Saved"
# password_mismatch: "Password does not match."
#
# account_profile:
# edit_settings: "Edit Settings"
# profile_for_prefix: "Profile for "
# profile_for_suffix: ""
# profile: "Profile"
# user_not_found: "No user found. Check the URL?"
# gravatar_not_found_mine: "We couldn't find your profile associated with:"
# gravatar_signup_prefix: "Sign up at "
# gravatar_signup_suffix: " to get set up!"
# gravatar_not_found_other: "Alas, there's no profile associated with this person's email address."
# gravatar_contact: "Contact"
# gravatar_websites: "Websites"
# gravatar_accounts: "As Seen On"
# gravatar_profile_link: "Full Gravatar Profile"
#
# play_level:
# level_load_error: "Level could not be loaded."
# done: "Done"
# grid: "Grid"
# customize_wizard: "Customize Wizard"
# home: "Home"
# guide: "Guide"
# multiplayer: "Multiplayer"
# restart: "Restart"
# goals: "Goals"
# action_timeline: "Action Timeline"
# click_to_select: "Click on a unit to select it."
# reload_title: "Reload All Code?"
# reload_really: "Are you sure you want to reload this level back to the beginning?"
# reload_confirm: "Reload All"
# victory_title_prefix: ""
# victory_title_suffix: " Complete"
# victory_sign_up: "Sign Up for Updates"
# victory_sign_up_poke: "Want to get the latest news by email? Create a free account and we'll keep you posted!"
# victory_rate_the_level: "Rate the level: "
# victory_play_next_level: "Play Next Level"
# victory_go_home: "Go Home"
# victory_review: "Tell us more!"
# victory_hour_of_code_done: "Are You Done?"
# victory_hour_of_code_done_yes: "Yes, I'm finished with my Hour of Code!"
# multiplayer_title: "Multiplayer Settings"
# multiplayer_link_description: "Give this link to anyone to have them join you."
# multiplayer_hint_label: "Hint:"
# multiplayer_hint: " Click the link to select all, then press Apple-C or Ctrl-C to copy the link."
# multiplayer_coming_soon: "More multiplayer features to come!"
# guide_title: "Guide"
# tome_minion_spells: "Your Minions' Spells"
# tome_read_only_spells: "Read-Only Spells"
# tome_other_units: "Other Units"
# tome_cast_button_castable: "Cast"
# tome_cast_button_casting: "Casting"
# tome_cast_button_cast: "Spell Cast"
# tome_autocast_delay: "Autocast Delay"
# tome_autocast_1: "1 second"
# tome_autocast_3: "3 seconds"
# tome_autocast_5: "5 seconds"
# tome_autocast_manual: "Manual"
# tome_select_spell: "Select a Spell"
# tome_select_a_thang: "Select Someone for "
# tome_available_spells: "Available Spells"
# hud_continue: "Continue (press shift-space)"
| 22901 | module.exports = nativeDescription: "فارسی", englishDescription: "Persian", translation:
common:
loading: "Loading..."
# modal:
# close: "Close"
# okay: "Okay"
#
# not_found:
# page_not_found: "Page not found"
#
# nav:
# # Header
# sign_up: "Create Account"
# log_in: "Log In"
# log_out: "Log Out"
# play: "Play"
# editor: "Editor"
# blog: "Blog"
# forum: "Forum"
# admin: "Admin"
# # Footer
# home: "Home"
# contribute: "Contribute"
# legal: "Legal"
# about: "About"
# contact: "Contact"
# twitter_follow: "Follow"
#
# forms:
# name: "Name"
# email: "Email"
# message: "Message"
# cancel: "Cancel"
#
# login:
# log_in: "Log In"
# sign_up: "create new account"
# or: ", or "
# recover: "recover account"
#
# signup:
# description: "It's free. Just need a couple things and you'll be good to go:"
# email_announcements: "Receive announcements by email"
# coppa: "13+ or non-USA"
# coppa_why: "(Why?)"
# creating: "Creating Account..."
# sign_up: "Sign Up"
# or: "or "
# log_in: "log in with password"
#
# home:
# slogan: "Learn to Code JavaScript by Playing a Game"
# no_ie: "CodeCombat does not run in IE8 or older. Sorry!"
# no_mobile: "CodeCombat wasn't designed for mobile devices and may not work!"
# play: "Play"
#
# play:
# choose_your_level: "Choose Your Level"
# adventurer_prefix: "You can jump to any level below, or discuss the levels on "
# adventurer_forum: "the Adventurer forum"
# adventurer_suffix: "."
# campaign_beginner: "Beginner Campaign"
# campaign_beginner_description: "... in which you learn the wizardry of programming."
# campaign_dev: "Random Harder Levels"
# campaign_dev_description: "... in which you learn the interface while doing something a little harder."
# campaign_multiplayer: "Multiplayer Arenas"
# campaign_multiplayer_description: "... in which you code head-to-head against other players."
# campaign_player_created: "Player-Created"
# campaign_player_created_description: "... in which you battle against the creativity of your fellow <a href=\"/contribute#artisan\">Artisan Wizards</a>."
# level_difficulty: "Difficulty: "
#
# contact:
# contact_us: "Contact CodeCombat"
# welcome: "Good to hear from you! Use this form to send us email."
# contribute_prefix: "If you're interested in contributing, check out our "
# contribute_page: "contribute page"
# contribute_suffix: "!"
# forum_prefix: "For anything public, please try "
# forum_page: "our forum"
# forum_suffix: " instead."
# sending: "Sending..."
# send: "Send Feedback"
#
diplomat_suggestion:
# title: "Help translate CodeCombat!"
# sub_heading: "We need your language skills."
pitch_body: "We develop CodeCombat in English, but we already have players all over the world. Many of them want to play in Persian but don't speak English, so if you can speak both, please consider signing up to be a Diplomat and help translate both the CodeCombat website and all the levels into Persian."
missing_translations: "Until we can translate everything into Persian, you'll see English when Persian isn't available."
# learn_more: "Learn more about being a Diplomat"
# subscribe_as_diplomat: "Subscribe as a Diplomat"
#
# account_settings:
# title: "Account Settings"
# not_logged_in: "Log in or create an account to change your settings."
# autosave: "Changes Save Automatically"
# me_tab: "Me"
# picture_tab: "Picture"
# wizard_tab: "Wizard"
# password_tab: "Password"
# emails_tab: "Emails"
# language_tab: "Language"
# gravatar_select: "Select which Gravatar photo to use"
# gravatar_add_photos: "Add thumbnails and photos to a Gravatar account for your email to choose an image."
# gravatar_add_more_photos: "Add more photos to your Gravatar account to access them here."
# wizard_color: "Wizard Clothes Color"
# new_password: "<PASSWORD>"
# new_password_verify: "<PASSWORD>"
# email_subscriptions: "Email Subscriptions"
# email_announcements: "Announcements"
# email_announcements_description: "Get emails on the latest news and developments at CodeCombat."
# contributor_emails: "Contributor Class Emails"
# contribute_prefix: "We're looking for people to join our party! Check out the "
# contribute_page: "contribute page"
# contribute_suffix: " to find out more."
# email_toggle: "Toggle All"
# language: "Language"
# saving: "Saving..."
# error_saving: "Error Saving"
# saved: "Changes Saved"
# password_mismatch: "<PASSWORD>."
#
# account_profile:
# edit_settings: "Edit Settings"
# profile_for_prefix: "Profile for "
# profile_for_suffix: ""
# profile: "Profile"
# user_not_found: "No user found. Check the URL?"
# gravatar_not_found_mine: "We couldn't find your profile associated with:"
# gravatar_signup_prefix: "Sign up at "
# gravatar_signup_suffix: " to get set up!"
# gravatar_not_found_other: "Alas, there's no profile associated with this person's email address."
# gravatar_contact: "Contact"
# gravatar_websites: "Websites"
# gravatar_accounts: "<NAME>"
# gravatar_profile_link: "Full Gravatar Profile"
#
# play_level:
# level_load_error: "Level could not be loaded."
# done: "Done"
# grid: "Grid"
# customize_wizard: "Customize Wizard"
# home: "Home"
# guide: "Guide"
# multiplayer: "Multiplayer"
# restart: "Restart"
# goals: "Goals"
# action_timeline: "Action Timeline"
# click_to_select: "Click on a unit to select it."
# reload_title: "Reload All Code?"
# reload_really: "Are you sure you want to reload this level back to the beginning?"
# reload_confirm: "Reload All"
# victory_title_prefix: ""
# victory_title_suffix: " Complete"
# victory_sign_up: "Sign Up for Updates"
# victory_sign_up_poke: "Want to get the latest news by email? Create a free account and we'll keep you posted!"
# victory_rate_the_level: "Rate the level: "
# victory_play_next_level: "Play Next Level"
# victory_go_home: "Go Home"
# victory_review: "Tell us more!"
# victory_hour_of_code_done: "Are You Done?"
# victory_hour_of_code_done_yes: "Yes, I'm finished with my Hour of Code!"
# multiplayer_title: "Multiplayer Settings"
# multiplayer_link_description: "Give this link to anyone to have them join you."
# multiplayer_hint_label: "Hint:"
# multiplayer_hint: " Click the link to select all, then press Apple-C or Ctrl-C to copy the link."
# multiplayer_coming_soon: "More multiplayer features to come!"
# guide_title: "Guide"
# tome_minion_spells: "Your Minions' Spells"
# tome_read_only_spells: "Read-Only Spells"
# tome_other_units: "Other Units"
# tome_cast_button_castable: "Cast"
# tome_cast_button_casting: "Casting"
# tome_cast_button_cast: "Spell Cast"
# tome_autocast_delay: "Autocast Delay"
# tome_autocast_1: "1 second"
# tome_autocast_3: "3 seconds"
# tome_autocast_5: "5 seconds"
# tome_autocast_manual: "Manual"
# tome_select_spell: "Select a Spell"
# tome_select_a_thang: "Select Someone for "
# tome_available_spells: "Available Spells"
# hud_continue: "Continue (press shift-space)"
| true | module.exports = nativeDescription: "فارسی", englishDescription: "Persian", translation:
common:
loading: "Loading..."
# modal:
# close: "Close"
# okay: "Okay"
#
# not_found:
# page_not_found: "Page not found"
#
# nav:
# # Header
# sign_up: "Create Account"
# log_in: "Log In"
# log_out: "Log Out"
# play: "Play"
# editor: "Editor"
# blog: "Blog"
# forum: "Forum"
# admin: "Admin"
# # Footer
# home: "Home"
# contribute: "Contribute"
# legal: "Legal"
# about: "About"
# contact: "Contact"
# twitter_follow: "Follow"
#
# forms:
# name: "Name"
# email: "Email"
# message: "Message"
# cancel: "Cancel"
#
# login:
# log_in: "Log In"
# sign_up: "create new account"
# or: ", or "
# recover: "recover account"
#
# signup:
# description: "It's free. Just need a couple things and you'll be good to go:"
# email_announcements: "Receive announcements by email"
# coppa: "13+ or non-USA"
# coppa_why: "(Why?)"
# creating: "Creating Account..."
# sign_up: "Sign Up"
# or: "or "
# log_in: "log in with password"
#
# home:
# slogan: "Learn to Code JavaScript by Playing a Game"
# no_ie: "CodeCombat does not run in IE8 or older. Sorry!"
# no_mobile: "CodeCombat wasn't designed for mobile devices and may not work!"
# play: "Play"
#
# play:
# choose_your_level: "Choose Your Level"
# adventurer_prefix: "You can jump to any level below, or discuss the levels on "
# adventurer_forum: "the Adventurer forum"
# adventurer_suffix: "."
# campaign_beginner: "Beginner Campaign"
# campaign_beginner_description: "... in which you learn the wizardry of programming."
# campaign_dev: "Random Harder Levels"
# campaign_dev_description: "... in which you learn the interface while doing something a little harder."
# campaign_multiplayer: "Multiplayer Arenas"
# campaign_multiplayer_description: "... in which you code head-to-head against other players."
# campaign_player_created: "Player-Created"
# campaign_player_created_description: "... in which you battle against the creativity of your fellow <a href=\"/contribute#artisan\">Artisan Wizards</a>."
# level_difficulty: "Difficulty: "
#
# contact:
# contact_us: "Contact CodeCombat"
# welcome: "Good to hear from you! Use this form to send us email."
# contribute_prefix: "If you're interested in contributing, check out our "
# contribute_page: "contribute page"
# contribute_suffix: "!"
# forum_prefix: "For anything public, please try "
# forum_page: "our forum"
# forum_suffix: " instead."
# sending: "Sending..."
# send: "Send Feedback"
#
diplomat_suggestion:
# title: "Help translate CodeCombat!"
# sub_heading: "We need your language skills."
pitch_body: "We develop CodeCombat in English, but we already have players all over the world. Many of them want to play in Persian but don't speak English, so if you can speak both, please consider signing up to be a Diplomat and help translate both the CodeCombat website and all the levels into Persian."
missing_translations: "Until we can translate everything into Persian, you'll see English when Persian isn't available."
# learn_more: "Learn more about being a Diplomat"
# subscribe_as_diplomat: "Subscribe as a Diplomat"
#
# account_settings:
# title: "Account Settings"
# not_logged_in: "Log in or create an account to change your settings."
# autosave: "Changes Save Automatically"
# me_tab: "Me"
# picture_tab: "Picture"
# wizard_tab: "Wizard"
# password_tab: "Password"
# emails_tab: "Emails"
# language_tab: "Language"
# gravatar_select: "Select which Gravatar photo to use"
# gravatar_add_photos: "Add thumbnails and photos to a Gravatar account for your email to choose an image."
# gravatar_add_more_photos: "Add more photos to your Gravatar account to access them here."
# wizard_color: "Wizard Clothes Color"
# new_password: "PI:PASSWORD:<PASSWORD>END_PI"
# new_password_verify: "PI:PASSWORD:<PASSWORD>END_PI"
# email_subscriptions: "Email Subscriptions"
# email_announcements: "Announcements"
# email_announcements_description: "Get emails on the latest news and developments at CodeCombat."
# contributor_emails: "Contributor Class Emails"
# contribute_prefix: "We're looking for people to join our party! Check out the "
# contribute_page: "contribute page"
# contribute_suffix: " to find out more."
# email_toggle: "Toggle All"
# language: "Language"
# saving: "Saving..."
# error_saving: "Error Saving"
# saved: "Changes Saved"
# password_mismatch: "PI:PASSWORD:<PASSWORD>END_PI."
#
# account_profile:
# edit_settings: "Edit Settings"
# profile_for_prefix: "Profile for "
# profile_for_suffix: ""
# profile: "Profile"
# user_not_found: "No user found. Check the URL?"
# gravatar_not_found_mine: "We couldn't find your profile associated with:"
# gravatar_signup_prefix: "Sign up at "
# gravatar_signup_suffix: " to get set up!"
# gravatar_not_found_other: "Alas, there's no profile associated with this person's email address."
# gravatar_contact: "Contact"
# gravatar_websites: "Websites"
# gravatar_accounts: "PI:NAME:<NAME>END_PI"
# gravatar_profile_link: "Full Gravatar Profile"
#
# play_level:
# level_load_error: "Level could not be loaded."
# done: "Done"
# grid: "Grid"
# customize_wizard: "Customize Wizard"
# home: "Home"
# guide: "Guide"
# multiplayer: "Multiplayer"
# restart: "Restart"
# goals: "Goals"
# action_timeline: "Action Timeline"
# click_to_select: "Click on a unit to select it."
# reload_title: "Reload All Code?"
# reload_really: "Are you sure you want to reload this level back to the beginning?"
# reload_confirm: "Reload All"
# victory_title_prefix: ""
# victory_title_suffix: " Complete"
# victory_sign_up: "Sign Up for Updates"
# victory_sign_up_poke: "Want to get the latest news by email? Create a free account and we'll keep you posted!"
# victory_rate_the_level: "Rate the level: "
# victory_play_next_level: "Play Next Level"
# victory_go_home: "Go Home"
# victory_review: "Tell us more!"
# victory_hour_of_code_done: "Are You Done?"
# victory_hour_of_code_done_yes: "Yes, I'm finished with my Hour of Code!"
# multiplayer_title: "Multiplayer Settings"
# multiplayer_link_description: "Give this link to anyone to have them join you."
# multiplayer_hint_label: "Hint:"
# multiplayer_hint: " Click the link to select all, then press Apple-C or Ctrl-C to copy the link."
# multiplayer_coming_soon: "More multiplayer features to come!"
# guide_title: "Guide"
# tome_minion_spells: "Your Minions' Spells"
# tome_read_only_spells: "Read-Only Spells"
# tome_other_units: "Other Units"
# tome_cast_button_castable: "Cast"
# tome_cast_button_casting: "Casting"
# tome_cast_button_cast: "Spell Cast"
# tome_autocast_delay: "Autocast Delay"
# tome_autocast_1: "1 second"
# tome_autocast_3: "3 seconds"
# tome_autocast_5: "5 seconds"
# tome_autocast_manual: "Manual"
# tome_select_spell: "Select a Spell"
# tome_select_a_thang: "Select Someone for "
# tome_available_spells: "Available Spells"
# hud_continue: "Continue (press shift-space)"
|
[
{
"context": "structor: (@alias = null, @hostname, @directory, @username, @port = \"22\", @localFiles = [], @usePassword = f",
"end": 798,
"score": 0.757660984992981,
"start": 790,
"tag": "USERNAME",
"value": "username"
},
{
"context": ") ->\n super( @alias, @hostname, @directory, @username, @port, @localFiles, @usePassword, @lastOpenDirec",
"end": 1013,
"score": 0.5241179466247559,
"start": 1005,
"tag": "USERNAME",
"value": "username"
},
{
"context": " @hostname,\n port: @port,\n username: @username,\n }\n\n if atom.config.get('remote-edit.a",
"end": 1209,
"score": 0.8548855781555176,
"start": 1200,
"tag": "USERNAME",
"value": "@username"
},
{
"context": ")\n {host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), pas",
"end": 1849,
"score": 0.7690384387969971,
"start": 1840,
"tag": "USERNAME",
"value": "@username"
},
{
"context": "e\n {host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), pas",
"end": 1995,
"score": 0.990870475769043,
"start": 1986,
"tag": "USERNAME",
"value": "@username"
},
{
"context": ")\n {host: @hostname, port: @port, username: @username, password: keytarPassword}\n else\n {ho",
"end": 2341,
"score": 0.9670060873031616,
"start": 2332,
"tag": "USERNAME",
"value": "@username"
},
{
"context": "tname, port: @port, username: @username, password: keytarPassword}\n else\n {host: @hostname, port: @port",
"end": 2367,
"score": 0.8396361470222473,
"start": 2353,
"tag": "PASSWORD",
"value": "keytarPassword"
},
{
"context": "e\n {host: @hostname, port: @port, username: @username, password: @password}\n\n getPrivateKey: (path) ",
"end": 2438,
"score": 0.9745093584060669,
"start": 2429,
"tag": "USERNAME",
"value": "@username"
},
{
"context": "tname, port: @port, username: @username, password: @password}\n\n getPrivateKey: (path) ->\n if path[0] =",
"end": 2459,
"score": 0.9611951112747192,
"start": 2450,
"tag": "PASSWORD",
"value": "@password"
},
{
"context": "r.emit 'info', {message: \"Connecting to sftp://#{@username}@#{@hostname}:#{@port}\", type: 'info'}\n asyn",
"end": 3955,
"score": 0.7886764407157898,
"start": 3947,
"tag": "USERNAME",
"value": "username"
},
{
"context": "sage: \"Error occured when connecting to sftp://#{@username}@#{@hostname}:#{@port}\", type: 'error'}\n ",
"end": 4623,
"score": 0.7162187099456787,
"start": 4615,
"tag": "USERNAME",
"value": "username"
},
{
"context": "', {message: \"Successfully connected to sftp://#{@username}@#{@hostname}:#{@port}\", type: 'success'}\n ",
"end": 4846,
"score": 0.8284196257591248,
"start": 4838,
"tag": "USERNAME",
"value": "username"
},
{
"context": "r occured when reading remote directory sftp://#{@username}@#{@hostname}:#{@port}:#{path}\", type: 'error'} )",
"end": 5954,
"score": 0.6888958215713501,
"start": 5946,
"tag": "USERNAME",
"value": "username"
},
{
"context": "('info', {message: \"Getting remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path",
"end": 6323,
"score": 0.9709435701370239,
"start": 6315,
"tag": "USERNAME",
"value": "username"
},
{
"context": "essage: \"Error when reading remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path",
"end": 6713,
"score": 0.9457857012748718,
"start": 6705,
"tag": "USERNAME",
"value": "username"
},
{
"context": "{message: \"Successfully read remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path",
"end": 6880,
"score": 0.7527759075164795,
"start": 6871,
"tag": "USERNAME",
"value": "@username"
},
{
"context": "t 'info', {message: \"Writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path",
"end": 7121,
"score": 0.8217557072639465,
"start": 7112,
"tag": "USERNAME",
"value": "@username"
},
{
"context": "\"Error occured when writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path",
"end": 7510,
"score": 0.9514104723930359,
"start": 7502,
"tag": "USERNAME",
"value": "username"
},
{
"context": "essage: \"Successfully wrote remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path",
"end": 7721,
"score": 0.947396457195282,
"start": 7713,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ias\n @hostname\n @directory\n @username\n @port\n localFiles: localFile.seria",
"end": 7943,
"score": 0.7918186783790588,
"start": 7935,
"tag": "USERNAME",
"value": "username"
}
] | lib/model/sftp-host.coffee | 18zehn/remote-edit | 171 | Host = require './host'
RemoteFile = require './remote-file'
LocalFile = require './local-file'
fs = require 'fs-plus'
ssh2 = require 'ssh2'
async = require 'async'
util = require 'util'
filesize = require 'file-size'
moment = require 'moment'
Serializable = require 'serializable'
Path = require 'path'
osenv = require 'osenv'
_ = require 'underscore-plus'
try
keytar = require 'keytar'
catch err
console.debug 'Keytar could not be loaded! Passwords will be stored in cleartext to remoteEdit.json!'
keytar = undefined
module.exports =
class SftpHost extends Host
Serializable.includeInto(this)
atom.deserializers.add(this)
Host.registerDeserializers(SftpHost)
connection: undefined
protocol: "sftp"
constructor: (@alias = null, @hostname, @directory, @username, @port = "22", @localFiles = [], @usePassword = false, @useAgent = true, @usePrivateKey = false, @password, @passphrase, @privateKeyPath, @lastOpenDirectory) ->
super( @alias, @hostname, @directory, @username, @port, @localFiles, @usePassword, @lastOpenDirectory)
getConnectionStringUsingAgent: ->
connectionString = {
host: @hostname,
port: @port,
username: @username,
}
if atom.config.get('remote-edit.agentToUse') != 'Default'
_.extend(connectionString, {agent: atom.config.get('remote-edit.agentToUse')})
else if process.platform == "win32"
_.extend(connectionString, {agent: 'pageant'})
else
_.extend(connectionString, {agent: process.env['SSH_AUTH_SOCK']})
connectionString
getConnectionStringUsingKey: ->
if atom.config.get('remote-edit.storePasswordsUsingKeytar') and (keytar?)
keytarPassphrase = keytar.getPassword(@getServiceNamePassphrase(), @getServiceAccount())
{host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), passphrase: keytarPassphrase}
else
{host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), passphrase: @passphrase}
getConnectionStringUsingPassword: ->
if atom.config.get('remote-edit.storePasswordsUsingKeytar') and (keytar?)
keytarPassword = keytar.getPassword(@getServiceNamePassword(), @getServiceAccount())
{host: @hostname, port: @port, username: @username, password: keytarPassword}
else
{host: @hostname, port: @port, username: @username, password: @password}
getPrivateKey: (path) ->
if path[0] == "~"
path = Path.normalize(osenv.home() + path.substring(1, path.length))
return fs.readFileSync(path, 'ascii', (err, data) ->
throw err if err?
return data.trim()
)
createRemoteFileFromFile: (path, file) ->
remoteFile = new RemoteFile(Path.normalize("#{path}/#{file.filename}").split(Path.sep).join('/'), (file.longname[0] == '-'), (file.longname[0] == 'd'), (file.longname[0] == 'l'), filesize(file.attrs.size).human(), parseInt(file.attrs.mode, 10).toString(8).substr(2, 4), moment(file.attrs.mtime * 1000).format("HH:mm:ss DD/MM/YYYY"))
return remoteFile
getServiceNamePassword: ->
"atom.remote-edit.ssh.password"
getServiceNamePassphrase: ->
"atom.remote-edit.ssh.passphrase"
####################
# Overridden methods
getConnectionString: (connectionOptions) ->
if @useAgent
return _.extend(@getConnectionStringUsingAgent(), connectionOptions)
else if @usePrivateKey
return _.extend(@getConnectionStringUsingKey(), connectionOptions)
else if @usePassword
return _.extend(@getConnectionStringUsingPassword(), connectionOptions)
else
throw new Error("No valid connection method is set for SftpHost!")
close: (callback) ->
@connection?.end()
callback?(null)
connect: (callback, connectionOptions = {}) ->
@emitter.emit 'info', {message: "Connecting to sftp://#{@username}@#{@hostname}:#{@port}", type: 'info'}
async.waterfall([
(callback) =>
if @usePrivateKey
fs.exists(@privateKeyPath, ((exists) =>
if exists
callback(null)
else
@emitter.emit 'info', {message: "Private key does not exist!", type: 'error'}
callback(new Error("Private key does not exist"))
)
)
else
callback(null)
(callback) =>
@connection = new ssh2()
@connection.on 'error', (err) =>
@emitter.emit 'info', {message: "Error occured when connecting to sftp://#{@username}@#{@hostname}:#{@port}", type: 'error'}
@connection.end()
callback(err)
@connection.on 'ready', =>
@emitter.emit 'info', {message: "Successfully connected to sftp://#{@username}@#{@hostname}:#{@port}", type: 'success'}
callback(null)
@connection.connect(@getConnectionString(connectionOptions))
], (err) ->
callback?(err)
)
isConnected: ->
@connection? and @connection._state == 'authenticated'
getFilesMetadata: (path, callback) ->
async.waterfall([
(callback) =>
@connection.sftp(callback)
(sftp, callback) ->
sftp.readdir(path, callback)
(files, callback) =>
async.map(files, ((file, callback) => callback(null, @createRemoteFileFromFile(path, file))), callback)
(objects, callback) ->
objects.push(new RemoteFile((path + "/.."), false, true, false, null, null, null))
if atom.config.get 'remote-edit.showHiddenFiles'
callback(null, objects)
else
async.filter(objects, ((item, callback) -> item.isHidden(callback)), ((result) -> callback(null, result)))
], (err, result) =>
if err?
@emitter.emit('info', {message: "Error occured when reading remote directory sftp://#{@username}@#{@hostname}:#{@port}:#{path}", type: 'error'} )
console.error err if err?
callback?(err)
else
callback?(err, (result.sort (a, b) -> return if a.name.toLowerCase() >= b.name.toLowerCase() then 1 else -1))
)
getFile: (localFile, callback) ->
@emitter.emit('info', {message: "Getting remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'info'})
async.waterfall([
(callback) =>
@connection.sftp(callback)
(sftp, callback) =>
sftp.fastGet(localFile.remoteFile.path, localFile.path, (err) => callback(err, sftp))
], (err, sftp) =>
@emitter.emit('info', {message: "Error when reading remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'error'}) if err?
@emitter.emit('info', {message: "Successfully read remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'success'}) if !err?
callback?(err, localFile)
)
writeFile: (localFile, callback) ->
@emitter.emit 'info', {message: "Writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'info'}
async.waterfall([
(callback) =>
@connection.sftp(callback)
(sftp, callback) ->
sftp.fastPut(localFile.path, localFile.remoteFile.path, callback)
], (err) =>
if err?
@emitter.emit('info', {message: "Error occured when writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'error'})
console.error err if err?
else
@emitter.emit('info', {message: "Successfully wrote remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'success'})
@close()
callback?(err)
)
serializeParams: ->
{
@alias
@hostname
@directory
@username
@port
localFiles: localFile.serialize() for localFile in @localFiles
@useAgent
@usePrivateKey
@usePassword
@password
@passphrase
@privateKeyPath
@lastOpenDirectory
}
deserializeParams: (params) ->
tmpArray = []
tmpArray.push(LocalFile.deserialize(localFile, host: this)) for localFile in params.localFiles
params.localFiles = tmpArray
params
| 107312 | Host = require './host'
RemoteFile = require './remote-file'
LocalFile = require './local-file'
fs = require 'fs-plus'
ssh2 = require 'ssh2'
async = require 'async'
util = require 'util'
filesize = require 'file-size'
moment = require 'moment'
Serializable = require 'serializable'
Path = require 'path'
osenv = require 'osenv'
_ = require 'underscore-plus'
try
keytar = require 'keytar'
catch err
console.debug 'Keytar could not be loaded! Passwords will be stored in cleartext to remoteEdit.json!'
keytar = undefined
module.exports =
class SftpHost extends Host
Serializable.includeInto(this)
atom.deserializers.add(this)
Host.registerDeserializers(SftpHost)
connection: undefined
protocol: "sftp"
constructor: (@alias = null, @hostname, @directory, @username, @port = "22", @localFiles = [], @usePassword = false, @useAgent = true, @usePrivateKey = false, @password, @passphrase, @privateKeyPath, @lastOpenDirectory) ->
super( @alias, @hostname, @directory, @username, @port, @localFiles, @usePassword, @lastOpenDirectory)
getConnectionStringUsingAgent: ->
connectionString = {
host: @hostname,
port: @port,
username: @username,
}
if atom.config.get('remote-edit.agentToUse') != 'Default'
_.extend(connectionString, {agent: atom.config.get('remote-edit.agentToUse')})
else if process.platform == "win32"
_.extend(connectionString, {agent: 'pageant'})
else
_.extend(connectionString, {agent: process.env['SSH_AUTH_SOCK']})
connectionString
getConnectionStringUsingKey: ->
if atom.config.get('remote-edit.storePasswordsUsingKeytar') and (keytar?)
keytarPassphrase = keytar.getPassword(@getServiceNamePassphrase(), @getServiceAccount())
{host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), passphrase: keytarPassphrase}
else
{host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), passphrase: @passphrase}
getConnectionStringUsingPassword: ->
if atom.config.get('remote-edit.storePasswordsUsingKeytar') and (keytar?)
keytarPassword = keytar.getPassword(@getServiceNamePassword(), @getServiceAccount())
{host: @hostname, port: @port, username: @username, password: <PASSWORD>}
else
{host: @hostname, port: @port, username: @username, password: <PASSWORD>}
getPrivateKey: (path) ->
if path[0] == "~"
path = Path.normalize(osenv.home() + path.substring(1, path.length))
return fs.readFileSync(path, 'ascii', (err, data) ->
throw err if err?
return data.trim()
)
createRemoteFileFromFile: (path, file) ->
remoteFile = new RemoteFile(Path.normalize("#{path}/#{file.filename}").split(Path.sep).join('/'), (file.longname[0] == '-'), (file.longname[0] == 'd'), (file.longname[0] == 'l'), filesize(file.attrs.size).human(), parseInt(file.attrs.mode, 10).toString(8).substr(2, 4), moment(file.attrs.mtime * 1000).format("HH:mm:ss DD/MM/YYYY"))
return remoteFile
getServiceNamePassword: ->
"atom.remote-edit.ssh.password"
getServiceNamePassphrase: ->
"atom.remote-edit.ssh.passphrase"
####################
# Overridden methods
getConnectionString: (connectionOptions) ->
if @useAgent
return _.extend(@getConnectionStringUsingAgent(), connectionOptions)
else if @usePrivateKey
return _.extend(@getConnectionStringUsingKey(), connectionOptions)
else if @usePassword
return _.extend(@getConnectionStringUsingPassword(), connectionOptions)
else
throw new Error("No valid connection method is set for SftpHost!")
close: (callback) ->
@connection?.end()
callback?(null)
connect: (callback, connectionOptions = {}) ->
@emitter.emit 'info', {message: "Connecting to sftp://#{@username}@#{@hostname}:#{@port}", type: 'info'}
async.waterfall([
(callback) =>
if @usePrivateKey
fs.exists(@privateKeyPath, ((exists) =>
if exists
callback(null)
else
@emitter.emit 'info', {message: "Private key does not exist!", type: 'error'}
callback(new Error("Private key does not exist"))
)
)
else
callback(null)
(callback) =>
@connection = new ssh2()
@connection.on 'error', (err) =>
@emitter.emit 'info', {message: "Error occured when connecting to sftp://#{@username}@#{@hostname}:#{@port}", type: 'error'}
@connection.end()
callback(err)
@connection.on 'ready', =>
@emitter.emit 'info', {message: "Successfully connected to sftp://#{@username}@#{@hostname}:#{@port}", type: 'success'}
callback(null)
@connection.connect(@getConnectionString(connectionOptions))
], (err) ->
callback?(err)
)
isConnected: ->
@connection? and @connection._state == 'authenticated'
getFilesMetadata: (path, callback) ->
async.waterfall([
(callback) =>
@connection.sftp(callback)
(sftp, callback) ->
sftp.readdir(path, callback)
(files, callback) =>
async.map(files, ((file, callback) => callback(null, @createRemoteFileFromFile(path, file))), callback)
(objects, callback) ->
objects.push(new RemoteFile((path + "/.."), false, true, false, null, null, null))
if atom.config.get 'remote-edit.showHiddenFiles'
callback(null, objects)
else
async.filter(objects, ((item, callback) -> item.isHidden(callback)), ((result) -> callback(null, result)))
], (err, result) =>
if err?
@emitter.emit('info', {message: "Error occured when reading remote directory sftp://#{@username}@#{@hostname}:#{@port}:#{path}", type: 'error'} )
console.error err if err?
callback?(err)
else
callback?(err, (result.sort (a, b) -> return if a.name.toLowerCase() >= b.name.toLowerCase() then 1 else -1))
)
getFile: (localFile, callback) ->
@emitter.emit('info', {message: "Getting remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'info'})
async.waterfall([
(callback) =>
@connection.sftp(callback)
(sftp, callback) =>
sftp.fastGet(localFile.remoteFile.path, localFile.path, (err) => callback(err, sftp))
], (err, sftp) =>
@emitter.emit('info', {message: "Error when reading remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'error'}) if err?
@emitter.emit('info', {message: "Successfully read remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'success'}) if !err?
callback?(err, localFile)
)
writeFile: (localFile, callback) ->
@emitter.emit 'info', {message: "Writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'info'}
async.waterfall([
(callback) =>
@connection.sftp(callback)
(sftp, callback) ->
sftp.fastPut(localFile.path, localFile.remoteFile.path, callback)
], (err) =>
if err?
@emitter.emit('info', {message: "Error occured when writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'error'})
console.error err if err?
else
@emitter.emit('info', {message: "Successfully wrote remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'success'})
@close()
callback?(err)
)
serializeParams: ->
{
@alias
@hostname
@directory
@username
@port
localFiles: localFile.serialize() for localFile in @localFiles
@useAgent
@usePrivateKey
@usePassword
@password
@passphrase
@privateKeyPath
@lastOpenDirectory
}
deserializeParams: (params) ->
tmpArray = []
tmpArray.push(LocalFile.deserialize(localFile, host: this)) for localFile in params.localFiles
params.localFiles = tmpArray
params
| true | Host = require './host'
RemoteFile = require './remote-file'
LocalFile = require './local-file'
fs = require 'fs-plus'
ssh2 = require 'ssh2'
async = require 'async'
util = require 'util'
filesize = require 'file-size'
moment = require 'moment'
Serializable = require 'serializable'
Path = require 'path'
osenv = require 'osenv'
_ = require 'underscore-plus'
try
keytar = require 'keytar'
catch err
console.debug 'Keytar could not be loaded! Passwords will be stored in cleartext to remoteEdit.json!'
keytar = undefined
module.exports =
class SftpHost extends Host
Serializable.includeInto(this)
atom.deserializers.add(this)
Host.registerDeserializers(SftpHost)
connection: undefined
protocol: "sftp"
constructor: (@alias = null, @hostname, @directory, @username, @port = "22", @localFiles = [], @usePassword = false, @useAgent = true, @usePrivateKey = false, @password, @passphrase, @privateKeyPath, @lastOpenDirectory) ->
super( @alias, @hostname, @directory, @username, @port, @localFiles, @usePassword, @lastOpenDirectory)
getConnectionStringUsingAgent: ->
connectionString = {
host: @hostname,
port: @port,
username: @username,
}
if atom.config.get('remote-edit.agentToUse') != 'Default'
_.extend(connectionString, {agent: atom.config.get('remote-edit.agentToUse')})
else if process.platform == "win32"
_.extend(connectionString, {agent: 'pageant'})
else
_.extend(connectionString, {agent: process.env['SSH_AUTH_SOCK']})
connectionString
getConnectionStringUsingKey: ->
if atom.config.get('remote-edit.storePasswordsUsingKeytar') and (keytar?)
keytarPassphrase = keytar.getPassword(@getServiceNamePassphrase(), @getServiceAccount())
{host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), passphrase: keytarPassphrase}
else
{host: @hostname, port: @port, username: @username, privateKey: @getPrivateKey(@privateKeyPath), passphrase: @passphrase}
getConnectionStringUsingPassword: ->
if atom.config.get('remote-edit.storePasswordsUsingKeytar') and (keytar?)
keytarPassword = keytar.getPassword(@getServiceNamePassword(), @getServiceAccount())
{host: @hostname, port: @port, username: @username, password: PI:PASSWORD:<PASSWORD>END_PI}
else
{host: @hostname, port: @port, username: @username, password: PI:PASSWORD:<PASSWORD>END_PI}
getPrivateKey: (path) ->
if path[0] == "~"
path = Path.normalize(osenv.home() + path.substring(1, path.length))
return fs.readFileSync(path, 'ascii', (err, data) ->
throw err if err?
return data.trim()
)
createRemoteFileFromFile: (path, file) ->
remoteFile = new RemoteFile(Path.normalize("#{path}/#{file.filename}").split(Path.sep).join('/'), (file.longname[0] == '-'), (file.longname[0] == 'd'), (file.longname[0] == 'l'), filesize(file.attrs.size).human(), parseInt(file.attrs.mode, 10).toString(8).substr(2, 4), moment(file.attrs.mtime * 1000).format("HH:mm:ss DD/MM/YYYY"))
return remoteFile
getServiceNamePassword: ->
"atom.remote-edit.ssh.password"
getServiceNamePassphrase: ->
"atom.remote-edit.ssh.passphrase"
####################
# Overridden methods
getConnectionString: (connectionOptions) ->
if @useAgent
return _.extend(@getConnectionStringUsingAgent(), connectionOptions)
else if @usePrivateKey
return _.extend(@getConnectionStringUsingKey(), connectionOptions)
else if @usePassword
return _.extend(@getConnectionStringUsingPassword(), connectionOptions)
else
throw new Error("No valid connection method is set for SftpHost!")
close: (callback) ->
@connection?.end()
callback?(null)
connect: (callback, connectionOptions = {}) ->
@emitter.emit 'info', {message: "Connecting to sftp://#{@username}@#{@hostname}:#{@port}", type: 'info'}
async.waterfall([
(callback) =>
if @usePrivateKey
fs.exists(@privateKeyPath, ((exists) =>
if exists
callback(null)
else
@emitter.emit 'info', {message: "Private key does not exist!", type: 'error'}
callback(new Error("Private key does not exist"))
)
)
else
callback(null)
(callback) =>
@connection = new ssh2()
@connection.on 'error', (err) =>
@emitter.emit 'info', {message: "Error occured when connecting to sftp://#{@username}@#{@hostname}:#{@port}", type: 'error'}
@connection.end()
callback(err)
@connection.on 'ready', =>
@emitter.emit 'info', {message: "Successfully connected to sftp://#{@username}@#{@hostname}:#{@port}", type: 'success'}
callback(null)
@connection.connect(@getConnectionString(connectionOptions))
], (err) ->
callback?(err)
)
isConnected: ->
@connection? and @connection._state == 'authenticated'
getFilesMetadata: (path, callback) ->
async.waterfall([
(callback) =>
@connection.sftp(callback)
(sftp, callback) ->
sftp.readdir(path, callback)
(files, callback) =>
async.map(files, ((file, callback) => callback(null, @createRemoteFileFromFile(path, file))), callback)
(objects, callback) ->
objects.push(new RemoteFile((path + "/.."), false, true, false, null, null, null))
if atom.config.get 'remote-edit.showHiddenFiles'
callback(null, objects)
else
async.filter(objects, ((item, callback) -> item.isHidden(callback)), ((result) -> callback(null, result)))
], (err, result) =>
if err?
@emitter.emit('info', {message: "Error occured when reading remote directory sftp://#{@username}@#{@hostname}:#{@port}:#{path}", type: 'error'} )
console.error err if err?
callback?(err)
else
callback?(err, (result.sort (a, b) -> return if a.name.toLowerCase() >= b.name.toLowerCase() then 1 else -1))
)
getFile: (localFile, callback) ->
@emitter.emit('info', {message: "Getting remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'info'})
async.waterfall([
(callback) =>
@connection.sftp(callback)
(sftp, callback) =>
sftp.fastGet(localFile.remoteFile.path, localFile.path, (err) => callback(err, sftp))
], (err, sftp) =>
@emitter.emit('info', {message: "Error when reading remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'error'}) if err?
@emitter.emit('info', {message: "Successfully read remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'success'}) if !err?
callback?(err, localFile)
)
writeFile: (localFile, callback) ->
@emitter.emit 'info', {message: "Writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'info'}
async.waterfall([
(callback) =>
@connection.sftp(callback)
(sftp, callback) ->
sftp.fastPut(localFile.path, localFile.remoteFile.path, callback)
], (err) =>
if err?
@emitter.emit('info', {message: "Error occured when writing remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'error'})
console.error err if err?
else
@emitter.emit('info', {message: "Successfully wrote remote file sftp://#{@username}@#{@hostname}:#{@port}#{localFile.remoteFile.path}", type: 'success'})
@close()
callback?(err)
)
serializeParams: ->
{
@alias
@hostname
@directory
@username
@port
localFiles: localFile.serialize() for localFile in @localFiles
@useAgent
@usePrivateKey
@usePassword
@password
@passphrase
@privateKeyPath
@lastOpenDirectory
}
deserializeParams: (params) ->
tmpArray = []
tmpArray.push(LocalFile.deserialize(localFile, host: this)) for localFile in params.localFiles
params.localFiles = tmpArray
params
|
[
{
"context": "ttps://dribbble.com/shots/2656702-Joshua\n# author: Chris Johnson\n# contact:\n#\temail: me@cmj.io\n#\ttwitter: @chrismj",
"end": 67,
"score": 0.9998109936714172,
"start": 54,
"tag": "NAME",
"value": "Chris Johnson"
},
{
"context": "Joshua\n# author: Chris Johnson\n# contact:\n#\temail: me@cmj.io\n#\ttwitter: @chrismj83\n#\tweb: http://cmj.io\n\ntnw =",
"end": 97,
"score": 0.9999315738677979,
"start": 88,
"tag": "EMAIL",
"value": "me@cmj.io"
},
{
"context": "s Johnson\n# contact:\n#\temail: me@cmj.io\n#\ttwitter: @chrismj83\n#\tweb: http://cmj.io\n\ntnw = new Layer\n\twidth: 750",
"end": 119,
"score": 0.9994387626647949,
"start": 109,
"tag": "USERNAME",
"value": "@chrismj83"
}
] | app.coffee | edgeui/joshua | 2 | # https://dribbble.com/shots/2656702-Joshua
# author: Chris Johnson
# contact:
# email: me@cmj.io
# twitter: @chrismj83
# web: http://cmj.io
tnw = new Layer
width: 750
height: 1334
backgroundColor: "rgba(63,104,116,1)"
opacity: 0
rotation: -360
scale: 0.8
wopr = Framer.Importer.load("imported/wopr@2x")
wopr.Group_2.y = 1340
wopr.Group_2.scale = 0.8
wopr.Group_2.opacity = 0
wopr.Group_6.x = 800
wopr.Group_6.opacity = 0
wopr.Group_2.animate
properties:
y: 250
scale: 1
opacity: 1
curve: "spring(200,15,0)"
delay: 1
repeat: 0
time: 1
wopr.Group_Copy.onClick =>
wopr.Group_6.animate
properties:
x: 110
opacity: 1
curve: "spring(200,15,0)"
time: 1
wopr.Group_6.onAnimationEnd =>
wopr.Group_6.animate
properties:
x: -440
time: 0.3
delay: 0.5
curve: "spring(200,15,0)"
wopr.Group.onTap =>
tnw.animate
properties:
opacity: 1
scale: 1
time: 0.5
wopr.iPhone_6.animate
properties:
x: -750
scale: 0.7
time: 0.5 | 96960 | # https://dribbble.com/shots/2656702-Joshua
# author: <NAME>
# contact:
# email: <EMAIL>
# twitter: @chrismj83
# web: http://cmj.io
tnw = new Layer
width: 750
height: 1334
backgroundColor: "rgba(63,104,116,1)"
opacity: 0
rotation: -360
scale: 0.8
wopr = Framer.Importer.load("imported/wopr@2x")
wopr.Group_2.y = 1340
wopr.Group_2.scale = 0.8
wopr.Group_2.opacity = 0
wopr.Group_6.x = 800
wopr.Group_6.opacity = 0
wopr.Group_2.animate
properties:
y: 250
scale: 1
opacity: 1
curve: "spring(200,15,0)"
delay: 1
repeat: 0
time: 1
wopr.Group_Copy.onClick =>
wopr.Group_6.animate
properties:
x: 110
opacity: 1
curve: "spring(200,15,0)"
time: 1
wopr.Group_6.onAnimationEnd =>
wopr.Group_6.animate
properties:
x: -440
time: 0.3
delay: 0.5
curve: "spring(200,15,0)"
wopr.Group.onTap =>
tnw.animate
properties:
opacity: 1
scale: 1
time: 0.5
wopr.iPhone_6.animate
properties:
x: -750
scale: 0.7
time: 0.5 | true | # https://dribbble.com/shots/2656702-Joshua
# author: PI:NAME:<NAME>END_PI
# contact:
# email: PI:EMAIL:<EMAIL>END_PI
# twitter: @chrismj83
# web: http://cmj.io
tnw = new Layer
width: 750
height: 1334
backgroundColor: "rgba(63,104,116,1)"
opacity: 0
rotation: -360
scale: 0.8
wopr = Framer.Importer.load("imported/wopr@2x")
wopr.Group_2.y = 1340
wopr.Group_2.scale = 0.8
wopr.Group_2.opacity = 0
wopr.Group_6.x = 800
wopr.Group_6.opacity = 0
wopr.Group_2.animate
properties:
y: 250
scale: 1
opacity: 1
curve: "spring(200,15,0)"
delay: 1
repeat: 0
time: 1
wopr.Group_Copy.onClick =>
wopr.Group_6.animate
properties:
x: 110
opacity: 1
curve: "spring(200,15,0)"
time: 1
wopr.Group_6.onAnimationEnd =>
wopr.Group_6.animate
properties:
x: -440
time: 0.3
delay: 0.5
curve: "spring(200,15,0)"
wopr.Group.onTap =>
tnw.animate
properties:
opacity: 1
scale: 1
time: 0.5
wopr.iPhone_6.animate
properties:
x: -750
scale: 0.7
time: 0.5 |
[
{
"context": "lementation in CoffeeScript\n\n Copyright (c) 2015, Xiaoge Su\n All rights reserved.\n\n Redistribution and use ",
"end": 77,
"score": 0.9992588758468628,
"start": 68,
"tag": "NAME",
"value": "Xiaoge Su"
}
] | sprintf.coffee | xis19/coffee-sprintf | 0 | ###
sprintf implementation in CoffeeScript
Copyright (c) 2015, Xiaoge Su
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of coffee-sprintf nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
###*
* Conversion Specifier class
###
class ConversionSpecifier
###*
* Conversion specifier constructor
* @param {String} [flag]
* @param {Number} [width]
* @param {Number} [precision]
* @param {String} [length]
* @param {String} [specifier]
* @param {Boolean} [precisionDefined]
###
constructor: (flag, @width, @precision, @length, @specifier, @precisionDefined) ->
@flag = flag || ''
###*
* Check if a flag is defined
* @param {String} [flagChar]
###
hasFlag: (flagChar) ->
@flag.indexOf(flagChar) != -1
###*
* String presentation of NaN
* @type {String}
* @const
###
NAN = NaN.toString()
###*
* String presentation of Infinity
* @type {String}
* @const
###
INFINITY = Infinity.toString()
###*
* Flags for conversion specifier
* @type {String}
* @const
###
FLAGS = '-+ #0'
###*
* Conversion specifiers
* @type {String}
* @const
###
CONVERSION_SPECIFIERS = 'dioxXfFeEgGcs%'
###*
* Conversion specifiers for numerical values
* @type {String}
* @const
###
NUMERIC_CONVERSION_SPECIFIERS = 'dioxXaAeEfFgG'
###*
* Conversion specifiers for integer values
* @type {String}
* @const
###
INTEGER_CONVERSION_SPECIFIERS = 'dioxX'
###*
* Regular Expression to capture conversion specifiers
* @type {RegExp}
* @const
###
CONVERSION_SPECIFIER_REGEXP = new RegExp(
"^([#{FLAGS}]*)?(\\d+|\\*)?(\\.(\\d+|\\*)?)?(hh|h|l|ll|j|z|t|L)?([#{CONVERSION_SPECIFIERS}])")
###*
* Conversion specifiers with implied precision 1
* @type {String}
* @const
###
DEFAULT_PRECISION_1_SPECIFIERS = 'dioxX'
###*
* Conversion specifiers with implied precision 6
* @type {String}
* @const
###
DEFAULT_PRECISION_6_SPECIFIERS = 'fFeEgG'
###*
* Conversion specifiers with implied precision null
* @type {String}
* @const
###
DEFAULT_PRECISION_NULL_SPECIFIERS = 'cs%'
###*
* Conversion specifier for exponential term
* @type {ConversionSpecifier}
* @const
###
EXPONENTIAL_TERM_CONVERSION_SPECIFIER = new ConversionSpecifier('+', 0, 2, 'd', true)
###*
* Get the default precision value for a given conversion specifier
* @param {String} [specifier] conversion specifier
* @return {Number, null}
###
getDefaultPrecision = (specifier) ->
if specifier in DEFAULT_PRECISION_1_SPECIFIERS
1
else if specifier in DEFAULT_PRECISION_6_SPECIFIERS
6
else if specifier in DEFAULT_PRECISION_NULL_SPECIFIERS
null
else
throw new Error("Unexpected specifier #{specifier}")
###*
* Get the padding character for a given conversionSpec
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
getPaddingCharacter = (conversionSpec) ->
if !conversionSpec.hasFlag('0') || conversionSpec.hasFlag('-')
' '
else if conversionSpec.precisionDefined && conversionSpec.specifier in INTEGER_CONVERSION_SPECIFIERS
' '
else
'0'
###*
* Convert a float number to string, to a fixed number of decimals
* @param {Number} [value]
* @param {Number} [precision]
* @return {String}
###
toFixedRound = (value, precision) ->
(+(Math.round(+(value + 'e' + precision)) + 'e' + -precision)).toFixed(precision);
###*
* Convert a float number to a float value in (-10, 10) and exponential term
* @param {Number} [value]
* @param {ConversionSpecifier} [conversionSpec]
* @return {Array}
###
toExponential = (value) ->
expTerm = 0
# XXX This is a naive implementation. Need to check for other implementations for better performance.
while Math.abs(value) > 10
++expTerm
value /= 10
while 0 < Math.abs(value) < 1
--expTerm
value *= 10
[value, expTerm]
###*
* Convert a float nmber to a float value in (-16, 16) and exponetial term
* @param {Number} [value]
* @param {ConversionSpecifier} [conversionSpec]
* @return {Array}
###
toHexExponential = (value) ->
expTerm = 0
# XXX This is a naive implementation. Need to check for other implementations for better performance.
while Math.abs(value) > 16
++expTerm
value /= 16
while 0 < Math.abs(value) < 1
++expTerm
value *= 16
[value, expTerm]
###*
* Get the prefix sign character base on the value
* @param {Number} [value]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
getSignPrefix = (value, conversionSpec) ->
if value < 0
'-'
else
if conversionSpec.hasFlag('+')
'+'
else if conversionSpec.hasFlag(' ')
' '
else
''
###*
* For a string, adjust the width by padding using paddingCharacter, also add the sign
* @param {String} [string]
* @param {Object} [conversionSpec]
* @param {String} [sign]
* @param {String, null} [overridePaddingCharacter]
* @return {String}
###
adjustSignWidth = (string, conversionSpec, sign = '', overridePaddingCharacter = null) ->
if !(conversionSpec.width && conversionSpec.width > string.length)
string = sign + string
else
paddingCharacter = overridePaddingCharacter || getPaddingCharacter(conversionSpec)
spaces = Array(conversionSpec.width - string.length - sign.length + 1).join(paddingCharacter)
if conversionSpec.hasFlag('-')
string = sign + string + spaces
else if paddingCharacter == '0'
string = sign + spaces + string
else
string = spaces + sign + string
string
###*
* Format a NaN based on conversionSpec
* @param {ConversionSpecifier} [conversionSpec]
###
formatNaN = (conversionSpec) ->
adjustSignWidth(NAN, conversionSpec, '', ' ')
###*
* Format an Infinity based on conversionSpec
* @param {Number} [infValue]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatInfinity = (infValue, conversionSpec) ->
adjustSignWidth(INFINITY, conversionSpec, getSignPrefix(infValue, conversionSpec), ' ')
###*
* Translate one character to string
* @param {String, Number} [value] Either a character, or an integer which will be converted to a character
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatChar = (value, conversionSpec) ->
value_type = typeof(value)
if value_type == 'number'
if value % 1 != 0
throw new Error("%c cannot consume an float value #{value}")
value = String.fromCharCode(value)
else if value_type == 'string'
if value.length != 1
throw new Error("Expecting one character, got a string #{value} with length #{value.length}")
else
throw new Error("Expecting one character or a number that can be converted to character, got #{value_type}")
adjustSignWidth(value, conversionSpec)
###*
* Translate a number into string
* @param {Number} [value]
* @param {ConversionSpecifier} [conversionSpec]
* @param {Function} [formatRepresentableValueFunc]
* @return {String}
###
formatNumber = (value, conversionSpec, formatRepresentableValueFunc) ->
if isNaN(value)
formatNaN(conversionSpec)
else if !isFinite(value)
formatInfinity(value, conversionSpec)
else
formatRepresentableValueFunc(value, conversionSpec)
###*
* Format an integer
* @param {Number} [intValue]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatInteger = (intValue, conversionSpec) ->
result = ''
# Special case, when value is 0 && precision is 0, there is no digit
if !(intValue == 0 && conversionSpec.precision == 0)
result = Math.abs(intValue).toString()
if result.length < conversionSpec.precision
result = Array(conversionSpec.precision - result.length + 1).join('0') + result
adjustSignWidth(result, conversionSpec, getSignPrefix(intValue, conversionSpec))
###*
* Format an oct
* @param {Number} [intValue]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatOct = (intValue, conversionSpec) ->
throw new Error("Expecting a positive integer, got #{intValue}") unless intValue >= 0
result = ''
# Special case, when value is 0 && precision is 0, there is no digit
if !(intValue == 0 && conversionSpec.precision == 0)
result = Math.abs(intValue).toString(8)
if result.length < conversionSpec.precision
result = Array(conversionSpec.precision - result.length + 1).join('0') + result
if conversionSpec.hasFlag('#') && result[0] != '0'
result = '0' + result
adjustSignWidth(result, conversionSpec, '')
###*
* Format a hex
* @param {Number} [intValue]
* @param {ConversionSpecifier} [conversionSpec]
* @param {Boolean} [upperCase]
* @return {String}
###
formatHex = (intValue, conversionSpec, upperCase) ->
throw new Error("Expecting a positive integer, got #{intValue}") unless intValue >= 0
result = ''
# Special case, when value is 0 && precision is 0, there is no digit
if !(intValue == 0 && conversionSpec.precision == 0)
result = Math.abs(intValue).toString(16)
if upperCase
result = result.toUpperCase()
if result.length < conversionSpec.precision
result = Array(conversionSpec.precision - result.length + 1).join('0') + result
prefix = ''
if conversionSpec.hasFlag('#') && intValue != 0
prefix = '0x'
adjustSignWidth(result, conversionSpec, prefix)
###*
* Format a float number
* @param {Number} [floatValue]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatFloat = (floatValue, conversionSpec) ->
result = ''
if conversionSpec.precision == 0
result = Math.abs(toFixedRound(floatValue, 0)).toString()
if conversionSpec.hasFlag('#')
result += '.'
else
result = toFixedRound(Math.abs(floatValue), conversionSpec.precision)
adjustSignWidth(result, conversionSpec, getSignPrefix(floatValue, conversionSpec))
###*
* Format a float to string, using scientific notation
* @param {Number} [floatValue]
* @param {ConversionSpecifier} [conversionSpec]
* @param {Boolean} {upperCase}
* @return {String}
###
formatExponential = (floatValue, conversionSpec, upperCase) ->
[val, expTerm] = toExponential(floatValue)
floatFlag = ''
if conversionSpec.hasFlag('#')
floatFlag = '#'
floatConversionSpecifier = new ConversionSpecifier(
floatFlag, 0, conversionSpec.precision, 'f', true)
valueStr = formatFloat(Math.abs(val), floatConversionSpecifier)
expTermStr = formatInteger(expTerm, EXPONENTIAL_TERM_CONVERSION_SPECIFIER)
eChar = 'e'
if upperCase
eChar = 'E'
adjustSignWidth(valueStr + eChar + expTermStr, conversionSpec, getSignPrefix(floatValue, conversionSpec))
###*
* Format a float to string, depending on the value converted and the precision
*
###
###*
* Format a string
* @param {Object} [value]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatString = (value, conversionSpec) ->
result = String(value)
if conversionSpec.precision && result.length > conversionSpec.precision
result = result[0...conversionSpec.precision]
adjustSignWidth(result, conversionSpec)
###*
* Mapping function from conversion specifier
* @type {Hash}
* @const
###
CONVERSION_SPECIFIER_FUNCTIONS = {
c: (value, conversionSpec) -> formatChar(value, conversionSpec),
d: (value, conversionSpec) -> formatNumber(value, conversionSpec, formatInteger),
i: (value, conversionSpec) -> formatNumber(value, conversionSpec, formatInteger),
o: (value, conversionSpec) -> formatNumber(value, conversionSpec, formatOct),
x: (value, conversionSpec) -> formatNumber(
value, conversionSpec,
(_value, _conversionSpec) -> formatHex(_value, _conversionSpec, false)),
X: (value, conversionSpec) -> formatNumber(
value, conversionSpec,
(_value, _conversionSpec) -> formatHex(_value, _conversionSpec, true)),
f: (value, conversionSpec) -> formatNumber(value, conversionSpec,
(_value, _conversionSpec) -> formatFloat(_value, _conversionSpec)),
F: (value, conversionSpec) -> formatNumber(value, conversionSpec,
(_value, _conversionSpec) -> formatFloat(_value, _conversionSpec)),
e: (value, conversionSpec) -> formatExponential(value, conversionSpec),
E: (value, conversionSpec) -> formatExponential(value, conversionSpec),
s: (value, conversionSpec) -> formatString(value, conversionSpec)
}
###*
* sprintf function
* @param {String} [formatString]
* @param {Arguments} [args]
* @return {String}
###
(exports ? this).sprintf = (formatString, args...) ->
formatStringLength = formatString.length
formatStringIterator = 0
argsLength = args.length
argsIterator = 0
resultString = ''
###*
* Get the current character at formatStringIterator
* @return {String}
###
consumeFormatStringChar = ->
if formatStringIterator >= formatStringLength
null
else
formatString[formatStringIterator++]
###*
* Get the current args
* @return {Object}
###
consumeArgument = ->
if argsIterator >= argsLength
throw new Error("Got #{argsLength} args, expecting more.")
else
args[argsIterator++]
###*
* Interpret a matched conversion specifier
* @param {Hash} [match]
* @return {ConversionSpecifier}
###
interpretConversionSpecifiersMatches = (match) ->
width = parseInt(match[2]) or null
if width == '*'
width = parseInt(consumeArgument())
throw new Error("Expecting an integer for width, got #{width}") unless width
precision = getDefaultPrecision(match[6])
if match[3]
if !match[4]
precision = 0
else if match[4] == '*'
precision = parseInt(consumeArgument())
throw new Error("Expecting a positive integer for precision, got #{precision}") unless precision >= 0
else
precision = parseInt(match[4])
new ConversionSpecifier(match[1], width, precision, match[5], match[6], !!match[3])
###*
* Read a conversion specifier from format string
* @return {Hash}
###
readConversionSpecifier = ->
match = CONVERSION_SPECIFIER_REGEXP.exec(formatString[formatStringIterator..])
if match
formatStringIterator += match[0].length
match
else
throw new Error("Unable to parse a format specifier, starting at index #{formatStringIterator}. " +
"The remaining string is '#{formatString}'")
###*
* Apply conversion specifier to argument
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
applyConversionSpecifier = (conversionSpec) ->
specifier = conversionSpec.specifier
if specifier == '%'
'%'
else
if !CONVERSION_SPECIFIER_FUNCTIONS.hasOwnProperty(specifier)
throw new Error("Unsupported specifier #{specifier}")
else
CONVERSION_SPECIFIER_FUNCTIONS[specifier](consumeArgument(), conversionSpec)
char = consumeFormatStringChar()
while(char)
if char == '%'
resultString += applyConversionSpecifier(interpretConversionSpecifiersMatches(readConversionSpecifier()))
else
resultString += char
char = consumeFormatStringChar()
resultString | 29056 | ###
sprintf implementation in CoffeeScript
Copyright (c) 2015, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of coffee-sprintf nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
###*
* Conversion Specifier class
###
class ConversionSpecifier
###*
* Conversion specifier constructor
* @param {String} [flag]
* @param {Number} [width]
* @param {Number} [precision]
* @param {String} [length]
* @param {String} [specifier]
* @param {Boolean} [precisionDefined]
###
constructor: (flag, @width, @precision, @length, @specifier, @precisionDefined) ->
@flag = flag || ''
###*
* Check if a flag is defined
* @param {String} [flagChar]
###
hasFlag: (flagChar) ->
@flag.indexOf(flagChar) != -1
###*
* String presentation of NaN
* @type {String}
* @const
###
NAN = NaN.toString()
###*
* String presentation of Infinity
* @type {String}
* @const
###
INFINITY = Infinity.toString()
###*
* Flags for conversion specifier
* @type {String}
* @const
###
FLAGS = '-+ #0'
###*
* Conversion specifiers
* @type {String}
* @const
###
CONVERSION_SPECIFIERS = 'dioxXfFeEgGcs%'
###*
* Conversion specifiers for numerical values
* @type {String}
* @const
###
NUMERIC_CONVERSION_SPECIFIERS = 'dioxXaAeEfFgG'
###*
* Conversion specifiers for integer values
* @type {String}
* @const
###
INTEGER_CONVERSION_SPECIFIERS = 'dioxX'
###*
* Regular Expression to capture conversion specifiers
* @type {RegExp}
* @const
###
CONVERSION_SPECIFIER_REGEXP = new RegExp(
"^([#{FLAGS}]*)?(\\d+|\\*)?(\\.(\\d+|\\*)?)?(hh|h|l|ll|j|z|t|L)?([#{CONVERSION_SPECIFIERS}])")
###*
* Conversion specifiers with implied precision 1
* @type {String}
* @const
###
DEFAULT_PRECISION_1_SPECIFIERS = 'dioxX'
###*
* Conversion specifiers with implied precision 6
* @type {String}
* @const
###
DEFAULT_PRECISION_6_SPECIFIERS = 'fFeEgG'
###*
* Conversion specifiers with implied precision null
* @type {String}
* @const
###
DEFAULT_PRECISION_NULL_SPECIFIERS = 'cs%'
###*
* Conversion specifier for exponential term
* @type {ConversionSpecifier}
* @const
###
EXPONENTIAL_TERM_CONVERSION_SPECIFIER = new ConversionSpecifier('+', 0, 2, 'd', true)
###*
* Get the default precision value for a given conversion specifier
* @param {String} [specifier] conversion specifier
* @return {Number, null}
###
getDefaultPrecision = (specifier) ->
if specifier in DEFAULT_PRECISION_1_SPECIFIERS
1
else if specifier in DEFAULT_PRECISION_6_SPECIFIERS
6
else if specifier in DEFAULT_PRECISION_NULL_SPECIFIERS
null
else
throw new Error("Unexpected specifier #{specifier}")
###*
* Get the padding character for a given conversionSpec
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
getPaddingCharacter = (conversionSpec) ->
if !conversionSpec.hasFlag('0') || conversionSpec.hasFlag('-')
' '
else if conversionSpec.precisionDefined && conversionSpec.specifier in INTEGER_CONVERSION_SPECIFIERS
' '
else
'0'
###*
* Convert a float number to string, to a fixed number of decimals
* @param {Number} [value]
* @param {Number} [precision]
* @return {String}
###
toFixedRound = (value, precision) ->
(+(Math.round(+(value + 'e' + precision)) + 'e' + -precision)).toFixed(precision);
###*
* Convert a float number to a float value in (-10, 10) and exponential term
* @param {Number} [value]
* @param {ConversionSpecifier} [conversionSpec]
* @return {Array}
###
toExponential = (value) ->
expTerm = 0
# XXX This is a naive implementation. Need to check for other implementations for better performance.
while Math.abs(value) > 10
++expTerm
value /= 10
while 0 < Math.abs(value) < 1
--expTerm
value *= 10
[value, expTerm]
###*
* Convert a float nmber to a float value in (-16, 16) and exponetial term
* @param {Number} [value]
* @param {ConversionSpecifier} [conversionSpec]
* @return {Array}
###
toHexExponential = (value) ->
expTerm = 0
# XXX This is a naive implementation. Need to check for other implementations for better performance.
while Math.abs(value) > 16
++expTerm
value /= 16
while 0 < Math.abs(value) < 1
++expTerm
value *= 16
[value, expTerm]
###*
* Get the prefix sign character base on the value
* @param {Number} [value]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
getSignPrefix = (value, conversionSpec) ->
if value < 0
'-'
else
if conversionSpec.hasFlag('+')
'+'
else if conversionSpec.hasFlag(' ')
' '
else
''
###*
* For a string, adjust the width by padding using paddingCharacter, also add the sign
* @param {String} [string]
* @param {Object} [conversionSpec]
* @param {String} [sign]
* @param {String, null} [overridePaddingCharacter]
* @return {String}
###
adjustSignWidth = (string, conversionSpec, sign = '', overridePaddingCharacter = null) ->
if !(conversionSpec.width && conversionSpec.width > string.length)
string = sign + string
else
paddingCharacter = overridePaddingCharacter || getPaddingCharacter(conversionSpec)
spaces = Array(conversionSpec.width - string.length - sign.length + 1).join(paddingCharacter)
if conversionSpec.hasFlag('-')
string = sign + string + spaces
else if paddingCharacter == '0'
string = sign + spaces + string
else
string = spaces + sign + string
string
###*
* Format a NaN based on conversionSpec
* @param {ConversionSpecifier} [conversionSpec]
###
formatNaN = (conversionSpec) ->
adjustSignWidth(NAN, conversionSpec, '', ' ')
###*
* Format an Infinity based on conversionSpec
* @param {Number} [infValue]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatInfinity = (infValue, conversionSpec) ->
adjustSignWidth(INFINITY, conversionSpec, getSignPrefix(infValue, conversionSpec), ' ')
###*
* Translate one character to string
* @param {String, Number} [value] Either a character, or an integer which will be converted to a character
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatChar = (value, conversionSpec) ->
value_type = typeof(value)
if value_type == 'number'
if value % 1 != 0
throw new Error("%c cannot consume an float value #{value}")
value = String.fromCharCode(value)
else if value_type == 'string'
if value.length != 1
throw new Error("Expecting one character, got a string #{value} with length #{value.length}")
else
throw new Error("Expecting one character or a number that can be converted to character, got #{value_type}")
adjustSignWidth(value, conversionSpec)
###*
* Translate a number into string
* @param {Number} [value]
* @param {ConversionSpecifier} [conversionSpec]
* @param {Function} [formatRepresentableValueFunc]
* @return {String}
###
formatNumber = (value, conversionSpec, formatRepresentableValueFunc) ->
if isNaN(value)
formatNaN(conversionSpec)
else if !isFinite(value)
formatInfinity(value, conversionSpec)
else
formatRepresentableValueFunc(value, conversionSpec)
###*
* Format an integer
* @param {Number} [intValue]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatInteger = (intValue, conversionSpec) ->
result = ''
# Special case, when value is 0 && precision is 0, there is no digit
if !(intValue == 0 && conversionSpec.precision == 0)
result = Math.abs(intValue).toString()
if result.length < conversionSpec.precision
result = Array(conversionSpec.precision - result.length + 1).join('0') + result
adjustSignWidth(result, conversionSpec, getSignPrefix(intValue, conversionSpec))
###*
* Format an oct
* @param {Number} [intValue]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatOct = (intValue, conversionSpec) ->
throw new Error("Expecting a positive integer, got #{intValue}") unless intValue >= 0
result = ''
# Special case, when value is 0 && precision is 0, there is no digit
if !(intValue == 0 && conversionSpec.precision == 0)
result = Math.abs(intValue).toString(8)
if result.length < conversionSpec.precision
result = Array(conversionSpec.precision - result.length + 1).join('0') + result
if conversionSpec.hasFlag('#') && result[0] != '0'
result = '0' + result
adjustSignWidth(result, conversionSpec, '')
###*
* Format a hex
* @param {Number} [intValue]
* @param {ConversionSpecifier} [conversionSpec]
* @param {Boolean} [upperCase]
* @return {String}
###
formatHex = (intValue, conversionSpec, upperCase) ->
throw new Error("Expecting a positive integer, got #{intValue}") unless intValue >= 0
result = ''
# Special case, when value is 0 && precision is 0, there is no digit
if !(intValue == 0 && conversionSpec.precision == 0)
result = Math.abs(intValue).toString(16)
if upperCase
result = result.toUpperCase()
if result.length < conversionSpec.precision
result = Array(conversionSpec.precision - result.length + 1).join('0') + result
prefix = ''
if conversionSpec.hasFlag('#') && intValue != 0
prefix = '0x'
adjustSignWidth(result, conversionSpec, prefix)
###*
* Format a float number
* @param {Number} [floatValue]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatFloat = (floatValue, conversionSpec) ->
result = ''
if conversionSpec.precision == 0
result = Math.abs(toFixedRound(floatValue, 0)).toString()
if conversionSpec.hasFlag('#')
result += '.'
else
result = toFixedRound(Math.abs(floatValue), conversionSpec.precision)
adjustSignWidth(result, conversionSpec, getSignPrefix(floatValue, conversionSpec))
###*
* Format a float to string, using scientific notation
* @param {Number} [floatValue]
* @param {ConversionSpecifier} [conversionSpec]
* @param {Boolean} {upperCase}
* @return {String}
###
formatExponential = (floatValue, conversionSpec, upperCase) ->
[val, expTerm] = toExponential(floatValue)
floatFlag = ''
if conversionSpec.hasFlag('#')
floatFlag = '#'
floatConversionSpecifier = new ConversionSpecifier(
floatFlag, 0, conversionSpec.precision, 'f', true)
valueStr = formatFloat(Math.abs(val), floatConversionSpecifier)
expTermStr = formatInteger(expTerm, EXPONENTIAL_TERM_CONVERSION_SPECIFIER)
eChar = 'e'
if upperCase
eChar = 'E'
adjustSignWidth(valueStr + eChar + expTermStr, conversionSpec, getSignPrefix(floatValue, conversionSpec))
###*
* Format a float to string, depending on the value converted and the precision
*
###
###*
* Format a string
* @param {Object} [value]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatString = (value, conversionSpec) ->
result = String(value)
if conversionSpec.precision && result.length > conversionSpec.precision
result = result[0...conversionSpec.precision]
adjustSignWidth(result, conversionSpec)
###*
* Mapping function from conversion specifier
* @type {Hash}
* @const
###
CONVERSION_SPECIFIER_FUNCTIONS = {
c: (value, conversionSpec) -> formatChar(value, conversionSpec),
d: (value, conversionSpec) -> formatNumber(value, conversionSpec, formatInteger),
i: (value, conversionSpec) -> formatNumber(value, conversionSpec, formatInteger),
o: (value, conversionSpec) -> formatNumber(value, conversionSpec, formatOct),
x: (value, conversionSpec) -> formatNumber(
value, conversionSpec,
(_value, _conversionSpec) -> formatHex(_value, _conversionSpec, false)),
X: (value, conversionSpec) -> formatNumber(
value, conversionSpec,
(_value, _conversionSpec) -> formatHex(_value, _conversionSpec, true)),
f: (value, conversionSpec) -> formatNumber(value, conversionSpec,
(_value, _conversionSpec) -> formatFloat(_value, _conversionSpec)),
F: (value, conversionSpec) -> formatNumber(value, conversionSpec,
(_value, _conversionSpec) -> formatFloat(_value, _conversionSpec)),
e: (value, conversionSpec) -> formatExponential(value, conversionSpec),
E: (value, conversionSpec) -> formatExponential(value, conversionSpec),
s: (value, conversionSpec) -> formatString(value, conversionSpec)
}
###*
* sprintf function
* @param {String} [formatString]
* @param {Arguments} [args]
* @return {String}
###
(exports ? this).sprintf = (formatString, args...) ->
formatStringLength = formatString.length
formatStringIterator = 0
argsLength = args.length
argsIterator = 0
resultString = ''
###*
* Get the current character at formatStringIterator
* @return {String}
###
consumeFormatStringChar = ->
if formatStringIterator >= formatStringLength
null
else
formatString[formatStringIterator++]
###*
* Get the current args
* @return {Object}
###
consumeArgument = ->
if argsIterator >= argsLength
throw new Error("Got #{argsLength} args, expecting more.")
else
args[argsIterator++]
###*
* Interpret a matched conversion specifier
* @param {Hash} [match]
* @return {ConversionSpecifier}
###
interpretConversionSpecifiersMatches = (match) ->
width = parseInt(match[2]) or null
if width == '*'
width = parseInt(consumeArgument())
throw new Error("Expecting an integer for width, got #{width}") unless width
precision = getDefaultPrecision(match[6])
if match[3]
if !match[4]
precision = 0
else if match[4] == '*'
precision = parseInt(consumeArgument())
throw new Error("Expecting a positive integer for precision, got #{precision}") unless precision >= 0
else
precision = parseInt(match[4])
new ConversionSpecifier(match[1], width, precision, match[5], match[6], !!match[3])
###*
* Read a conversion specifier from format string
* @return {Hash}
###
readConversionSpecifier = ->
match = CONVERSION_SPECIFIER_REGEXP.exec(formatString[formatStringIterator..])
if match
formatStringIterator += match[0].length
match
else
throw new Error("Unable to parse a format specifier, starting at index #{formatStringIterator}. " +
"The remaining string is '#{formatString}'")
###*
* Apply conversion specifier to argument
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
applyConversionSpecifier = (conversionSpec) ->
specifier = conversionSpec.specifier
if specifier == '%'
'%'
else
if !CONVERSION_SPECIFIER_FUNCTIONS.hasOwnProperty(specifier)
throw new Error("Unsupported specifier #{specifier}")
else
CONVERSION_SPECIFIER_FUNCTIONS[specifier](consumeArgument(), conversionSpec)
char = consumeFormatStringChar()
while(char)
if char == '%'
resultString += applyConversionSpecifier(interpretConversionSpecifiersMatches(readConversionSpecifier()))
else
resultString += char
char = consumeFormatStringChar()
resultString | true | ###
sprintf implementation in CoffeeScript
Copyright (c) 2015, PI:NAME:<NAME>END_PI
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of coffee-sprintf nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
###*
* Conversion Specifier class
###
class ConversionSpecifier
###*
* Conversion specifier constructor
* @param {String} [flag]
* @param {Number} [width]
* @param {Number} [precision]
* @param {String} [length]
* @param {String} [specifier]
* @param {Boolean} [precisionDefined]
###
constructor: (flag, @width, @precision, @length, @specifier, @precisionDefined) ->
@flag = flag || ''
###*
* Check if a flag is defined
* @param {String} [flagChar]
###
hasFlag: (flagChar) ->
@flag.indexOf(flagChar) != -1
###*
* String presentation of NaN
* @type {String}
* @const
###
NAN = NaN.toString()
###*
* String presentation of Infinity
* @type {String}
* @const
###
INFINITY = Infinity.toString()
###*
* Flags for conversion specifier
* @type {String}
* @const
###
FLAGS = '-+ #0'
###*
* Conversion specifiers
* @type {String}
* @const
###
CONVERSION_SPECIFIERS = 'dioxXfFeEgGcs%'
###*
* Conversion specifiers for numerical values
* @type {String}
* @const
###
NUMERIC_CONVERSION_SPECIFIERS = 'dioxXaAeEfFgG'
###*
* Conversion specifiers for integer values
* @type {String}
* @const
###
INTEGER_CONVERSION_SPECIFIERS = 'dioxX'
###*
* Regular Expression to capture conversion specifiers
* @type {RegExp}
* @const
###
CONVERSION_SPECIFIER_REGEXP = new RegExp(
"^([#{FLAGS}]*)?(\\d+|\\*)?(\\.(\\d+|\\*)?)?(hh|h|l|ll|j|z|t|L)?([#{CONVERSION_SPECIFIERS}])")
###*
* Conversion specifiers with implied precision 1
* @type {String}
* @const
###
DEFAULT_PRECISION_1_SPECIFIERS = 'dioxX'
###*
* Conversion specifiers with implied precision 6
* @type {String}
* @const
###
DEFAULT_PRECISION_6_SPECIFIERS = 'fFeEgG'
###*
* Conversion specifiers with implied precision null
* @type {String}
* @const
###
DEFAULT_PRECISION_NULL_SPECIFIERS = 'cs%'
###*
* Conversion specifier for exponential term
* @type {ConversionSpecifier}
* @const
###
EXPONENTIAL_TERM_CONVERSION_SPECIFIER = new ConversionSpecifier('+', 0, 2, 'd', true)
###*
* Get the default precision value for a given conversion specifier
* @param {String} [specifier] conversion specifier
* @return {Number, null}
###
getDefaultPrecision = (specifier) ->
if specifier in DEFAULT_PRECISION_1_SPECIFIERS
1
else if specifier in DEFAULT_PRECISION_6_SPECIFIERS
6
else if specifier in DEFAULT_PRECISION_NULL_SPECIFIERS
null
else
throw new Error("Unexpected specifier #{specifier}")
###*
* Get the padding character for a given conversionSpec
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
getPaddingCharacter = (conversionSpec) ->
if !conversionSpec.hasFlag('0') || conversionSpec.hasFlag('-')
' '
else if conversionSpec.precisionDefined && conversionSpec.specifier in INTEGER_CONVERSION_SPECIFIERS
' '
else
'0'
###*
* Convert a float number to string, to a fixed number of decimals
* @param {Number} [value]
* @param {Number} [precision]
* @return {String}
###
toFixedRound = (value, precision) ->
(+(Math.round(+(value + 'e' + precision)) + 'e' + -precision)).toFixed(precision);
###*
* Convert a float number to a float value in (-10, 10) and exponential term
* @param {Number} [value]
* @param {ConversionSpecifier} [conversionSpec]
* @return {Array}
###
toExponential = (value) ->
expTerm = 0
# XXX This is a naive implementation. Need to check for other implementations for better performance.
while Math.abs(value) > 10
++expTerm
value /= 10
while 0 < Math.abs(value) < 1
--expTerm
value *= 10
[value, expTerm]
###*
* Convert a float nmber to a float value in (-16, 16) and exponetial term
* @param {Number} [value]
* @param {ConversionSpecifier} [conversionSpec]
* @return {Array}
###
toHexExponential = (value) ->
expTerm = 0
# XXX This is a naive implementation. Need to check for other implementations for better performance.
while Math.abs(value) > 16
++expTerm
value /= 16
while 0 < Math.abs(value) < 1
++expTerm
value *= 16
[value, expTerm]
###*
* Get the prefix sign character base on the value
* @param {Number} [value]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
getSignPrefix = (value, conversionSpec) ->
if value < 0
'-'
else
if conversionSpec.hasFlag('+')
'+'
else if conversionSpec.hasFlag(' ')
' '
else
''
###*
* For a string, adjust the width by padding using paddingCharacter, also add the sign
* @param {String} [string]
* @param {Object} [conversionSpec]
* @param {String} [sign]
* @param {String, null} [overridePaddingCharacter]
* @return {String}
###
adjustSignWidth = (string, conversionSpec, sign = '', overridePaddingCharacter = null) ->
if !(conversionSpec.width && conversionSpec.width > string.length)
string = sign + string
else
paddingCharacter = overridePaddingCharacter || getPaddingCharacter(conversionSpec)
spaces = Array(conversionSpec.width - string.length - sign.length + 1).join(paddingCharacter)
if conversionSpec.hasFlag('-')
string = sign + string + spaces
else if paddingCharacter == '0'
string = sign + spaces + string
else
string = spaces + sign + string
string
###*
* Format a NaN based on conversionSpec
* @param {ConversionSpecifier} [conversionSpec]
###
formatNaN = (conversionSpec) ->
adjustSignWidth(NAN, conversionSpec, '', ' ')
###*
* Format an Infinity based on conversionSpec
* @param {Number} [infValue]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatInfinity = (infValue, conversionSpec) ->
adjustSignWidth(INFINITY, conversionSpec, getSignPrefix(infValue, conversionSpec), ' ')
###*
* Translate one character to string
* @param {String, Number} [value] Either a character, or an integer which will be converted to a character
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatChar = (value, conversionSpec) ->
value_type = typeof(value)
if value_type == 'number'
if value % 1 != 0
throw new Error("%c cannot consume an float value #{value}")
value = String.fromCharCode(value)
else if value_type == 'string'
if value.length != 1
throw new Error("Expecting one character, got a string #{value} with length #{value.length}")
else
throw new Error("Expecting one character or a number that can be converted to character, got #{value_type}")
adjustSignWidth(value, conversionSpec)
###*
* Translate a number into string
* @param {Number} [value]
* @param {ConversionSpecifier} [conversionSpec]
* @param {Function} [formatRepresentableValueFunc]
* @return {String}
###
formatNumber = (value, conversionSpec, formatRepresentableValueFunc) ->
if isNaN(value)
formatNaN(conversionSpec)
else if !isFinite(value)
formatInfinity(value, conversionSpec)
else
formatRepresentableValueFunc(value, conversionSpec)
###*
* Format an integer
* @param {Number} [intValue]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatInteger = (intValue, conversionSpec) ->
result = ''
# Special case, when value is 0 && precision is 0, there is no digit
if !(intValue == 0 && conversionSpec.precision == 0)
result = Math.abs(intValue).toString()
if result.length < conversionSpec.precision
result = Array(conversionSpec.precision - result.length + 1).join('0') + result
adjustSignWidth(result, conversionSpec, getSignPrefix(intValue, conversionSpec))
###*
* Format an oct
* @param {Number} [intValue]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatOct = (intValue, conversionSpec) ->
throw new Error("Expecting a positive integer, got #{intValue}") unless intValue >= 0
result = ''
# Special case, when value is 0 && precision is 0, there is no digit
if !(intValue == 0 && conversionSpec.precision == 0)
result = Math.abs(intValue).toString(8)
if result.length < conversionSpec.precision
result = Array(conversionSpec.precision - result.length + 1).join('0') + result
if conversionSpec.hasFlag('#') && result[0] != '0'
result = '0' + result
adjustSignWidth(result, conversionSpec, '')
###*
* Format a hex
* @param {Number} [intValue]
* @param {ConversionSpecifier} [conversionSpec]
* @param {Boolean} [upperCase]
* @return {String}
###
formatHex = (intValue, conversionSpec, upperCase) ->
throw new Error("Expecting a positive integer, got #{intValue}") unless intValue >= 0
result = ''
# Special case, when value is 0 && precision is 0, there is no digit
if !(intValue == 0 && conversionSpec.precision == 0)
result = Math.abs(intValue).toString(16)
if upperCase
result = result.toUpperCase()
if result.length < conversionSpec.precision
result = Array(conversionSpec.precision - result.length + 1).join('0') + result
prefix = ''
if conversionSpec.hasFlag('#') && intValue != 0
prefix = '0x'
adjustSignWidth(result, conversionSpec, prefix)
###*
* Format a float number
* @param {Number} [floatValue]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatFloat = (floatValue, conversionSpec) ->
result = ''
if conversionSpec.precision == 0
result = Math.abs(toFixedRound(floatValue, 0)).toString()
if conversionSpec.hasFlag('#')
result += '.'
else
result = toFixedRound(Math.abs(floatValue), conversionSpec.precision)
adjustSignWidth(result, conversionSpec, getSignPrefix(floatValue, conversionSpec))
###*
* Format a float to string, using scientific notation
* @param {Number} [floatValue]
* @param {ConversionSpecifier} [conversionSpec]
* @param {Boolean} {upperCase}
* @return {String}
###
formatExponential = (floatValue, conversionSpec, upperCase) ->
[val, expTerm] = toExponential(floatValue)
floatFlag = ''
if conversionSpec.hasFlag('#')
floatFlag = '#'
floatConversionSpecifier = new ConversionSpecifier(
floatFlag, 0, conversionSpec.precision, 'f', true)
valueStr = formatFloat(Math.abs(val), floatConversionSpecifier)
expTermStr = formatInteger(expTerm, EXPONENTIAL_TERM_CONVERSION_SPECIFIER)
eChar = 'e'
if upperCase
eChar = 'E'
adjustSignWidth(valueStr + eChar + expTermStr, conversionSpec, getSignPrefix(floatValue, conversionSpec))
###*
* Format a float to string, depending on the value converted and the precision
*
###
###*
* Format a string
* @param {Object} [value]
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
formatString = (value, conversionSpec) ->
result = String(value)
if conversionSpec.precision && result.length > conversionSpec.precision
result = result[0...conversionSpec.precision]
adjustSignWidth(result, conversionSpec)
###*
* Mapping function from conversion specifier
* @type {Hash}
* @const
###
CONVERSION_SPECIFIER_FUNCTIONS = {
c: (value, conversionSpec) -> formatChar(value, conversionSpec),
d: (value, conversionSpec) -> formatNumber(value, conversionSpec, formatInteger),
i: (value, conversionSpec) -> formatNumber(value, conversionSpec, formatInteger),
o: (value, conversionSpec) -> formatNumber(value, conversionSpec, formatOct),
x: (value, conversionSpec) -> formatNumber(
value, conversionSpec,
(_value, _conversionSpec) -> formatHex(_value, _conversionSpec, false)),
X: (value, conversionSpec) -> formatNumber(
value, conversionSpec,
(_value, _conversionSpec) -> formatHex(_value, _conversionSpec, true)),
f: (value, conversionSpec) -> formatNumber(value, conversionSpec,
(_value, _conversionSpec) -> formatFloat(_value, _conversionSpec)),
F: (value, conversionSpec) -> formatNumber(value, conversionSpec,
(_value, _conversionSpec) -> formatFloat(_value, _conversionSpec)),
e: (value, conversionSpec) -> formatExponential(value, conversionSpec),
E: (value, conversionSpec) -> formatExponential(value, conversionSpec),
s: (value, conversionSpec) -> formatString(value, conversionSpec)
}
###*
* sprintf function
* @param {String} [formatString]
* @param {Arguments} [args]
* @return {String}
###
(exports ? this).sprintf = (formatString, args...) ->
formatStringLength = formatString.length
formatStringIterator = 0
argsLength = args.length
argsIterator = 0
resultString = ''
###*
* Get the current character at formatStringIterator
* @return {String}
###
consumeFormatStringChar = ->
if formatStringIterator >= formatStringLength
null
else
formatString[formatStringIterator++]
###*
* Get the current args
* @return {Object}
###
consumeArgument = ->
if argsIterator >= argsLength
throw new Error("Got #{argsLength} args, expecting more.")
else
args[argsIterator++]
###*
* Interpret a matched conversion specifier
* @param {Hash} [match]
* @return {ConversionSpecifier}
###
interpretConversionSpecifiersMatches = (match) ->
width = parseInt(match[2]) or null
if width == '*'
width = parseInt(consumeArgument())
throw new Error("Expecting an integer for width, got #{width}") unless width
precision = getDefaultPrecision(match[6])
if match[3]
if !match[4]
precision = 0
else if match[4] == '*'
precision = parseInt(consumeArgument())
throw new Error("Expecting a positive integer for precision, got #{precision}") unless precision >= 0
else
precision = parseInt(match[4])
new ConversionSpecifier(match[1], width, precision, match[5], match[6], !!match[3])
###*
* Read a conversion specifier from format string
* @return {Hash}
###
readConversionSpecifier = ->
match = CONVERSION_SPECIFIER_REGEXP.exec(formatString[formatStringIterator..])
if match
formatStringIterator += match[0].length
match
else
throw new Error("Unable to parse a format specifier, starting at index #{formatStringIterator}. " +
"The remaining string is '#{formatString}'")
###*
* Apply conversion specifier to argument
* @param {ConversionSpecifier} [conversionSpec]
* @return {String}
###
applyConversionSpecifier = (conversionSpec) ->
specifier = conversionSpec.specifier
if specifier == '%'
'%'
else
if !CONVERSION_SPECIFIER_FUNCTIONS.hasOwnProperty(specifier)
throw new Error("Unsupported specifier #{specifier}")
else
CONVERSION_SPECIFIER_FUNCTIONS[specifier](consumeArgument(), conversionSpec)
char = consumeFormatStringChar()
while(char)
if char == '%'
resultString += applyConversionSpecifier(interpretConversionSpecifiersMatches(readConversionSpecifier()))
else
resultString += char
char = consumeFormatStringChar()
resultString |
[
{
"context": " access token.\n @param {String} [options.email=loopback-with-admin@example.com] email address for admin user\n @param {String}",
"end": 568,
"score": 0.9999189376831055,
"start": 537,
"tag": "EMAIL",
"value": "loopback-with-admin@example.com"
},
{
"context": " admin user\n @param {String} [options.password=admin-user-password] password of admin user\n @param {Number} [opti",
"end": 734,
"score": 0.9988104104995728,
"start": 715,
"tag": "PASSWORD",
"value": "admin-user-password"
},
{
"context": "am {String} [options.password=admin-user-password] password of admin user\n @param {Number} [options.interv",
"end": 744,
"score": 0.8976653218269348,
"start": 736,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "[options.password=admin-user-password] password of admin user\n @param {Number} [options.intervalHours] Inter",
"end": 758,
"score": 0.9829179048538208,
"start": 748,
"tag": "PASSWORD",
"value": "admin user"
}
] | src/lib/loopback-server.coffee | CureApp/loopback-with-admin | 13 |
{ normalize } = require 'path'
AdminTokenManager = require '../server/admin-token-manager'
ParticipantTokenSetter = require '../server/participant-token-setter'
###*
launches loopback server
@class LoopbackServer
###
class LoopbackServer
entryPath: normalize __dirname + '/../../loopback/server/server.js'
###*
@param {Function|Array(String)} [options.fetch] function to return admin tokens (or promise of it). When string[] is given, these value are used for the admin access token.
@param {String} [options.email=loopback-with-admin@example.com] email address for admin user
@param {String} [options.id=loopback-with-admin-user-id] id of admin user
@param {String} [options.password=admin-user-password] password of admin user
@param {Number} [options.intervalHours] Interval hours to fetch new admin token.
@param {String} [participantToken] static token for participant user
###
launch: (options = {}, participantToken) -> new Promise (resolve, reject) =>
@app = require(@entryPath)
# see loopback/server/boot/admin.js
@app.lwaTokenManager = new AdminTokenManager(options)
# see loopback/server/boot/participant.js
if participantToken
@app.participantTokenSetter = new ParticipantTokenSetter(participantToken)
return @app.start (err) =>
return reject(err) if err
@startRefreshingAdminTokens(intervalHours = Number(options.intervalHours) || 12)
resolve()
###*
Start refreshing admin access tokens
@public
@method startRefreshingAdminTokens
@param {Number} [intervalHours=12]
###
startRefreshingAdminTokens: (intervalHours = 12) ->
console.log "Admin token will be refreshed every #{intervalHours} hours."
clearInterval(@timer) if @timer?
@timer = setInterval =>
@app.lwaTokenManager.refreshTokens()
, intervalHours * 3600 * 1000
###*
Check if the regular timer refreshing admin access tokens is set
@public
@method isRefreshingAdminTokens
@return {Boolean}
###
isRefreshingAdminTokens: -> @timer?
###*
Stop refreshing admin access tokens
@public
@method stopRefreshingAdminTokens
###
stopRefreshingAdminTokens: ->
console.log "Admin token will no more be refreshed."
clearInterval @timer if @timer?
module.exports = LoopbackServer
| 34002 |
{ normalize } = require 'path'
AdminTokenManager = require '../server/admin-token-manager'
ParticipantTokenSetter = require '../server/participant-token-setter'
###*
launches loopback server
@class LoopbackServer
###
class LoopbackServer
entryPath: normalize __dirname + '/../../loopback/server/server.js'
###*
@param {Function|Array(String)} [options.fetch] function to return admin tokens (or promise of it). When string[] is given, these value are used for the admin access token.
@param {String} [options.email=<EMAIL>] email address for admin user
@param {String} [options.id=loopback-with-admin-user-id] id of admin user
@param {String} [options.password=<PASSWORD>] <PASSWORD> of <PASSWORD>
@param {Number} [options.intervalHours] Interval hours to fetch new admin token.
@param {String} [participantToken] static token for participant user
###
launch: (options = {}, participantToken) -> new Promise (resolve, reject) =>
@app = require(@entryPath)
# see loopback/server/boot/admin.js
@app.lwaTokenManager = new AdminTokenManager(options)
# see loopback/server/boot/participant.js
if participantToken
@app.participantTokenSetter = new ParticipantTokenSetter(participantToken)
return @app.start (err) =>
return reject(err) if err
@startRefreshingAdminTokens(intervalHours = Number(options.intervalHours) || 12)
resolve()
###*
Start refreshing admin access tokens
@public
@method startRefreshingAdminTokens
@param {Number} [intervalHours=12]
###
startRefreshingAdminTokens: (intervalHours = 12) ->
console.log "Admin token will be refreshed every #{intervalHours} hours."
clearInterval(@timer) if @timer?
@timer = setInterval =>
@app.lwaTokenManager.refreshTokens()
, intervalHours * 3600 * 1000
###*
Check if the regular timer refreshing admin access tokens is set
@public
@method isRefreshingAdminTokens
@return {Boolean}
###
isRefreshingAdminTokens: -> @timer?
###*
Stop refreshing admin access tokens
@public
@method stopRefreshingAdminTokens
###
stopRefreshingAdminTokens: ->
console.log "Admin token will no more be refreshed."
clearInterval @timer if @timer?
module.exports = LoopbackServer
| true |
{ normalize } = require 'path'
AdminTokenManager = require '../server/admin-token-manager'
ParticipantTokenSetter = require '../server/participant-token-setter'
###*
launches loopback server
@class LoopbackServer
###
class LoopbackServer
entryPath: normalize __dirname + '/../../loopback/server/server.js'
###*
@param {Function|Array(String)} [options.fetch] function to return admin tokens (or promise of it). When string[] is given, these value are used for the admin access token.
@param {String} [options.email=PI:EMAIL:<EMAIL>END_PI] email address for admin user
@param {String} [options.id=loopback-with-admin-user-id] id of admin user
@param {String} [options.password=PI:PASSWORD:<PASSWORD>END_PI] PI:PASSWORD:<PASSWORD>END_PI of PI:PASSWORD:<PASSWORD>END_PI
@param {Number} [options.intervalHours] Interval hours to fetch new admin token.
@param {String} [participantToken] static token for participant user
###
launch: (options = {}, participantToken) -> new Promise (resolve, reject) =>
@app = require(@entryPath)
# see loopback/server/boot/admin.js
@app.lwaTokenManager = new AdminTokenManager(options)
# see loopback/server/boot/participant.js
if participantToken
@app.participantTokenSetter = new ParticipantTokenSetter(participantToken)
return @app.start (err) =>
return reject(err) if err
@startRefreshingAdminTokens(intervalHours = Number(options.intervalHours) || 12)
resolve()
###*
Start refreshing admin access tokens
@public
@method startRefreshingAdminTokens
@param {Number} [intervalHours=12]
###
startRefreshingAdminTokens: (intervalHours = 12) ->
console.log "Admin token will be refreshed every #{intervalHours} hours."
clearInterval(@timer) if @timer?
@timer = setInterval =>
@app.lwaTokenManager.refreshTokens()
, intervalHours * 3600 * 1000
###*
Check if the regular timer refreshing admin access tokens is set
@public
@method isRefreshingAdminTokens
@return {Boolean}
###
isRefreshingAdminTokens: -> @timer?
###*
Stop refreshing admin access tokens
@public
@method stopRefreshingAdminTokens
###
stopRefreshingAdminTokens: ->
console.log "Admin token will no more be refreshed."
clearInterval @timer if @timer?
module.exports = LoopbackServer
|
[
{
"context": "s\",\"Prov\",\"Eccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"",
"end": 505,
"score": 0.8026483058929443,
"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.7051619291305542,
"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.8735369443893433,
"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.6134071946144104,
"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.6057674884796143,
"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.8772698044776917,
"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.8447204828262329,
"start": 543,
"tag": "NAME",
"value": "Mic"
},
{
"context": "\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"L",
"end": 552,
"score": 0.590347170829773,
"start": 549,
"tag": "NAME",
"value": "Nah"
},
{
"context": "d\",\"Jonah\",\"Mic\",\"Nah\",\"Hab\",\"Zeph\",\"Hag\",\"Zech\",\"Mal\",\"Matt\",\"Mark\",\"Luke\",\"John\",\"Acts\",\"Rom\",\"1Cor\",",
"end": 584,
"score": 0.6499794721603394,
"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.9379973411560059,
"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.954888641834259,
"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.8850599527359009,
"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.7376314997673035,
"start": 608,
"tag": "NAME",
"value": "John"
},
{
"context": "ual(\"EpJer.1.1\")\n\t\texpect(p.parse(\"La Carta de Jeremías 1:1\").osis()).toEqual(\"EpJer.1.1\")\n\t\texpect(p.par",
"end": 10375,
"score": 0.6153736114501953,
"start": 10370,
"tag": "NAME",
"value": "emías"
},
{
"context": "is()).toEqual(\"EpJer.1.1\")\n\t\texpect(p.parse(\"Carta de Jeremias 1:1\").osis()).toEqual(\"EpJer.1.1\")\n\t\texp",
"end": 10437,
"score": 0.5143479704856873,
"start": 10435,
"tag": "NAME",
"value": "de"
},
{
"context": "oEqual(\"EpJer.1.1\")\n\t\texpect(p.parse(\"Carta de Jeremias 1:1\").osis()).toEqual(\"EpJer.1.1\")\n\t\texpect(p.par",
"end": 10446,
"score": 0.7131159901618958,
"start": 10441,
"tag": "NAME",
"value": "emias"
},
{
"context": "oEqual(\"EpJer.1.1\")\n\t\texpect(p.parse(\"Carta de Jeremías 1:1\").osis()).toEqual(\"EpJer.1.1\")\n\t\texpect(p.",
"end": 10514,
"score": 0.5684248805046082,
"start": 10512,
"tag": "NAME",
"value": "em"
},
{
"context": ").toEqual(\"EpJer.1.1\")\n\t\texpect(p.parse(\"Carta Jeremias 1:1\").osis()).toEqual(\"EpJer.1.1\")\n\t\texpect(p.par",
"end": 10585,
"score": 0.6276609897613525,
"start": 10580,
"tag": "NAME",
"value": "emias"
},
{
"context": ").toEqual(\"EpJer.1.1\")\n\t\texpect(p.parse(\"Carta Jeremías 1:1\").osis()).toEqual(\"EpJer.1.1\")\n\t\texpect(p.par",
"end": 10653,
"score": 0.582295835018158,
"start": 10648,
"tag": "NAME",
"value": "emías"
},
{
"context": "al(\"Deut.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Josh (es)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_pa",
"end": 14443,
"score": 0.9888061285018921,
"start": 14439,
"tag": "NAME",
"value": "Josh"
},
{
"context": "\tp.include_apocrypha true\n\tit \"should handle book: Josh (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Josue 1:1\").osis(",
"end": 14702,
"score": 0.9790780544281006,
"start": 14698,
"tag": "NAME",
"value": "Josh"
},
{
"context": "\t`\n\t\texpect(p.parse(\"Josue 1:1\").osis()).toEqual(\"Josh.1.1\")\n\t\texpect(p.parse(\"Josué 1:1\").osis()).toEqu",
"end": 14768,
"score": 0.7203341126441956,
"start": 14764,
"tag": "NAME",
"value": "Josh"
},
{
"context": "handle book: 2Sam (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Segundo Samuel 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\tex",
"end": 20708,
"score": 0.536483645439148,
"start": 20705,
"tag": "NAME",
"value": "Seg"
},
{
"context": "book: 2Sam (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Segundo Samuel 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars",
"end": 20719,
"score": 0.9826869368553162,
"start": 20713,
"tag": "NAME",
"value": "Samuel"
},
{
"context": "osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.parse(\"2.o. Samuel 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars",
"end": 20783,
"score": 0.9916528463363647,
"start": 20777,
"tag": "NAME",
"value": "Samuel"
},
{
"context": "osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.parse(\"2.º. Samuel 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars",
"end": 20847,
"score": 0.9893198013305664,
"start": 20841,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ".osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.parse(\"2.o Samuel 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars",
"end": 20910,
"score": 0.9871950149536133,
"start": 20904,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ".osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.parse(\"2.º Samuel 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars",
"end": 20973,
"score": 0.9891853928565979,
"start": 20967,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ".osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.parse(\"2o. Samuel 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars",
"end": 21036,
"score": 0.990382730960846,
"start": 21030,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ".osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.parse(\"2º. Samuel 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars",
"end": 21099,
"score": 0.9926744699478149,
"start": 21093,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ".osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.parse(\"II. Samuel 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars",
"end": 21162,
"score": 0.9919904470443726,
"start": 21156,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.parse(\"2. Samuel 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars",
"end": 21224,
"score": 0.984532356262207,
"start": 21218,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.parse(\"2o Samuel 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars",
"end": 21286,
"score": 0.9704011678695679,
"start": 21280,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.parse(\"2º Samuel 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars",
"end": 21348,
"score": 0.9702455997467041,
"start": 21342,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.parse(\"II Samuel 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars",
"end": 21410,
"score": 0.9497811198234558,
"start": 21404,
"tag": "NAME",
"value": "Samuel"
},
{
"context": "sis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.parse(\"2 Samuel 1:1\").osis()).toEqual(\"2Sam.1.1\")\n\t\texpect(p.pars",
"end": 21471,
"score": 0.9257391095161438,
"start": 21468,
"tag": "NAME",
"value": "uel"
},
{
"context": "book: 1Sam (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Primero Samuel 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 23270,
"score": 0.9727557897567749,
"start": 23264,
"tag": "NAME",
"value": "Samuel"
},
{
"context": "is()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"Primer Samuel 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 23336,
"score": 0.9798378944396973,
"start": 23330,
"tag": "NAME",
"value": "Samuel"
},
{
"context": "osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"1.o. Samuel 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 23400,
"score": 0.9869623184204102,
"start": 23394,
"tag": "NAME",
"value": "Samuel"
},
{
"context": "osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"1.º. Samuel 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 23464,
"score": 0.9834057092666626,
"start": 23458,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ".osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"1.o Samuel 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 23527,
"score": 0.9606801867485046,
"start": 23521,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ".osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"1.º Samuel 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 23590,
"score": 0.9298911094665527,
"start": 23584,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ".osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"1o. Samuel 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 23653,
"score": 0.9682470560073853,
"start": 23647,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ".osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"1º. Samuel 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 23716,
"score": 0.9641131162643433,
"start": 23710,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"1. Samuel 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 23778,
"score": 0.9644904732704163,
"start": 23772,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"1o Samuel 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 23840,
"score": 0.9052883982658386,
"start": 23834,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"1º Samuel 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 23902,
"score": 0.9368298649787903,
"start": 23896,
"tag": "NAME",
"value": "Samuel"
},
{
"context": ").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"I. Samuel 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 23964,
"score": 0.9837116003036499,
"start": 23958,
"tag": "NAME",
"value": "Samuel"
},
{
"context": "sis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"1 Samuel 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 24025,
"score": 0.7622830867767334,
"start": 24022,
"tag": "NAME",
"value": "uel"
},
{
"context": "sis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"I Samuel 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 24086,
"score": 0.6886340975761414,
"start": 24083,
"tag": "NAME",
"value": "uel"
},
{
"context": "\")\n\t\tp.include_apocrypha(false)\n\t\texpect(p.parse(\"PRIMERO SAMUEL 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 24467,
"score": 0.9112248420715332,
"start": 24453,
"tag": "NAME",
"value": "PRIMERO SAMUEL"
},
{
"context": "1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.parse(\"PRIMER SAMUEL 1:1\").osis()).toEqual(\"1Sam.1.1\")\n\t\texpect(p.pars",
"end": 24533,
"score": 0.9496107697486877,
"start": 24520,
"tag": "NAME",
"value": "PRIMER SAMUEL"
},
{
"context": "al(\"Ezek.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Dan (es)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_pa",
"end": 80028,
"score": 0.9335970878601074,
"start": 80025,
"tag": "NAME",
"value": "Dan"
},
{
"context": "\tp.include_apocrypha true\n\tit \"should handle book: Dan (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Daniel 1:1\").osis",
"end": 80286,
"score": 0.9936843514442444,
"start": 80283,
"tag": "NAME",
"value": "Dan"
},
{
"context": " handle book: Dan (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Daniel 1:1\").osis()).toEqual(\"Dan.1.1\")\n\t\texpect(p.parse",
"end": 80325,
"score": 0.9903256297111511,
"start": 80319,
"tag": "NAME",
"value": "Daniel"
},
{
"context": "al(\"Obad.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Jonah (es)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_",
"end": 84203,
"score": 0.79181307554245,
"start": 84200,
"tag": "NAME",
"value": "Jon"
},
{
"context": "\tp.include_apocrypha true\n\tit \"should handle book: Jonah (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Jonah 1:1\").osi",
"end": 84463,
"score": 0.781254768371582,
"start": 84460,
"tag": "NAME",
"value": "Jon"
},
{
"context": "andle book: Jonah (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Jonah 1:1\").osis()).toEqual(\"Jonah.1.1\")\n\t\texpect(p.par",
"end": 84503,
"score": 0.6452155113220215,
"start": 84498,
"tag": "NAME",
"value": "Jonah"
},
{
"context": "\").osis()).toEqual(\"Jonah.1.1\")\n\t\texpect(p.parse(\"Jonás 1:1\").osis()).toEqual(\"Jonah.1.1\")\n\t\texpect(p.p",
"end": 84619,
"score": 0.6912126541137695,
"start": 84616,
"tag": "NAME",
"value": "Jon"
},
{
"context": "l(\"Jonah.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Mic (es)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_",
"end": 85128,
"score": 0.7360767126083374,
"start": 85127,
"tag": "NAME",
"value": "M"
},
{
"context": "ual(\"Mal.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Matt (es)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv",
"end": 92293,
"score": 0.5766847729682922,
"start": 92292,
"tag": "NAME",
"value": "M"
},
{
"context": "\tp.include_apocrypha true\n\tit \"should handle book: Matt (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"El Evangelio de M",
"end": 92555,
"score": 0.7369469404220581,
"start": 92551,
"tag": "NAME",
"value": "Matt"
},
{
"context": "l(\"3John.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book John (es)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_pa",
"end": 200714,
"score": 0.900881290435791,
"start": 200710,
"tag": "NAME",
"value": "John"
},
{
"context": "\tp.include_apocrypha true\n\tit \"should handle book: John (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"El Evangelio de J",
"end": 200973,
"score": 0.9502068758010864,
"start": 200969,
"tag": "NAME",
"value": "John"
},
{
"context": "1\").osis()).toEqual(\"John.1.1\")\n\t\texpect(p.parse(\"JOHN 1:1\").osis()).toEqual(\"John.1.1\")\n\t\texpect(p.pars",
"end": 202199,
"score": 0.6919687390327454,
"start": 202195,
"tag": "NAME",
"value": "JOHN"
},
{
"context": "\tp.include_apocrypha true\n\tit \"should handle book: Eph (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Efesios 1:1\").o",
"end": 213083,
"score": 0.872917115688324,
"start": 213082,
"tag": "NAME",
"value": "E"
},
{
"context": ".include_apocrypha true\n\tit \"should handle book: Eph (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Efesios 1:1\").osi",
"end": 213085,
"score": 0.4796214997768402,
"start": 213083,
"tag": "NAME",
"value": "ph"
},
{
"context": "ual(\"Eph.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Phil (es)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_pa",
"end": 213727,
"score": 0.5991406440734863,
"start": 213723,
"tag": "NAME",
"value": "Phil"
},
{
"context": "\tp.include_apocrypha true\n\tit \"should handle book: Phil (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Filipenses 1:1\").",
"end": 213986,
"score": 0.7593266367912292,
"start": 213982,
"tag": "NAME",
"value": "Phil"
},
{
"context": "ual(\"Heb.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Jonah,Job,Josh,Joel (es)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\t",
"end": 258890,
"score": 0.7030718922615051,
"start": 258885,
"tag": "NAME",
"value": "Jonah"
},
{
"context": "1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Jonah,Job,Josh,Joel (es)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new b",
"end": 258899,
"score": 0.8074240684509277,
"start": 258895,
"tag": "NAME",
"value": "Josh"
},
{
"context": "\tp.include_apocrypha true\n\tit \"should handle book: Jonah,Job,Josh,Joel (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Jo ",
"end": 259164,
"score": 0.6348050832748413,
"start": 259159,
"tag": "NAME",
"value": "Jonah"
},
{
"context": "ude_apocrypha true\n\tit \"should handle book: Jonah,Job,Josh,Joel (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Jo 1:1\"",
"end": 259168,
"score": 0.843985378742218,
"start": 259165,
"tag": "NAME",
"value": "Job"
},
{
"context": "apocrypha true\n\tit \"should handle book: Jonah,Job,Josh,Joel (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Jo 1:1\").osi",
"end": 259173,
"score": 0.8355506658554077,
"start": 259169,
"tag": "NAME",
"value": "Josh"
},
{
"context": "ha true\n\tit \"should handle book: Jonah,Job,Josh,Joel (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Jo 1:1\").osis()).",
"end": 259178,
"score": 0.9033513069152832,
"start": 259176,
"tag": "NAME",
"value": "el"
},
{
"context": "al(\"Jude.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Matt,Mark,Mal (es)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = n",
"end": 259837,
"score": 0.9960390329360962,
"start": 259833,
"tag": "NAME",
"value": "Matt"
},
{
"context": "de.1.1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Matt,Mark,Mal (es)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bc",
"end": 259842,
"score": 0.9932607412338257,
"start": 259838,
"tag": "NAME",
"value": "Mark"
},
{
"context": "1\")\n\t\t`\n\t\ttrue\ndescribe \"Localized book Matt,Mark,Mal (es)\", ->\n\tp = {}\n\tbeforeEach ->\n\t\tp = new bcv_pa",
"end": 259846,
"score": 0.7583454847335815,
"start": 259843,
"tag": "NAME",
"value": "Mal"
},
{
"context": "\tp.include_apocrypha true\n\tit \"should handle book: Matt,Mark,Mal (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Ma 1:1\")",
"end": 260105,
"score": 0.9925886392593384,
"start": 260101,
"tag": "NAME",
"value": "Matt"
},
{
"context": "lude_apocrypha true\n\tit \"should handle book: Matt,Mark,Mal (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Ma 1:1\").osis",
"end": 260110,
"score": 0.988486647605896,
"start": 260106,
"tag": "NAME",
"value": "Mark"
},
{
"context": "apocrypha true\n\tit \"should handle book: Matt,Mark,Mal (es)\", ->\n\t\t`\n\t\texpect(p.parse(\"Ma 1:1\").osis()).",
"end": 260114,
"score": 0.8517513871192932,
"start": 260111,
"tag": "NAME",
"value": "Mal"
}
] | lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/es/spec.coffee | saiba-mais/bible-lessons | 0 | bcv_parser = require("../../js/es_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 (es)", ->
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 (es)", ->
`
expect(p.parse("Genesis 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Génesis 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gén 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Ge 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gn 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gé 1:1").osis()).toEqual("Gen.1.1")
p.include_apocrypha(false)
expect(p.parse("GENESIS 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GÉNESIS 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GÉN 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GE 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GN 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GÉ 1:1").osis()).toEqual("Gen.1.1")
`
true
describe "Localized book Exod (es)", ->
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 (es)", ->
`
expect(p.parse("Exodo 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Éxodo 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Éxod 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exd 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exo 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Éxd 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Éxo 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Ex 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Éx 1:1").osis()).toEqual("Exod.1.1")
p.include_apocrypha(false)
expect(p.parse("EXODO 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("ÉXODO 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("ÉXOD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXO 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("ÉXD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("ÉXO 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EX 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("ÉX 1:1").osis()).toEqual("Exod.1.1")
`
true
describe "Localized book Bel (es)", ->
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 (es)", ->
`
expect(p.parse("Bel y el Serpiente 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bel y el Dragon 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bel y el Dragón 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1")
`
true
describe "Localized book Lev (es)", ->
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 (es)", ->
`
expect(p.parse("Levitico 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Levítico 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Lv 1:1").osis()).toEqual("Lev.1.1")
p.include_apocrypha(false)
expect(p.parse("LEVITICO 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEVÍTICO 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LV 1:1").osis()).toEqual("Lev.1.1")
`
true
describe "Localized book Num (es)", ->
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 (es)", ->
`
expect(p.parse("Numeros 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Números 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Núm 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Nm 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Nu 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Nú 1:1").osis()).toEqual("Num.1.1")
p.include_apocrypha(false)
expect(p.parse("NUMEROS 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NÚMEROS 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NÚM 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NM 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NU 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NÚ 1:1").osis()).toEqual("Num.1.1")
`
true
describe "Localized book Sir (es)", ->
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 (es)", ->
`
expect(p.parse("Eclesiastico 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Eclesiástico 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Siracides 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sirácides 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Siracida 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sirácida 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Ecclus 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sirac 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sirác 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Si 1:1").osis()).toEqual("Sir.1.1")
`
true
describe "Localized book Wis (es)", ->
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 (es)", ->
`
expect(p.parse("Sabiduria 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Sabiduría 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Sab 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Sb 1:1").osis()).toEqual("Wis.1.1")
`
true
describe "Localized book Lam (es)", ->
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 (es)", ->
`
expect(p.parse("Lamentaciones 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lamintaciones 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lamentacione 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lamintacione 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("La 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lm 1:1").osis()).toEqual("Lam.1.1")
p.include_apocrypha(false)
expect(p.parse("LAMENTACIONES 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAMINTACIONES 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAMENTACIONE 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAMINTACIONE 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LA 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LM 1:1").osis()).toEqual("Lam.1.1")
`
true
describe "Localized book EpJer (es)", ->
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 (es)", ->
`
expect(p.parse("La Carta de Jeremias 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("La Carta de Jeremías 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("Carta de Jeremias 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("Carta de Jeremías 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("Carta Jeremias 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("Carta Jeremías 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("Carta Jer 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1")
`
true
describe "Localized book Rev (es)", ->
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 (es)", ->
`
expect(p.parse("El Apocalipsis 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Apocalipsis 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Apoc 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Ap 1:1").osis()).toEqual("Rev.1.1")
p.include_apocrypha(false)
expect(p.parse("EL APOCALIPSIS 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("APOCALIPSIS 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("APOC 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("AP 1:1").osis()).toEqual("Rev.1.1")
`
true
describe "Localized book PrMan (es)", ->
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 (es)", ->
`
expect(p.parse("La Oracion de Manases 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("La Oracion de Manasés 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("La Oración de Manases 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("La Oración de Manasés 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Oracion de Manases 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Oracion de Manasés 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Oración de Manases 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Oración de Manasés 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Or. Man 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Or Man 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1")
`
true
describe "Localized book Deut (es)", ->
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 (es)", ->
`
expect(p.parse("Deuteronomio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deutoronomio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Dueteronomio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deuteronmio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deutoronmio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deutronomio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deutronmio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deu 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Dt 1:1").osis()).toEqual("Deut.1.1")
p.include_apocrypha(false)
expect(p.parse("DEUTERONOMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTORONOMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DUETERONOMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTERONMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTORONMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTRONOMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTRONMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEU 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DT 1:1").osis()).toEqual("Deut.1.1")
`
true
describe "Localized book Josh (es)", ->
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 (es)", ->
`
expect(p.parse("Josue 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("Josué 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")
p.include_apocrypha(false)
expect(p.parse("JOSUE 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("JOSUÉ 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")
`
true
describe "Localized book Judg (es)", ->
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 (es)", ->
`
expect(p.parse("Jueces 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Juec 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Jue 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Jc 1:1").osis()).toEqual("Judg.1.1")
p.include_apocrypha(false)
expect(p.parse("JUECES 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JUEC 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JUE 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JC 1:1").osis()).toEqual("Judg.1.1")
`
true
describe "Localized book Ruth (es)", ->
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 (es)", ->
`
expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Rut 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Rt 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Ru 1:1").osis()).toEqual("Ruth.1.1")
p.include_apocrypha(false)
expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RUT 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RT 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RU 1:1").osis()).toEqual("Ruth.1.1")
`
true
describe "Localized book 1Esd (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("Primer Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1.o. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1.º. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1.o Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1.º Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1o. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1º. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1o Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1º Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Esdr 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Esd 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1")
`
true
describe "Localized book 2Esd (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2.o. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2.º. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2.o Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2.º Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2o. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2º. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2o Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2º Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Esdr 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Esd 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1")
`
true
describe "Localized book Isa (es)", ->
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 (es)", ->
`
expect(p.parse("Isaias 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Isaías 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Is 1:1").osis()).toEqual("Isa.1.1")
p.include_apocrypha(false)
expect(p.parse("ISAIAS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("ISAÍAS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IS 1:1").osis()).toEqual("Isa.1.1")
`
true
describe "Localized book 2Sam (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.o. Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.º. Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.o Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.º Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2o. Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2º. Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2o Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2º Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Sa 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Sm 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 S 1:1").osis()).toEqual("2Sam.1.1")
p.include_apocrypha(false)
expect(p.parse("SEGUNDO SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.O. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.º. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.O SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.º SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2O. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2º. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2O SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2º SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 S 1:1").osis()).toEqual("2Sam.1.1")
`
true
describe "Localized book 1Sam (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Primer Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.o. Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.º. Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.o Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.º Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1o. Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1º. Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1o Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1º Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 Sa 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 Sm 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 S 1:1").osis()).toEqual("1Sam.1.1")
p.include_apocrypha(false)
expect(p.parse("PRIMERO SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRIMER SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.O. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.º. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.O SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.º SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1O. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1º. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1O SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1º SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 S 1:1").osis()).toEqual("1Sam.1.1")
`
true
describe "Localized book 2Kgs (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.o. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.º. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.o Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.º Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2o. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2º. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2o Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2º Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Rees 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Reye 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Reys 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Ryes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Ree 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Res 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Rey 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Rye 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Rys 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Re 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Rs 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Ry 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 R 1:1").osis()).toEqual("2Kgs.1.1")
p.include_apocrypha(false)
expect(p.parse("SEGUNDO REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.O. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.º. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.O REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.º REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2O. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2º. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2O REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2º REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REYE 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REYS 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REE 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REY 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RYE 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RYS 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RE 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RS 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RY 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 R 1:1").osis()).toEqual("2Kgs.1.1")
`
true
describe "Localized book 1Kgs (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Primer Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.o. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.º. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.o Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.º Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1o. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1º. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1o Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1º Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Rees 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Reye 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Reys 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Ryes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Ree 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Res 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Rey 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Rye 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Rys 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Re 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Rs 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Ry 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 R 1:1").osis()).toEqual("1Kgs.1.1")
p.include_apocrypha(false)
expect(p.parse("PRIMERO REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRIMER REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.O. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.º. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.O REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.º REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1O. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1º. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1O REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1º REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REYE 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REYS 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REE 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REY 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RYE 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RYS 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RE 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RS 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RY 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 R 1:1").osis()).toEqual("1Kgs.1.1")
`
true
describe "Localized book 2Chr (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Segundo Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.o. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.o. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.o Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.o Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2o. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2o. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2o Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2o Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Cron 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Crón 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Cro 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Cró 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Cr 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("SEGUNDO CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("SEGUNDO CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.O. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.O. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.O CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.O CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2O. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2O. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2O CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2O CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRÓN 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRO 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRÓ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CR 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1")
`
true
describe "Localized book 1Chr (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Primero Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Primer Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Primer Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.o. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.o. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.o Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.o Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1o. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1o. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1o Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1o Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Cron 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Crón 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Cro 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Cró 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Cr 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("PRIMERO CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRIMERO CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRIMER CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRIMER CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.O. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.O. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.O CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.O CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1O. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1O. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1O CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1O CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRÓN 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRO 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRÓ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CR 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1")
`
true
describe "Localized book Ezra (es)", ->
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 (es)", ->
`
expect(p.parse("Esdras 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Esdr 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Esd 1:1").osis()).toEqual("Ezra.1.1")
p.include_apocrypha(false)
expect(p.parse("ESDRAS 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("ESDR 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("ESD 1:1").osis()).toEqual("Ezra.1.1")
`
true
describe "Localized book Neh (es)", ->
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 (es)", ->
`
expect(p.parse("Nehemias 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemías 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Ne 1:1").osis()).toEqual("Neh.1.1")
p.include_apocrypha(false)
expect(p.parse("NEHEMIAS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMÍAS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NE 1:1").osis()).toEqual("Neh.1.1")
`
true
describe "Localized book GkEsth (es)", ->
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 (es)", ->
`
expect(p.parse("Ester (Griego) 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester (griego) 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester Griego 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester griego 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Est Gr 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1")
`
true
describe "Localized book Esth (es)", ->
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 (es)", ->
`
expect(p.parse("Ester 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")
expect(p.parse("Es 1:1").osis()).toEqual("Esth.1.1")
p.include_apocrypha(false)
expect(p.parse("ESTER 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")
expect(p.parse("ES 1:1").osis()).toEqual("Esth.1.1")
`
true
describe "Localized book Job (es)", ->
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 (es)", ->
`
expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("Jb 1:1").osis()).toEqual("Job.1.1")
p.include_apocrypha(false)
expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("JB 1:1").osis()).toEqual("Job.1.1")
`
true
describe "Localized book Ps (es)", ->
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 (es)", ->
`
expect(p.parse("Salmos 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Salmo 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Salm 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Sal 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")
expect(p.parse("Sl 1:1").osis()).toEqual("Ps.1.1")
p.include_apocrypha(false)
expect(p.parse("SALMOS 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("SALMO 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("SALM 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("SAL 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")
expect(p.parse("SL 1:1").osis()).toEqual("Ps.1.1")
`
true
describe "Localized book PrAzar (es)", ->
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 (es)", ->
`
expect(p.parse("Cantico de Azarias 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Cantico de Azarías 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Cántico de Azarias 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Cántico de Azarías 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Oracion de Azarias 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Oracion de Azarías 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Oración de Azarias 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Oración de Azarías 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Azarias 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Azarías 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Or Azar 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Or Az 1:1").osis()).toEqual("PrAzar.1.1")
`
true
describe "Localized book Prov (es)", ->
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 (es)", ->
`
expect(p.parse("Probverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Porverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Preverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Proberbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Proverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Poverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Preverbio 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Provebios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Proverbio 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prverbio 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prvbos 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prvbo 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prvbs 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prvb 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Pro 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prv 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Pr 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Pv 1:1").osis()).toEqual("Prov.1.1")
p.include_apocrypha(false)
expect(p.parse("PROBVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PORVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PREVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROBERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("POVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PREVERBIO 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROVEBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROVERBIO 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVERBIO 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVBOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVBO 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVBS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVB 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRO 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRV 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PR 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PV 1:1").osis()).toEqual("Prov.1.1")
`
true
describe "Localized book Eccl (es)", ->
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 (es)", ->
`
expect(p.parse("Ecclesiastices 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiasticés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiasties 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiastiés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiastices 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiasticés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiasties 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiastiés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eccles 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecles 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecc 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecl 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ec 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Qo 1:1").osis()).toEqual("Eccl.1.1")
p.include_apocrypha(false)
expect(p.parse("ECCLESIASTICES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTICÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTIES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTIÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTICES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTICÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTIES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTIÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECC 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECL 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("EC 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("QO 1:1").osis()).toEqual("Eccl.1.1")
`
true
describe "Localized book SgThree (es)", ->
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 (es)", ->
`
expect(p.parse("El Canto de los Tres Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los Tres Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los Tres Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los Tres Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los Tres Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los Tres Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tres Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tres Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("3 Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("3 Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Ct 3 Jo 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Ct 3 Jó 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1")
`
true
describe "Localized book Song (es)", ->
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 (es)", ->
`
expect(p.parse("El Cantar de los Cantares 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Cantare de los Cantares 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Cantar de los Cantares 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Cantares 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Cant 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Can 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Cnt 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Ct 1:1").osis()).toEqual("Song.1.1")
p.include_apocrypha(false)
expect(p.parse("EL CANTAR DE LOS CANTARES 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CANTARE DE LOS CANTARES 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CANTAR DE LOS CANTARES 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CANTARES 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CANT 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CAN 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CNT 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CT 1:1").osis()).toEqual("Song.1.1")
`
true
describe "Localized book Jer (es)", ->
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 (es)", ->
`
expect(p.parse("Jeremias 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jeremías 1:1").osis()).toEqual("Jer.1.1")
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("Jere 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jr 1:1").osis()).toEqual("Jer.1.1")
p.include_apocrypha(false)
expect(p.parse("JEREMIAS 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMÍAS 1:1").osis()).toEqual("Jer.1.1")
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("JERE 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JR 1:1").osis()).toEqual("Jer.1.1")
`
true
describe "Localized book Ezek (es)", ->
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 (es)", ->
`
expect(p.parse("Ezeequiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezeiquiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziequiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziiquiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezeequel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezeiquel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezequial 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezequiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziequel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziiquel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziquiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezequel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziquel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezequ 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezeq 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eze 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezq 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ez 1:1").osis()).toEqual("Ezek.1.1")
p.include_apocrypha(false)
expect(p.parse("EZEEQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEIQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIEQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIIQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEEQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEIQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEQUIAL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIEQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIIQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEQU 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEQ 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZE 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZQ 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZ 1:1").osis()).toEqual("Ezek.1.1")
`
true
describe "Localized book Dan (es)", ->
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 (es)", ->
`
expect(p.parse("Daniel 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Da 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Dl 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Dn 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 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DA 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DL 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DN 1:1").osis()).toEqual("Dan.1.1")
`
true
describe "Localized book Hos (es)", ->
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 (es)", ->
`
expect(p.parse("Oseas 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Os 1:1").osis()).toEqual("Hos.1.1")
p.include_apocrypha(false)
expect(p.parse("OSEAS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("OS 1:1").osis()).toEqual("Hos.1.1")
`
true
describe "Localized book Joel (es)", ->
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 (es)", ->
`
expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("Joe 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("JOE 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("JL 1:1").osis()).toEqual("Joel.1.1")
`
true
describe "Localized book Amos (es)", ->
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 (es)", ->
`
expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Amós 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Amo 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Ams 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Amó 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ÓS 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AMO 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AMS 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AMÓ 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AM 1:1").osis()).toEqual("Amos.1.1")
`
true
describe "Localized book Obad (es)", ->
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 (es)", ->
`
expect(p.parse("Abdias 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdías 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abd 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Ab 1:1").osis()).toEqual("Obad.1.1")
p.include_apocrypha(false)
expect(p.parse("ABDIAS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDÍAS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABD 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("AB 1:1").osis()).toEqual("Obad.1.1")
`
true
describe "Localized book Jonah (es)", ->
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 (es)", ->
`
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("Jonás 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jns 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jon 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("JONÁS 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JNS 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JON 1:1").osis()).toEqual("Jonah.1.1")
`
true
describe "Localized book Mic (es)", ->
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 (es)", ->
`
expect(p.parse("Miqueas 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Miq 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mi 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mq 1:1").osis()).toEqual("Mic.1.1")
p.include_apocrypha(false)
expect(p.parse("MIQUEAS 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MIQ 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MI 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MQ 1:1").osis()).toEqual("Mic.1.1")
`
true
describe "Localized book Nah (es)", ->
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 (es)", ->
`
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("Nahu 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Nahú 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Na 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Nh 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("NAHU 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NAHÚ 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NA 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NH 1:1").osis()).toEqual("Nah.1.1")
`
true
describe "Localized book Hab (es)", ->
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 (es)", ->
`
expect(p.parse("Habbacac 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Habbacuc 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Habacac 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Habacuc 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Habc 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("HABBACAC 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HABBACUC 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HABACAC 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HABACUC 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HABC 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1")
`
true
describe "Localized book Zeph (es)", ->
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 (es)", ->
`
expect(p.parse("Sofonias 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofonías 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sof 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sf 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("So 1:1").osis()).toEqual("Zeph.1.1")
p.include_apocrypha(false)
expect(p.parse("SOFONIAS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONÍAS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOF 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SF 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SO 1:1").osis()).toEqual("Zeph.1.1")
`
true
describe "Localized book Hag (es)", ->
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 (es)", ->
`
expect(p.parse("Haggeo 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Hageo 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Ageo 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Ag 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Hg 1:1").osis()).toEqual("Hag.1.1")
p.include_apocrypha(false)
expect(p.parse("HAGGEO 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("HAGEO 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("AGEO 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("AG 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("HG 1:1").osis()).toEqual("Hag.1.1")
`
true
describe "Localized book Zech (es)", ->
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 (es)", ->
`
expect(p.parse("Zacarias 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacarías 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacar 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zac 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Za 1:1").osis()).toEqual("Zech.1.1")
p.include_apocrypha(false)
expect(p.parse("ZACARIAS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACARÍAS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACAR 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZAC 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZA 1:1").osis()).toEqual("Zech.1.1")
`
true
describe "Localized book Mal (es)", ->
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 (es)", ->
`
expect(p.parse("Malaquias 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Malaquías 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Malaqu 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Mala 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Ml 1:1").osis()).toEqual("Mal.1.1")
p.include_apocrypha(false)
expect(p.parse("MALAQUIAS 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALAQUÍAS 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALAQU 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALA 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("ML 1:1").osis()).toEqual("Mal.1.1")
`
true
describe "Localized book Matt (es)", ->
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 (es)", ->
`
expect(p.parse("El Evangelio de Mateo 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Evangelio de Mateo 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("San Mateo 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Mateo 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Mat 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Mt 1:1").osis()).toEqual("Matt.1.1")
p.include_apocrypha(false)
expect(p.parse("EL EVANGELIO DE MATEO 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("EVANGELIO DE MATEO 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("SAN MATEO 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATEO 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MAT 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MT 1:1").osis()).toEqual("Matt.1.1")
`
true
describe "Localized book 2Macc (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macc 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Mac 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Mc 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 M 1:1").osis()).toEqual("2Macc.1.1")
`
true
describe "Localized book 3Macc (es)", ->
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 (es)", ->
`
expect(p.parse("Tercero Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macc 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Mac 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Mc 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 M 1:1").osis()).toEqual("3Macc.1.1")
`
true
describe "Localized book 4Macc (es)", ->
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 (es)", ->
`
expect(p.parse("Cuarto Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macc 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Mac 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Mc 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 M 1:1").osis()).toEqual("4Macc.1.1")
`
true
describe "Localized book 1Macc (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macc 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Mac 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Mc 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 M 1:1").osis()).toEqual("1Macc.1.1")
`
true
describe "Localized book Mark (es)", ->
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 (es)", ->
`
expect(p.parse("El Evangelio de Marcos 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Evangelio de Marcos 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("San Marcos 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Marcos 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mrcos 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Marc 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mar 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mrc 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mc 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mr 1:1").osis()).toEqual("Mark.1.1")
p.include_apocrypha(false)
expect(p.parse("EL EVANGELIO DE MARCOS 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("EVANGELIO DE MARCOS 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("SAN MARCOS 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARCOS 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MRCOS 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARC 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MAR 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MRC 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MC 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MR 1:1").osis()).toEqual("Mark.1.1")
`
true
describe "Localized book Luke (es)", ->
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 (es)", ->
`
expect(p.parse("El Evangelio de Lucas 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Evangelio de Lucas 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("San Lucas 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lucas 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Luc 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lc 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lu 1:1").osis()).toEqual("Luke.1.1")
p.include_apocrypha(false)
expect(p.parse("EL EVANGELIO DE LUCAS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("EVANGELIO DE LUCAS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("SAN LUCAS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUCAS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUC 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LC 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LU 1:1").osis()).toEqual("Luke.1.1")
`
true
describe "Localized book 1John (es)", ->
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 (es)", ->
`
expect(p.parse("Primero San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Jn 1:1").osis()).toEqual("1John.1.1")
p.include_apocrypha(false)
expect(p.parse("PRIMERO SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JN 1:1").osis()).toEqual("1John.1.1")
`
true
describe "Localized book 2John (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Jn 1:1").osis()).toEqual("2John.1.1")
p.include_apocrypha(false)
expect(p.parse("SEGUNDO SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JN 1:1").osis()).toEqual("2John.1.1")
`
true
describe "Localized book 3John (es)", ->
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 (es)", ->
`
expect(p.parse("Tercero San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Jn 1:1").osis()).toEqual("3John.1.1")
p.include_apocrypha(false)
expect(p.parse("TERCERO SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JN 1:1").osis()).toEqual("3John.1.1")
`
true
describe "Localized book John (es)", ->
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 (es)", ->
`
expect(p.parse("El Evangelio de Jaan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("El Evangelio de Jaun 1:1").osis()).toEqual("John.1.1")
expect(p.parse("El Evangelio de Juan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("El Evangelio de Juun 1:1").osis()).toEqual("John.1.1")
expect(p.parse("San Juan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Jaan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Jaun 1:1").osis()).toEqual("John.1.1")
expect(p.parse("John 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Juan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Juun 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Jn 1:1").osis()).toEqual("John.1.1")
p.include_apocrypha(false)
expect(p.parse("EL EVANGELIO DE JAAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("EL EVANGELIO DE JAUN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("EL EVANGELIO DE JUAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("EL EVANGELIO DE JUUN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("SAN JUAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JAAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JAUN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JUAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JUUN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JN 1:1").osis()).toEqual("John.1.1")
`
true
describe "Localized book Acts (es)", ->
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 (es)", ->
`
expect(p.parse("Los Hechos de los Apostoles 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Los Hechos de los Apóstoles 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hechos de los Apostoles 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hechos de los Apóstoles 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Los Hechos 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hechos 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hech 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hch 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hec 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hc 1:1").osis()).toEqual("Acts.1.1")
p.include_apocrypha(false)
expect(p.parse("LOS HECHOS DE LOS APOSTOLES 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("LOS HECHOS DE LOS APÓSTOLES 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HECHOS DE LOS APOSTOLES 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HECHOS DE LOS APÓSTOLES 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("LOS HECHOS 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HECHOS 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HECH 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HCH 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HEC 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HC 1:1").osis()).toEqual("Acts.1.1")
`
true
describe "Localized book Rom (es)", ->
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 (es)", ->
`
expect(p.parse("Romanos 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Romano 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rmns 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Roms 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rmn 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rms 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Ros 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rm 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Ro 1:1").osis()).toEqual("Rom.1.1")
p.include_apocrypha(false)
expect(p.parse("ROMANOS 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROMANO 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RMNS 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROMS 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RMN 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RMS 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROS 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RO 1:1").osis()).toEqual("Rom.1.1")
`
true
describe "Localized book 2Cor (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.o. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.º. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.o Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.º Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2o. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2º. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2o Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2º Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Corinti 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Corini 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Corint 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Corin 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Cor 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Co 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("SEGUNDO CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.O. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.º. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.O CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.º CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2O. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2º. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2O CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2º CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CORINTI 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CORINI 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CORINT 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CORIN 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 COR 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CO 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1")
`
true
describe "Localized book 1Cor (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Primer Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.o. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.º. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.o Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.º Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1o. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1º. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1o Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1º Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Corinti 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Corini 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Corint 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Corin 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Cor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Co 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("PRIMERO CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRIMER CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.O. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.º. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.O CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.º CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1O. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1º. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1O CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1º CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CORINTI 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CORINI 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CORINT 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CORIN 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 COR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CO 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1")
`
true
describe "Localized book Gal (es)", ->
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 (es)", ->
`
expect(p.parse("Galatas 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gálatas 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Galat 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gálat 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gál 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Ga 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gá 1:1").osis()).toEqual("Gal.1.1")
p.include_apocrypha(false)
expect(p.parse("GALATAS 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GÁLATAS 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GALAT 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GÁLAT 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GÁL 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GA 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GÁ 1:1").osis()).toEqual("Gal.1.1")
`
true
describe "Localized book Eph (es)", ->
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 (es)", ->
`
expect(p.parse("Efesios 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efes 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efe 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("EFESIOS 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFES 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFE 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 (es)", ->
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 (es)", ->
`
expect(p.parse("Filipenses 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Filip 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Fili 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")
expect(p.parse("Flp 1:1").osis()).toEqual("Phil.1.1")
p.include_apocrypha(false)
expect(p.parse("FILIPENSES 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILIP 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILI 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")
expect(p.parse("FLP 1:1").osis()).toEqual("Phil.1.1")
`
true
describe "Localized book Col (es)", ->
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 (es)", ->
`
expect(p.parse("Colosenses 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Colos 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1")
p.include_apocrypha(false)
expect(p.parse("COLOSENSES 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("COLOS 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1")
`
true
describe "Localized book 2Thess (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Segundo Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Segundo Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Segundo Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Thess 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tes 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Ts 1:1").osis()).toEqual("2Thess.1.1")
p.include_apocrypha(false)
expect(p.parse("SEGUNDO TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("SEGUNDO TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("SEGUNDO TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("SEGUNDO TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 THESS 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TS 1:1").osis()).toEqual("2Thess.1.1")
`
true
describe "Localized book 1Thess (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primero Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primer Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primer Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primero Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primero Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primer Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primer Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Thess 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tes 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Ts 1:1").osis()).toEqual("1Thess.1.1")
p.include_apocrypha(false)
expect(p.parse("PRIMERO TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMERO TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMER TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMER TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMERO TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMERO TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMER TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMER TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 THESS 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TS 1:1").osis()).toEqual("1Thess.1.1")
`
true
describe "Localized book 2Tim (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.o. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.º. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.o Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.º Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2o. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2º. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2o Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2º Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Ti 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Tm 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("SEGUNDO TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.O. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.º. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.O TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.º TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2O. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2º. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2O TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2º TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1")
`
true
describe "Localized book 1Tim (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Primer Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.o. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.º. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.o Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.º Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1o. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1º. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1o Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1º Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Ti 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Tm 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("PRIMERO TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRIMER TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.O. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.º. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.O TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.º TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1O. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1º. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1O TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1º TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1")
`
true
describe "Localized book Titus (es)", ->
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 (es)", ->
`
expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Tito 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Tit 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Ti 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Tt 1:1").osis()).toEqual("Titus.1.1")
p.include_apocrypha(false)
expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TITO 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TIT 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TI 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TT 1:1").osis()).toEqual("Titus.1.1")
`
true
describe "Localized book Phlm (es)", ->
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 (es)", ->
`
expect(p.parse("Filemon 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Filemón 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Filem 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Flmn 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Flm 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Fmn 1:1").osis()).toEqual("Phlm.1.1")
p.include_apocrypha(false)
expect(p.parse("FILEMON 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FILEMÓN 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FILEM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FLMN 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FLM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FMN 1:1").osis()).toEqual("Phlm.1.1")
`
true
describe "Localized book Heb (es)", ->
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 (es)", ->
`
expect(p.parse("Hebeees 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeeos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeers 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeoes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeoos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeors 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heberes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heberos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heberrs 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboees 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboeos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboers 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebooes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebooos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboors 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebores 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboros 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heborrs 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrees 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebreos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrers 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebroes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebroos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrors 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrres 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrros 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrrrs 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebees 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebers 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebors 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebreo 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebres 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebros 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrrs 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrs 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebr 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("He 1:1").osis()).toEqual("Heb.1.1")
p.include_apocrypha(false)
expect(p.parse("HEBEEES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEEOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEERS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEOES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEOOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEORS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBERES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEROS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBERRS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOEES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOEOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOERS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOOES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOOOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOORS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBORES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOROS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBORRS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBREES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBREOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRERS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBROES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBROOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRORS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRRES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRROS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRRRS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBERS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBORS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBREO 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBROS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRRS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBR 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HE 1:1").osis()).toEqual("Heb.1.1")
`
true
describe "Localized book Jas (es)", ->
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 (es)", ->
`
expect(p.parse("Santiago 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Sant 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Stg 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("St 1:1").osis()).toEqual("Jas.1.1")
p.include_apocrypha(false)
expect(p.parse("SANTIAGO 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("SANT 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("STG 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("ST 1:1").osis()).toEqual("Jas.1.1")
`
true
describe "Localized book 2Pet (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.o. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.o San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2o. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Segundo Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2o San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.o. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.o Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2o. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2o Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Ped 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Pd 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Pe 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 P 1:1").osis()).toEqual("2Pet.1.1")
p.include_apocrypha(false)
expect(p.parse("SEGUNDO SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.O. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.O SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2O. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("SEGUNDO PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2O SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.O. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.O PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2O. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2O PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PED 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PD 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PE 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 P 1:1").osis()).toEqual("2Pet.1.1")
`
true
describe "Localized book 1Pet (es)", ->
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 (es)", ->
`
expect(p.parse("Primero San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Primer San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.o. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.o San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1o. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Primero Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1o San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Primer Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.o. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.o Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1o. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1o Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Ped 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Pd 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Pe 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 P 1:1").osis()).toEqual("1Pet.1.1")
p.include_apocrypha(false)
expect(p.parse("PRIMERO SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRIMER SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.O. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.O SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1O. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRIMERO PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1O SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRIMER PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.O. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.O PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1O. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1O PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PED 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PD 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PE 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 P 1:1").osis()).toEqual("1Pet.1.1")
`
true
describe "Localized book Jude (es)", ->
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 (es)", ->
`
expect(p.parse("San Judas 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Judas 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Jdas 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("Jd 1:1").osis()).toEqual("Jude.1.1")
p.include_apocrypha(false)
expect(p.parse("SAN JUDAS 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDAS 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JDAS 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("JD 1:1").osis()).toEqual("Jude.1.1")
`
true
describe "Localized book Tob (es)", ->
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 (es)", ->
`
expect(p.parse("Tobit 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobi 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobt 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tb 1:1").osis()).toEqual("Tob.1.1")
`
true
describe "Localized book Jdt (es)", ->
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 (es)", ->
`
expect(p.parse("Judit 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Jdit 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Judt 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1")
`
true
describe "Localized book Bar (es)", ->
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 (es)", ->
`
expect(p.parse("Baruc 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Ba 1:1").osis()).toEqual("Bar.1.1")
`
true
describe "Localized book Sus (es)", ->
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 (es)", ->
`
expect(p.parse("Susana 1:1").osis()).toEqual("Sus.1.1")
expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1")
`
true
describe "Localized book Hab,Hag (es)", ->
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,Hag (es)", ->
`
expect(p.parse("Ha 1:1").osis()).toEqual("Hab.1.1")
p.include_apocrypha(false)
expect(p.parse("HA 1:1").osis()).toEqual("Hab.1.1")
`
true
describe "Localized book Heb,Hab (es)", ->
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,Hab (es)", ->
`
expect(p.parse("Hb 1:1").osis()).toEqual("Heb.1.1")
p.include_apocrypha(false)
expect(p.parse("HB 1:1").osis()).toEqual("Heb.1.1")
`
true
describe "Localized book Jonah,Job,Josh,Joel (es)", ->
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,Job,Josh,Joel (es)", ->
`
expect(p.parse("Jo 1:1").osis()).toEqual("Jonah.1.1")
p.include_apocrypha(false)
expect(p.parse("JO 1:1").osis()).toEqual("Jonah.1.1")
`
true
describe "Localized book Jude,Judg (es)", ->
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,Judg (es)", ->
`
expect(p.parse("Ju 1:1").osis()).toEqual("Jude.1.1")
p.include_apocrypha(false)
expect(p.parse("JU 1:1").osis()).toEqual("Jude.1.1")
`
true
describe "Localized book Matt,Mark,Mal (es)", ->
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,Mark,Mal (es)", ->
`
expect(p.parse("Ma 1:1").osis()).toEqual("Matt.1.1")
p.include_apocrypha(false)
expect(p.parse("MA 1:1").osis()).toEqual("Matt.1.1")
`
true
describe "Localized book Phil,Phlm (es)", ->
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,Phlm (es)", ->
`
expect(p.parse("Fil 1:1").osis()).toEqual("Phil.1.1")
p.include_apocrypha(false)
expect(p.parse("FIL 1:1").osis()).toEqual("Phil.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 ["es"]
it "should handle ranges (es)", ->
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"
expect(p.parse("Titus 1:1 al 2").osis()).toEqual "Titus.1.1-Titus.1.2"
expect(p.parse("Matt 1al2").osis()).toEqual "Matt.1-Matt.2"
expect(p.parse("Phlm 2 AL 3").osis()).toEqual "Phlm.1.2-Phlm.1.3"
it "should handle chapters (es)", ->
expect(p.parse("Titus 1:1, capítulos 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPÍTULOS 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, capitulos 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPITULOS 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, capítulo 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPÍTULO 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, capitulo 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPITULO 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, caps. 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPS. 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, caps 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPS 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, cap. 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAP. 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, cap 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAP 6").osis()).toEqual "Matt.3.4,Matt.6"
it "should handle verses (es)", ->
expect(p.parse("Exod 1:1 versículos 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERSÍCULOS 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 versiculos 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERSICULOS 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 versículo 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERSÍCULO 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 versiculo 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERSICULO 6").osis()).toEqual "Phlm.1.6"
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"
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"
expect(p.parse("Exod 1:1 ver. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VER. 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 ver 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VER 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vss. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VSS. 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vss 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VSS 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vs. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VS. 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vs 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VS 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vv. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VV. 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vv 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VV 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 v. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm V. 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 v 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm V 6").osis()).toEqual "Phlm.1.6"
it "should handle 'and' (es)", ->
expect(p.parse("Exod 1:1 y 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm 2 Y 6").osis()).toEqual "Phlm.1.2,Phlm.1.6"
it "should handle titles (es)", ->
expect(p.parse("Ps 3 subtítulo, 4:2, 5:subtítulo").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 SUBTÍTULO, 4:2, 5:SUBTÍTULO").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("Ps 3 subtitulo, 4:2, 5:subtitulo").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 SUBTITULO, 4:2, 5:SUBTITULO").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("Ps 3 título, 4:2, 5:título").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 TÍTULO, 4:2, 5:TÍTULO").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("Ps 3 titulo, 4:2, 5:titulo").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 TITULO, 4:2, 5:TITULO").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("Ps 3 tít, 4:2, 5:tít").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 TÍT, 4:2, 5:TÍT").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
it "should handle 'ff' (es)", ->
expect(p.parse("Rev 3y siguientes, 4:2y siguientes").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
expect(p.parse("REV 3 Y SIGUIENTES, 4:2 Y SIGUIENTES").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
expect(p.parse("Rev 3y sig, 4:2y sig").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
expect(p.parse("REV 3 Y SIG, 4:2 Y SIG").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
it "should handle translations (es)", ->
expect(p.parse("Lev 1 (DHH)").osis_and_translations()).toEqual [["Lev.1", "DHH"]]
expect(p.parse("lev 1 dhh").osis_and_translations()).toEqual [["Lev.1", "DHH"]]
expect(p.parse("Lev 1 (LBLA)").osis_and_translations()).toEqual [["Lev.1", "LBLA"]]
expect(p.parse("lev 1 lbla").osis_and_translations()).toEqual [["Lev.1", "LBLA"]]
expect(p.parse("Lev 1 (NBLH)").osis_and_translations()).toEqual [["Lev.1", "NBLH"]]
expect(p.parse("lev 1 nblh").osis_and_translations()).toEqual [["Lev.1", "NBLH"]]
expect(p.parse("Lev 1 (NTV)").osis_and_translations()).toEqual [["Lev.1", "NTV"]]
expect(p.parse("lev 1 ntv").osis_and_translations()).toEqual [["Lev.1", "NTV"]]
expect(p.parse("Lev 1 (NVI)").osis_and_translations()).toEqual [["Lev.1", "NVI"]]
expect(p.parse("lev 1 nvi").osis_and_translations()).toEqual [["Lev.1", "NVI"]]
expect(p.parse("Lev 1 (RVR)").osis_and_translations()).toEqual [["Lev.1", "RVR"]]
expect(p.parse("lev 1 rvr").osis_and_translations()).toEqual [["Lev.1", "RVR"]]
expect(p.parse("Lev 1 (RVR1960)").osis_and_translations()).toEqual [["Lev.1", "RVR1960"]]
expect(p.parse("lev 1 rvr1960").osis_and_translations()).toEqual [["Lev.1", "RVR1960"]]
expect(p.parse("Lev 1 (TLA)").osis_and_translations()).toEqual [["Lev.1", "TLA"]]
expect(p.parse("lev 1 tla").osis_and_translations()).toEqual [["Lev.1", "TLA"]]
it "should handle book ranges (es)", ->
p.set_options {book_alone_strategy: "full", book_range_strategy: "include"}
expect(p.parse("1.º á 3.º Jaan").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º al 3.º Jaan").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º á 3.º Jaun").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º al 3.º Jaun").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º á 3.º Juan").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º al 3.º Juan").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º á 3.º Juun").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º al 3.º Juun").osis()).toEqual "1John.1-3John.1"
it "should handle boundaries (es)", ->
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"
| 94771 | bcv_parser = require("../../js/es_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>","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 (es)", ->
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 (es)", ->
`
expect(p.parse("Genesis 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Génesis 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gén 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Ge 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gn 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gé 1:1").osis()).toEqual("Gen.1.1")
p.include_apocrypha(false)
expect(p.parse("GENESIS 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GÉNESIS 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GÉN 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GE 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GN 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GÉ 1:1").osis()).toEqual("Gen.1.1")
`
true
describe "Localized book Exod (es)", ->
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 (es)", ->
`
expect(p.parse("Exodo 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Éxodo 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Éxod 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exd 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exo 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Éxd 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Éxo 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Ex 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Éx 1:1").osis()).toEqual("Exod.1.1")
p.include_apocrypha(false)
expect(p.parse("EXODO 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("ÉXODO 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("ÉXOD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXO 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("ÉXD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("ÉXO 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EX 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("ÉX 1:1").osis()).toEqual("Exod.1.1")
`
true
describe "Localized book Bel (es)", ->
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 (es)", ->
`
expect(p.parse("Bel y el Serpiente 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bel y el Dragon 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bel y el Dragón 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1")
`
true
describe "Localized book Lev (es)", ->
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 (es)", ->
`
expect(p.parse("Levitico 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Levítico 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Lv 1:1").osis()).toEqual("Lev.1.1")
p.include_apocrypha(false)
expect(p.parse("LEVITICO 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEVÍTICO 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LV 1:1").osis()).toEqual("Lev.1.1")
`
true
describe "Localized book Num (es)", ->
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 (es)", ->
`
expect(p.parse("Numeros 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Números 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Núm 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Nm 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Nu 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Nú 1:1").osis()).toEqual("Num.1.1")
p.include_apocrypha(false)
expect(p.parse("NUMEROS 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NÚMEROS 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NÚM 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NM 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NU 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NÚ 1:1").osis()).toEqual("Num.1.1")
`
true
describe "Localized book Sir (es)", ->
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 (es)", ->
`
expect(p.parse("Eclesiastico 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Eclesiástico 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Siracides 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sirácides 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Siracida 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sirácida 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Ecclus 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sirac 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sirác 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Si 1:1").osis()).toEqual("Sir.1.1")
`
true
describe "Localized book Wis (es)", ->
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 (es)", ->
`
expect(p.parse("Sabiduria 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Sabiduría 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Sab 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Sb 1:1").osis()).toEqual("Wis.1.1")
`
true
describe "Localized book Lam (es)", ->
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 (es)", ->
`
expect(p.parse("Lamentaciones 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lamintaciones 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lamentacione 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lamintacione 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("La 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lm 1:1").osis()).toEqual("Lam.1.1")
p.include_apocrypha(false)
expect(p.parse("LAMENTACIONES 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAMINTACIONES 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAMENTACIONE 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAMINTACIONE 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LA 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LM 1:1").osis()).toEqual("Lam.1.1")
`
true
describe "Localized book EpJer (es)", ->
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 (es)", ->
`
expect(p.parse("La Carta de Jeremias 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("La Carta de Jer<NAME> 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("Carta <NAME> Jer<NAME> 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("Carta de Jer<NAME>ías 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("Carta Jer<NAME> 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("Carta Jer<NAME> 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("Carta Jer 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1")
`
true
describe "Localized book Rev (es)", ->
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 (es)", ->
`
expect(p.parse("El Apocalipsis 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Apocalipsis 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Apoc 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Ap 1:1").osis()).toEqual("Rev.1.1")
p.include_apocrypha(false)
expect(p.parse("EL APOCALIPSIS 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("APOCALIPSIS 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("APOC 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("AP 1:1").osis()).toEqual("Rev.1.1")
`
true
describe "Localized book PrMan (es)", ->
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 (es)", ->
`
expect(p.parse("La Oracion de Manases 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("La Oracion de Manasés 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("La Oración de Manases 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("La Oración de Manasés 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Oracion de Manases 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Oracion de Manasés 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Oración de Manases 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Oración de Manasés 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Or. Man 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Or Man 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1")
`
true
describe "Localized book Deut (es)", ->
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 (es)", ->
`
expect(p.parse("Deuteronomio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deutoronomio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Dueteronomio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deuteronmio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deutoronmio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deutronomio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deutronmio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deu 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Dt 1:1").osis()).toEqual("Deut.1.1")
p.include_apocrypha(false)
expect(p.parse("DEUTERONOMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTORONOMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DUETERONOMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTERONMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTORONMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTRONOMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTRONMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEU 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DT 1:1").osis()).toEqual("Deut.1.1")
`
true
describe "Localized book <NAME> (es)", ->
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> (es)", ->
`
expect(p.parse("Josue 1:1").osis()).toEqual("<NAME>.1.1")
expect(p.parse("Josué 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")
p.include_apocrypha(false)
expect(p.parse("JOSUE 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("JOSUÉ 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")
`
true
describe "Localized book Judg (es)", ->
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 (es)", ->
`
expect(p.parse("Jueces 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Juec 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Jue 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Jc 1:1").osis()).toEqual("Judg.1.1")
p.include_apocrypha(false)
expect(p.parse("JUECES 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JUEC 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JUE 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JC 1:1").osis()).toEqual("Judg.1.1")
`
true
describe "Localized book Ruth (es)", ->
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 (es)", ->
`
expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Rut 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Rt 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Ru 1:1").osis()).toEqual("Ruth.1.1")
p.include_apocrypha(false)
expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RUT 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RT 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RU 1:1").osis()).toEqual("Ruth.1.1")
`
true
describe "Localized book 1Esd (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("Primer Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1.o. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1.º. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1.o Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1.º Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1o. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1º. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1o Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1º Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Esdr 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Esd 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1")
`
true
describe "Localized book 2Esd (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2.o. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2.º. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2.o Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2.º Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2o. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2º. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2o Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2º Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Esdr 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Esd 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1")
`
true
describe "Localized book Isa (es)", ->
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 (es)", ->
`
expect(p.parse("Isaias 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Isaías 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Is 1:1").osis()).toEqual("Isa.1.1")
p.include_apocrypha(false)
expect(p.parse("ISAIAS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("ISAÍAS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IS 1:1").osis()).toEqual("Isa.1.1")
`
true
describe "Localized book 2Sam (es)", ->
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 (es)", ->
`
expect(p.parse("<NAME>undo <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.o. <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.º. <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.o <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.º <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2o. <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2º. <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2o <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2º <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Sam<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Sa 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Sm 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 S 1:1").osis()).toEqual("2Sam.1.1")
p.include_apocrypha(false)
expect(p.parse("SEGUNDO SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.O. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.º. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.O SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.º SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2O. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2º. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2O SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2º SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 S 1:1").osis()).toEqual("2Sam.1.1")
`
true
describe "Localized book 1Sam (es)", ->
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 (es)", ->
`
expect(p.parse("Primero <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Primer <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.o. <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.º. <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.o <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.º <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1o. <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1º. <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1o <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<NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I Sam<NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 Sa 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 Sm 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 S 1:1").osis()).toEqual("1Sam.1.1")
p.include_apocrypha(false)
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.O. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.º. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.O SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.º SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1O. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1º. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1O SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1º SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 S 1:1").osis()).toEqual("1Sam.1.1")
`
true
describe "Localized book 2Kgs (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.o. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.º. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.o Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.º Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2o. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2º. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2o Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2º Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Rees 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Reye 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Reys 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Ryes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Ree 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Res 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Rey 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Rye 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Rys 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Re 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Rs 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Ry 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 R 1:1").osis()).toEqual("2Kgs.1.1")
p.include_apocrypha(false)
expect(p.parse("SEGUNDO REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.O. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.º. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.O REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.º REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2O. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2º. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2O REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2º REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REYE 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REYS 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REE 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REY 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RYE 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RYS 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RE 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RS 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RY 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 R 1:1").osis()).toEqual("2Kgs.1.1")
`
true
describe "Localized book 1Kgs (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Primer Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.o. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.º. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.o Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.º Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1o. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1º. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1o Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1º Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Rees 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Reye 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Reys 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Ryes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Ree 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Res 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Rey 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Rye 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Rys 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Re 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Rs 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Ry 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 R 1:1").osis()).toEqual("1Kgs.1.1")
p.include_apocrypha(false)
expect(p.parse("PRIMERO REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRIMER REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.O. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.º. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.O REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.º REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1O. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1º. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1O REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1º REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REYE 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REYS 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REE 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REY 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RYE 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RYS 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RE 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RS 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RY 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 R 1:1").osis()).toEqual("1Kgs.1.1")
`
true
describe "Localized book 2Chr (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Segundo Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.o. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.o. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.o Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.o Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2o. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2o. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2o Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2o Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Cron 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Crón 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Cro 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Cró 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Cr 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("SEGUNDO CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("SEGUNDO CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.O. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.O. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.O CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.O CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2O. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2O. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2O CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2O CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRÓN 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRO 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRÓ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CR 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1")
`
true
describe "Localized book 1Chr (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Primero Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Primer Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Primer Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.o. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.o. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.o Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.o Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1o. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1o. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1o Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1o Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Cron 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Crón 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Cro 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Cró 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Cr 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("PRIMERO CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRIMERO CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRIMER CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRIMER CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.O. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.O. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.O CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.O CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1O. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1O. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1O CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1O CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRÓN 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRO 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRÓ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CR 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1")
`
true
describe "Localized book Ezra (es)", ->
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 (es)", ->
`
expect(p.parse("Esdras 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Esdr 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Esd 1:1").osis()).toEqual("Ezra.1.1")
p.include_apocrypha(false)
expect(p.parse("ESDRAS 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("ESDR 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("ESD 1:1").osis()).toEqual("Ezra.1.1")
`
true
describe "Localized book Neh (es)", ->
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 (es)", ->
`
expect(p.parse("Nehemias 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemías 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Ne 1:1").osis()).toEqual("Neh.1.1")
p.include_apocrypha(false)
expect(p.parse("NEHEMIAS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMÍAS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NE 1:1").osis()).toEqual("Neh.1.1")
`
true
describe "Localized book GkEsth (es)", ->
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 (es)", ->
`
expect(p.parse("Ester (Griego) 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester (griego) 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester Griego 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester griego 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Est Gr 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1")
`
true
describe "Localized book Esth (es)", ->
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 (es)", ->
`
expect(p.parse("Ester 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")
expect(p.parse("Es 1:1").osis()).toEqual("Esth.1.1")
p.include_apocrypha(false)
expect(p.parse("ESTER 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")
expect(p.parse("ES 1:1").osis()).toEqual("Esth.1.1")
`
true
describe "Localized book Job (es)", ->
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 (es)", ->
`
expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("Jb 1:1").osis()).toEqual("Job.1.1")
p.include_apocrypha(false)
expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("JB 1:1").osis()).toEqual("Job.1.1")
`
true
describe "Localized book Ps (es)", ->
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 (es)", ->
`
expect(p.parse("Salmos 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Salmo 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Salm 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Sal 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")
expect(p.parse("Sl 1:1").osis()).toEqual("Ps.1.1")
p.include_apocrypha(false)
expect(p.parse("SALMOS 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("SALMO 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("SALM 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("SAL 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")
expect(p.parse("SL 1:1").osis()).toEqual("Ps.1.1")
`
true
describe "Localized book PrAzar (es)", ->
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 (es)", ->
`
expect(p.parse("Cantico de Azarias 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Cantico de Azarías 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Cántico de Azarias 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Cántico de Azarías 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Oracion de Azarias 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Oracion de Azarías 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Oración de Azarias 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Oración de Azarías 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Azarias 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Azarías 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Or Azar 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Or Az 1:1").osis()).toEqual("PrAzar.1.1")
`
true
describe "Localized book Prov (es)", ->
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 (es)", ->
`
expect(p.parse("Probverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Porverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Preverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Proberbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Proverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Poverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Preverbio 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Provebios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Proverbio 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prverbio 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prvbos 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prvbo 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prvbs 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prvb 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Pro 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prv 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Pr 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Pv 1:1").osis()).toEqual("Prov.1.1")
p.include_apocrypha(false)
expect(p.parse("PROBVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PORVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PREVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROBERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("POVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PREVERBIO 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROVEBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROVERBIO 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVERBIO 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVBOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVBO 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVBS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVB 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRO 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRV 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PR 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PV 1:1").osis()).toEqual("Prov.1.1")
`
true
describe "Localized book Eccl (es)", ->
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 (es)", ->
`
expect(p.parse("Ecclesiastices 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiasticés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiasties 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiastiés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiastices 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiasticés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiasties 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiastiés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eccles 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecles 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecc 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecl 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ec 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Qo 1:1").osis()).toEqual("Eccl.1.1")
p.include_apocrypha(false)
expect(p.parse("ECCLESIASTICES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTICÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTIES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTIÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTICES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTICÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTIES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTIÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECC 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECL 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("EC 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("QO 1:1").osis()).toEqual("Eccl.1.1")
`
true
describe "Localized book SgThree (es)", ->
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 (es)", ->
`
expect(p.parse("El Canto de los Tres Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los Tres Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los Tres Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los Tres Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los Tres Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los Tres Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tres Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tres Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("3 Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("3 Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Ct 3 Jo 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Ct 3 Jó 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1")
`
true
describe "Localized book Song (es)", ->
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 (es)", ->
`
expect(p.parse("El Cantar de los Cantares 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Cantare de los Cantares 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Cantar de los Cantares 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Cantares 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Cant 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Can 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Cnt 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Ct 1:1").osis()).toEqual("Song.1.1")
p.include_apocrypha(false)
expect(p.parse("EL CANTAR DE LOS CANTARES 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CANTARE DE LOS CANTARES 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CANTAR DE LOS CANTARES 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CANTARES 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CANT 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CAN 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CNT 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CT 1:1").osis()).toEqual("Song.1.1")
`
true
describe "Localized book Jer (es)", ->
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 (es)", ->
`
expect(p.parse("Jeremias 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jeremías 1:1").osis()).toEqual("Jer.1.1")
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("Jere 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jr 1:1").osis()).toEqual("Jer.1.1")
p.include_apocrypha(false)
expect(p.parse("JEREMIAS 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMÍAS 1:1").osis()).toEqual("Jer.1.1")
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("JERE 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JR 1:1").osis()).toEqual("Jer.1.1")
`
true
describe "Localized book Ezek (es)", ->
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 (es)", ->
`
expect(p.parse("Ezeequiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezeiquiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziequiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziiquiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezeequel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezeiquel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezequial 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezequiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziequel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziiquel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziquiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezequel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziquel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezequ 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezeq 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eze 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezq 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ez 1:1").osis()).toEqual("Ezek.1.1")
p.include_apocrypha(false)
expect(p.parse("EZEEQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEIQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIEQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIIQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEEQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEIQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEQUIAL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIEQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIIQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEQU 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEQ 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZE 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZQ 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZ 1:1").osis()).toEqual("Ezek.1.1")
`
true
describe "Localized book <NAME> (es)", ->
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> (es)", ->
`
expect(p.parse("<NAME> 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Da 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Dl 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Dn 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 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DA 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DL 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DN 1:1").osis()).toEqual("Dan.1.1")
`
true
describe "Localized book Hos (es)", ->
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 (es)", ->
`
expect(p.parse("Oseas 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Os 1:1").osis()).toEqual("Hos.1.1")
p.include_apocrypha(false)
expect(p.parse("OSEAS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("OS 1:1").osis()).toEqual("Hos.1.1")
`
true
describe "Localized book Joel (es)", ->
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 (es)", ->
`
expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("Joe 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("JOE 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("JL 1:1").osis()).toEqual("Joel.1.1")
`
true
describe "Localized book Amos (es)", ->
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 (es)", ->
`
expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Amós 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Amo 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Ams 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Amó 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ÓS 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AMO 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AMS 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AMÓ 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AM 1:1").osis()).toEqual("Amos.1.1")
`
true
describe "Localized book Obad (es)", ->
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 (es)", ->
`
expect(p.parse("Abdias 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdías 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abd 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Ab 1:1").osis()).toEqual("Obad.1.1")
p.include_apocrypha(false)
expect(p.parse("ABDIAS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDÍAS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABD 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("AB 1:1").osis()).toEqual("Obad.1.1")
`
true
describe "Localized book <NAME>ah (es)", ->
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>ah (es)", ->
`
expect(p.parse("<NAME> 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jonas 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("<NAME>ás 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jns 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jon 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("JONÁS 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JNS 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JON 1:1").osis()).toEqual("Jonah.1.1")
`
true
describe "Localized book <NAME>ic (es)", ->
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 (es)", ->
`
expect(p.parse("Miqueas 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Miq 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mi 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mq 1:1").osis()).toEqual("Mic.1.1")
p.include_apocrypha(false)
expect(p.parse("MIQUEAS 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MIQ 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MI 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MQ 1:1").osis()).toEqual("Mic.1.1")
`
true
describe "Localized book Nah (es)", ->
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 (es)", ->
`
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("Nahu 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Nahú 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Na 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Nh 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("NAHU 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NAHÚ 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NA 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NH 1:1").osis()).toEqual("Nah.1.1")
`
true
describe "Localized book Hab (es)", ->
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 (es)", ->
`
expect(p.parse("Habbacac 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Habbacuc 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Habacac 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Habacuc 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Habc 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("HABBACAC 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HABBACUC 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HABACAC 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HABACUC 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HABC 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1")
`
true
describe "Localized book Zeph (es)", ->
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 (es)", ->
`
expect(p.parse("Sofonias 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofonías 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sof 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sf 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("So 1:1").osis()).toEqual("Zeph.1.1")
p.include_apocrypha(false)
expect(p.parse("SOFONIAS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONÍAS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOF 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SF 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SO 1:1").osis()).toEqual("Zeph.1.1")
`
true
describe "Localized book Hag (es)", ->
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 (es)", ->
`
expect(p.parse("Haggeo 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Hageo 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Ageo 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Ag 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Hg 1:1").osis()).toEqual("Hag.1.1")
p.include_apocrypha(false)
expect(p.parse("HAGGEO 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("HAGEO 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("AGEO 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("AG 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("HG 1:1").osis()).toEqual("Hag.1.1")
`
true
describe "Localized book Zech (es)", ->
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 (es)", ->
`
expect(p.parse("Zacarias 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacarías 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacar 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zac 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Za 1:1").osis()).toEqual("Zech.1.1")
p.include_apocrypha(false)
expect(p.parse("ZACARIAS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACARÍAS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACAR 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZAC 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZA 1:1").osis()).toEqual("Zech.1.1")
`
true
describe "Localized book Mal (es)", ->
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 (es)", ->
`
expect(p.parse("Malaquias 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Malaquías 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Malaqu 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Mala 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Ml 1:1").osis()).toEqual("Mal.1.1")
p.include_apocrypha(false)
expect(p.parse("MALAQUIAS 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALAQUÍAS 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALAQU 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALA 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("ML 1:1").osis()).toEqual("Mal.1.1")
`
true
describe "Localized book <NAME>att (es)", ->
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> (es)", ->
`
expect(p.parse("El Evangelio de Mateo 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Evangelio de Mateo 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("San Mateo 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Mateo 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Mat 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Mt 1:1").osis()).toEqual("Matt.1.1")
p.include_apocrypha(false)
expect(p.parse("EL EVANGELIO DE MATEO 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("EVANGELIO DE MATEO 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("SAN MATEO 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATEO 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MAT 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MT 1:1").osis()).toEqual("Matt.1.1")
`
true
describe "Localized book 2Macc (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macc 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Mac 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Mc 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 M 1:1").osis()).toEqual("2Macc.1.1")
`
true
describe "Localized book 3Macc (es)", ->
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 (es)", ->
`
expect(p.parse("Tercero Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macc 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Mac 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Mc 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 M 1:1").osis()).toEqual("3Macc.1.1")
`
true
describe "Localized book 4Macc (es)", ->
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 (es)", ->
`
expect(p.parse("Cuarto Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macc 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Mac 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Mc 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 M 1:1").osis()).toEqual("4Macc.1.1")
`
true
describe "Localized book 1Macc (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macc 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Mac 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Mc 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 M 1:1").osis()).toEqual("1Macc.1.1")
`
true
describe "Localized book Mark (es)", ->
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 (es)", ->
`
expect(p.parse("El Evangelio de Marcos 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Evangelio de Marcos 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("San Marcos 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Marcos 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mrcos 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Marc 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mar 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mrc 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mc 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mr 1:1").osis()).toEqual("Mark.1.1")
p.include_apocrypha(false)
expect(p.parse("EL EVANGELIO DE MARCOS 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("EVANGELIO DE MARCOS 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("SAN MARCOS 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARCOS 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MRCOS 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARC 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MAR 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MRC 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MC 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MR 1:1").osis()).toEqual("Mark.1.1")
`
true
describe "Localized book Luke (es)", ->
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 (es)", ->
`
expect(p.parse("El Evangelio de Lucas 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Evangelio de Lucas 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("San Lucas 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lucas 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Luc 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lc 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lu 1:1").osis()).toEqual("Luke.1.1")
p.include_apocrypha(false)
expect(p.parse("EL EVANGELIO DE LUCAS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("EVANGELIO DE LUCAS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("SAN LUCAS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUCAS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUC 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LC 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LU 1:1").osis()).toEqual("Luke.1.1")
`
true
describe "Localized book 1John (es)", ->
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 (es)", ->
`
expect(p.parse("Primero San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Jn 1:1").osis()).toEqual("1John.1.1")
p.include_apocrypha(false)
expect(p.parse("PRIMERO SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JN 1:1").osis()).toEqual("1John.1.1")
`
true
describe "Localized book 2John (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Jn 1:1").osis()).toEqual("2John.1.1")
p.include_apocrypha(false)
expect(p.parse("SEGUNDO SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JN 1:1").osis()).toEqual("2John.1.1")
`
true
describe "Localized book 3John (es)", ->
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 (es)", ->
`
expect(p.parse("Tercero San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Jn 1:1").osis()).toEqual("3John.1.1")
p.include_apocrypha(false)
expect(p.parse("TERCERO SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JN 1:1").osis()).toEqual("3John.1.1")
`
true
describe "Localized book <NAME> (es)", ->
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> (es)", ->
`
expect(p.parse("El Evangelio de Jaan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("El Evangelio de Jaun 1:1").osis()).toEqual("John.1.1")
expect(p.parse("El Evangelio de Juan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("El Evangelio de Juun 1:1").osis()).toEqual("John.1.1")
expect(p.parse("San Juan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Jaan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Jaun 1:1").osis()).toEqual("John.1.1")
expect(p.parse("John 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Juan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Juun 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Jn 1:1").osis()).toEqual("John.1.1")
p.include_apocrypha(false)
expect(p.parse("EL EVANGELIO DE JAAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("EL EVANGELIO DE JAUN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("EL EVANGELIO DE JUAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("EL EVANGELIO DE JUUN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("SAN JUAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JAAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JAUN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JUAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JUUN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JN 1:1").osis()).toEqual("John.1.1")
`
true
describe "Localized book Acts (es)", ->
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 (es)", ->
`
expect(p.parse("Los Hechos de los Apostoles 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Los Hechos de los Apóstoles 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hechos de los Apostoles 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hechos de los Apóstoles 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Los Hechos 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hechos 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hech 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hch 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hec 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hc 1:1").osis()).toEqual("Acts.1.1")
p.include_apocrypha(false)
expect(p.parse("LOS HECHOS DE LOS APOSTOLES 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("LOS HECHOS DE LOS APÓSTOLES 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HECHOS DE LOS APOSTOLES 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HECHOS DE LOS APÓSTOLES 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("LOS HECHOS 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HECHOS 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HECH 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HCH 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HEC 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HC 1:1").osis()).toEqual("Acts.1.1")
`
true
describe "Localized book Rom (es)", ->
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 (es)", ->
`
expect(p.parse("Romanos 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Romano 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rmns 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Roms 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rmn 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rms 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Ros 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rm 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Ro 1:1").osis()).toEqual("Rom.1.1")
p.include_apocrypha(false)
expect(p.parse("ROMANOS 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROMANO 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RMNS 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROMS 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RMN 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RMS 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROS 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RO 1:1").osis()).toEqual("Rom.1.1")
`
true
describe "Localized book 2Cor (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.o. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.º. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.o Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.º Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2o. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2º. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2o Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2º Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Corinti 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Corini 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Corint 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Corin 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Cor 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Co 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("SEGUNDO CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.O. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.º. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.O CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.º CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2O. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2º. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2O CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2º CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CORINTI 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CORINI 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CORINT 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CORIN 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 COR 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CO 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1")
`
true
describe "Localized book 1Cor (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Primer Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.o. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.º. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.o Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.º Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1o. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1º. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1o Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1º Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Corinti 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Corini 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Corint 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Corin 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Cor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Co 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("PRIMERO CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRIMER CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.O. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.º. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.O CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.º CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1O. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1º. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1O CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1º CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CORINTI 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CORINI 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CORINT 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CORIN 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 COR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CO 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1")
`
true
describe "Localized book Gal (es)", ->
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 (es)", ->
`
expect(p.parse("Galatas 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gálatas 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Galat 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gálat 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gál 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Ga 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gá 1:1").osis()).toEqual("Gal.1.1")
p.include_apocrypha(false)
expect(p.parse("GALATAS 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GÁLATAS 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GALAT 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GÁLAT 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GÁL 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GA 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GÁ 1:1").osis()).toEqual("Gal.1.1")
`
true
describe "Localized book Eph (es)", ->
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> <NAME> (es)", ->
`
expect(p.parse("Efesios 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efes 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efe 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("EFESIOS 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFES 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFE 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> (es)", ->
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> (es)", ->
`
expect(p.parse("Filipenses 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Filip 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Fili 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")
expect(p.parse("Flp 1:1").osis()).toEqual("Phil.1.1")
p.include_apocrypha(false)
expect(p.parse("FILIPENSES 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILIP 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILI 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")
expect(p.parse("FLP 1:1").osis()).toEqual("Phil.1.1")
`
true
describe "Localized book Col (es)", ->
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 (es)", ->
`
expect(p.parse("Colosenses 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Colos 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1")
p.include_apocrypha(false)
expect(p.parse("COLOSENSES 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("COLOS 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1")
`
true
describe "Localized book 2Thess (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Segundo Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Segundo Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Segundo Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Thess 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tes 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Ts 1:1").osis()).toEqual("2Thess.1.1")
p.include_apocrypha(false)
expect(p.parse("SEGUNDO TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("SEGUNDO TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("SEGUNDO TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("SEGUNDO TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 THESS 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TS 1:1").osis()).toEqual("2Thess.1.1")
`
true
describe "Localized book 1Thess (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primero Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primer Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primer Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primero Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primero Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primer Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primer Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Thess 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tes 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Ts 1:1").osis()).toEqual("1Thess.1.1")
p.include_apocrypha(false)
expect(p.parse("PRIMERO TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMERO TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMER TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMER TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMERO TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMERO TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMER TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMER TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 THESS 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TS 1:1").osis()).toEqual("1Thess.1.1")
`
true
describe "Localized book 2Tim (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.o. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.º. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.o Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.º Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2o. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2º. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2o Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2º Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Ti 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Tm 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("SEGUNDO TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.O. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.º. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.O TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.º TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2O. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2º. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2O TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2º TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1")
`
true
describe "Localized book 1Tim (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Primer Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.o. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.º. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.o Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.º Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1o. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1º. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1o Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1º Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Ti 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Tm 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("PRIMERO TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRIMER TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.O. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.º. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.O TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.º TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1O. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1º. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1O TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1º TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1")
`
true
describe "Localized book Titus (es)", ->
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 (es)", ->
`
expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Tito 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Tit 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Ti 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Tt 1:1").osis()).toEqual("Titus.1.1")
p.include_apocrypha(false)
expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TITO 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TIT 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TI 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TT 1:1").osis()).toEqual("Titus.1.1")
`
true
describe "Localized book Phlm (es)", ->
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 (es)", ->
`
expect(p.parse("Filemon 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Filemón 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Filem 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Flmn 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Flm 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Fmn 1:1").osis()).toEqual("Phlm.1.1")
p.include_apocrypha(false)
expect(p.parse("FILEMON 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FILEMÓN 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FILEM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FLMN 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FLM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FMN 1:1").osis()).toEqual("Phlm.1.1")
`
true
describe "Localized book Heb (es)", ->
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 (es)", ->
`
expect(p.parse("Hebeees 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeeos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeers 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeoes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeoos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeors 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heberes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heberos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heberrs 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboees 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboeos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboers 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebooes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebooos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboors 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebores 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboros 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heborrs 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrees 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebreos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrers 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebroes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebroos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrors 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrres 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrros 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrrrs 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebees 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebers 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebors 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebreo 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebres 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebros 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrrs 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrs 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebr 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("He 1:1").osis()).toEqual("Heb.1.1")
p.include_apocrypha(false)
expect(p.parse("HEBEEES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEEOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEERS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEOES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEOOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEORS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBERES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEROS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBERRS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOEES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOEOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOERS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOOES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOOOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOORS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBORES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOROS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBORRS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBREES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBREOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRERS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBROES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBROOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRORS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRRES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRROS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRRRS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBERS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBORS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBREO 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBROS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRRS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBR 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HE 1:1").osis()).toEqual("Heb.1.1")
`
true
describe "Localized book Jas (es)", ->
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 (es)", ->
`
expect(p.parse("Santiago 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Sant 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Stg 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("St 1:1").osis()).toEqual("Jas.1.1")
p.include_apocrypha(false)
expect(p.parse("SANTIAGO 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("SANT 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("STG 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("ST 1:1").osis()).toEqual("Jas.1.1")
`
true
describe "Localized book 2Pet (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.o. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.o San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2o. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Segundo Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2o San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.o. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.o Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2o. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2o Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Ped 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Pd 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Pe 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 P 1:1").osis()).toEqual("2Pet.1.1")
p.include_apocrypha(false)
expect(p.parse("SEGUNDO SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.O. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.O SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2O. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("SEGUNDO PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2O SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.O. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.O PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2O. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2O PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PED 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PD 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PE 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 P 1:1").osis()).toEqual("2Pet.1.1")
`
true
describe "Localized book 1Pet (es)", ->
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 (es)", ->
`
expect(p.parse("Primero San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Primer San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.o. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.o San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1o. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Primero Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1o San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Primer Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.o. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.o Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1o. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1o Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Ped 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Pd 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Pe 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 P 1:1").osis()).toEqual("1Pet.1.1")
p.include_apocrypha(false)
expect(p.parse("PRIMERO SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRIMER SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.O. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.O SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1O. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRIMERO PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1O SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRIMER PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.O. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.O PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1O. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1O PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PED 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PD 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PE 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 P 1:1").osis()).toEqual("1Pet.1.1")
`
true
describe "Localized book Jude (es)", ->
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 (es)", ->
`
expect(p.parse("San Judas 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Judas 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Jdas 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("Jd 1:1").osis()).toEqual("Jude.1.1")
p.include_apocrypha(false)
expect(p.parse("SAN JUDAS 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDAS 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JDAS 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("JD 1:1").osis()).toEqual("Jude.1.1")
`
true
describe "Localized book Tob (es)", ->
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 (es)", ->
`
expect(p.parse("Tobit 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobi 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobt 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tb 1:1").osis()).toEqual("Tob.1.1")
`
true
describe "Localized book Jdt (es)", ->
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 (es)", ->
`
expect(p.parse("Judit 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Jdit 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Judt 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1")
`
true
describe "Localized book Bar (es)", ->
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 (es)", ->
`
expect(p.parse("Baruc 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Ba 1:1").osis()).toEqual("Bar.1.1")
`
true
describe "Localized book Sus (es)", ->
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 (es)", ->
`
expect(p.parse("Susana 1:1").osis()).toEqual("Sus.1.1")
expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1")
`
true
describe "Localized book Hab,Hag (es)", ->
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,Hag (es)", ->
`
expect(p.parse("Ha 1:1").osis()).toEqual("Hab.1.1")
p.include_apocrypha(false)
expect(p.parse("HA 1:1").osis()).toEqual("Hab.1.1")
`
true
describe "Localized book Heb,Hab (es)", ->
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,Hab (es)", ->
`
expect(p.parse("Hb 1:1").osis()).toEqual("Heb.1.1")
p.include_apocrypha(false)
expect(p.parse("HB 1:1").osis()).toEqual("Heb.1.1")
`
true
describe "Localized book <NAME>,Job,<NAME>,Joel (es)", ->
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>,<NAME>,<NAME>,Jo<NAME> (es)", ->
`
expect(p.parse("Jo 1:1").osis()).toEqual("Jonah.1.1")
p.include_apocrypha(false)
expect(p.parse("JO 1:1").osis()).toEqual("Jonah.1.1")
`
true
describe "Localized book Jude,Judg (es)", ->
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,Judg (es)", ->
`
expect(p.parse("Ju 1:1").osis()).toEqual("Jude.1.1")
p.include_apocrypha(false)
expect(p.parse("JU 1:1").osis()).toEqual("Jude.1.1")
`
true
describe "Localized book <NAME>,<NAME>,<NAME> (es)", ->
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>,<NAME>,<NAME> (es)", ->
`
expect(p.parse("Ma 1:1").osis()).toEqual("Matt.1.1")
p.include_apocrypha(false)
expect(p.parse("MA 1:1").osis()).toEqual("Matt.1.1")
`
true
describe "Localized book Phil,Phlm (es)", ->
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,Phlm (es)", ->
`
expect(p.parse("Fil 1:1").osis()).toEqual("Phil.1.1")
p.include_apocrypha(false)
expect(p.parse("FIL 1:1").osis()).toEqual("Phil.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 ["es"]
it "should handle ranges (es)", ->
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"
expect(p.parse("Titus 1:1 al 2").osis()).toEqual "Titus.1.1-Titus.1.2"
expect(p.parse("Matt 1al2").osis()).toEqual "Matt.1-Matt.2"
expect(p.parse("Phlm 2 AL 3").osis()).toEqual "Phlm.1.2-Phlm.1.3"
it "should handle chapters (es)", ->
expect(p.parse("Titus 1:1, capítulos 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPÍTULOS 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, capitulos 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPITULOS 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, capítulo 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPÍTULO 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, capitulo 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPITULO 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, caps. 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPS. 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, caps 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPS 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, cap. 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAP. 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, cap 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAP 6").osis()).toEqual "Matt.3.4,Matt.6"
it "should handle verses (es)", ->
expect(p.parse("Exod 1:1 versículos 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERSÍCULOS 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 versiculos 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERSICULOS 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 versículo 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERSÍCULO 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 versiculo 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERSICULO 6").osis()).toEqual "Phlm.1.6"
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"
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"
expect(p.parse("Exod 1:1 ver. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VER. 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 ver 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VER 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vss. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VSS. 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vss 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VSS 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vs. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VS. 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vs 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VS 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vv. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VV. 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vv 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VV 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 v. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm V. 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 v 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm V 6").osis()).toEqual "Phlm.1.6"
it "should handle 'and' (es)", ->
expect(p.parse("Exod 1:1 y 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm 2 Y 6").osis()).toEqual "Phlm.1.2,Phlm.1.6"
it "should handle titles (es)", ->
expect(p.parse("Ps 3 subtítulo, 4:2, 5:subtítulo").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 SUBTÍTULO, 4:2, 5:SUBTÍTULO").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("Ps 3 subtitulo, 4:2, 5:subtitulo").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 SUBTITULO, 4:2, 5:SUBTITULO").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("Ps 3 título, 4:2, 5:título").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 TÍTULO, 4:2, 5:TÍTULO").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("Ps 3 titulo, 4:2, 5:titulo").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 TITULO, 4:2, 5:TITULO").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("Ps 3 tít, 4:2, 5:tít").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 TÍT, 4:2, 5:TÍT").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
it "should handle 'ff' (es)", ->
expect(p.parse("Rev 3y siguientes, 4:2y siguientes").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
expect(p.parse("REV 3 Y SIGUIENTES, 4:2 Y SIGUIENTES").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
expect(p.parse("Rev 3y sig, 4:2y sig").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
expect(p.parse("REV 3 Y SIG, 4:2 Y SIG").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
it "should handle translations (es)", ->
expect(p.parse("Lev 1 (DHH)").osis_and_translations()).toEqual [["Lev.1", "DHH"]]
expect(p.parse("lev 1 dhh").osis_and_translations()).toEqual [["Lev.1", "DHH"]]
expect(p.parse("Lev 1 (LBLA)").osis_and_translations()).toEqual [["Lev.1", "LBLA"]]
expect(p.parse("lev 1 lbla").osis_and_translations()).toEqual [["Lev.1", "LBLA"]]
expect(p.parse("Lev 1 (NBLH)").osis_and_translations()).toEqual [["Lev.1", "NBLH"]]
expect(p.parse("lev 1 nblh").osis_and_translations()).toEqual [["Lev.1", "NBLH"]]
expect(p.parse("Lev 1 (NTV)").osis_and_translations()).toEqual [["Lev.1", "NTV"]]
expect(p.parse("lev 1 ntv").osis_and_translations()).toEqual [["Lev.1", "NTV"]]
expect(p.parse("Lev 1 (NVI)").osis_and_translations()).toEqual [["Lev.1", "NVI"]]
expect(p.parse("lev 1 nvi").osis_and_translations()).toEqual [["Lev.1", "NVI"]]
expect(p.parse("Lev 1 (RVR)").osis_and_translations()).toEqual [["Lev.1", "RVR"]]
expect(p.parse("lev 1 rvr").osis_and_translations()).toEqual [["Lev.1", "RVR"]]
expect(p.parse("Lev 1 (RVR1960)").osis_and_translations()).toEqual [["Lev.1", "RVR1960"]]
expect(p.parse("lev 1 rvr1960").osis_and_translations()).toEqual [["Lev.1", "RVR1960"]]
expect(p.parse("Lev 1 (TLA)").osis_and_translations()).toEqual [["Lev.1", "TLA"]]
expect(p.parse("lev 1 tla").osis_and_translations()).toEqual [["Lev.1", "TLA"]]
it "should handle book ranges (es)", ->
p.set_options {book_alone_strategy: "full", book_range_strategy: "include"}
expect(p.parse("1.º á 3.º Jaan").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º al 3.º Jaan").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º á 3.º Jaun").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º al 3.º Jaun").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º á 3.º Juan").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º al 3.º Juan").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º á 3.º Juun").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º al 3.º Juun").osis()).toEqual "1John.1-3John.1"
it "should handle boundaries (es)", ->
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/es_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_PI","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 (es)", ->
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 (es)", ->
`
expect(p.parse("Genesis 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Génesis 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gén 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Ge 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gn 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gé 1:1").osis()).toEqual("Gen.1.1")
p.include_apocrypha(false)
expect(p.parse("GENESIS 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GÉNESIS 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GÉN 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GE 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GN 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GÉ 1:1").osis()).toEqual("Gen.1.1")
`
true
describe "Localized book Exod (es)", ->
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 (es)", ->
`
expect(p.parse("Exodo 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Éxodo 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Éxod 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exd 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exo 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Éxd 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Éxo 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Ex 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Éx 1:1").osis()).toEqual("Exod.1.1")
p.include_apocrypha(false)
expect(p.parse("EXODO 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("ÉXODO 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("ÉXOD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXO 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("ÉXD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("ÉXO 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EX 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("ÉX 1:1").osis()).toEqual("Exod.1.1")
`
true
describe "Localized book Bel (es)", ->
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 (es)", ->
`
expect(p.parse("Bel y el Serpiente 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bel y el Dragon 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bel y el Dragón 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1")
`
true
describe "Localized book Lev (es)", ->
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 (es)", ->
`
expect(p.parse("Levitico 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Levítico 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Lv 1:1").osis()).toEqual("Lev.1.1")
p.include_apocrypha(false)
expect(p.parse("LEVITICO 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEVÍTICO 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LV 1:1").osis()).toEqual("Lev.1.1")
`
true
describe "Localized book Num (es)", ->
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 (es)", ->
`
expect(p.parse("Numeros 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Números 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Núm 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Nm 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Nu 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Nú 1:1").osis()).toEqual("Num.1.1")
p.include_apocrypha(false)
expect(p.parse("NUMEROS 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NÚMEROS 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NÚM 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NM 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NU 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NÚ 1:1").osis()).toEqual("Num.1.1")
`
true
describe "Localized book Sir (es)", ->
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 (es)", ->
`
expect(p.parse("Eclesiastico 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Eclesiástico 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Siracides 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sirácides 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Siracida 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sirácida 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Ecclus 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sirac 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sirác 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Si 1:1").osis()).toEqual("Sir.1.1")
`
true
describe "Localized book Wis (es)", ->
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 (es)", ->
`
expect(p.parse("Sabiduria 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Sabiduría 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Sab 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Sb 1:1").osis()).toEqual("Wis.1.1")
`
true
describe "Localized book Lam (es)", ->
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 (es)", ->
`
expect(p.parse("Lamentaciones 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lamintaciones 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lamentacione 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lamintacione 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("La 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lm 1:1").osis()).toEqual("Lam.1.1")
p.include_apocrypha(false)
expect(p.parse("LAMENTACIONES 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAMINTACIONES 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAMENTACIONE 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAMINTACIONE 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LA 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LM 1:1").osis()).toEqual("Lam.1.1")
`
true
describe "Localized book EpJer (es)", ->
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 (es)", ->
`
expect(p.parse("La Carta de Jeremias 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("La Carta de JerPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("Carta PI:NAME:<NAME>END_PI JerPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("Carta de JerPI:NAME:<NAME>END_PIías 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("Carta JerPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("Carta JerPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("Carta Jer 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1")
`
true
describe "Localized book Rev (es)", ->
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 (es)", ->
`
expect(p.parse("El Apocalipsis 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Apocalipsis 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Apoc 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Ap 1:1").osis()).toEqual("Rev.1.1")
p.include_apocrypha(false)
expect(p.parse("EL APOCALIPSIS 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("APOCALIPSIS 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("APOC 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("AP 1:1").osis()).toEqual("Rev.1.1")
`
true
describe "Localized book PrMan (es)", ->
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 (es)", ->
`
expect(p.parse("La Oracion de Manases 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("La Oracion de Manasés 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("La Oración de Manases 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("La Oración de Manasés 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Oracion de Manases 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Oracion de Manasés 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Oración de Manases 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Oración de Manasés 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Or. Man 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("Or Man 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1")
`
true
describe "Localized book Deut (es)", ->
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 (es)", ->
`
expect(p.parse("Deuteronomio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deutoronomio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Dueteronomio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deuteronmio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deutoronmio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deutronomio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deutronmio 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deu 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Dt 1:1").osis()).toEqual("Deut.1.1")
p.include_apocrypha(false)
expect(p.parse("DEUTERONOMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTORONOMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DUETERONOMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTERONMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTORONMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTRONOMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTRONMIO 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEU 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DT 1:1").osis()).toEqual("Deut.1.1")
`
true
describe "Localized book PI:NAME:<NAME>END_PI (es)", ->
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 (es)", ->
`
expect(p.parse("Josue 1:1").osis()).toEqual("PI:NAME:<NAME>END_PI.1.1")
expect(p.parse("Josué 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")
p.include_apocrypha(false)
expect(p.parse("JOSUE 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("JOSUÉ 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")
`
true
describe "Localized book Judg (es)", ->
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 (es)", ->
`
expect(p.parse("Jueces 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Juec 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Jue 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Jc 1:1").osis()).toEqual("Judg.1.1")
p.include_apocrypha(false)
expect(p.parse("JUECES 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JUEC 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JUE 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JC 1:1").osis()).toEqual("Judg.1.1")
`
true
describe "Localized book Ruth (es)", ->
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 (es)", ->
`
expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Rut 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Rt 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Ru 1:1").osis()).toEqual("Ruth.1.1")
p.include_apocrypha(false)
expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RUT 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RT 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RU 1:1").osis()).toEqual("Ruth.1.1")
`
true
describe "Localized book 1Esd (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("Primer Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1.o. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1.º. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1.o Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1.º Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1o. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1º. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1o Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1º Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I. Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I Esdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Esdr 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Esd 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1")
`
true
describe "Localized book 2Esd (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2.o. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2.º. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2.o Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2.º Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2o. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2º. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2. Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2o Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2º Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Esdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Esdr 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Esd 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1")
`
true
describe "Localized book Isa (es)", ->
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 (es)", ->
`
expect(p.parse("Isaias 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Isaías 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Is 1:1").osis()).toEqual("Isa.1.1")
p.include_apocrypha(false)
expect(p.parse("ISAIAS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("ISAÍAS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IS 1:1").osis()).toEqual("Isa.1.1")
`
true
describe "Localized book 2Sam (es)", ->
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 (es)", ->
`
expect(p.parse("PI:NAME:<NAME>END_PIundo PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.o. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.º. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.o PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.º PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2o. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2º. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2o PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2º PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SamPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Sa 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Sm 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 S 1:1").osis()).toEqual("2Sam.1.1")
p.include_apocrypha(false)
expect(p.parse("SEGUNDO SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.O. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.º. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.O SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2.º SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2O. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2º. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2O SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2º SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 S 1:1").osis()).toEqual("2Sam.1.1")
`
true
describe "Localized book 1Sam (es)", ->
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 (es)", ->
`
expect(p.parse("Primero PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Primer PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.o. 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("1.o 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("1o. 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("1. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1o 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 SamPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I SamPI: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("1 Sa 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 Sm 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 S 1:1").osis()).toEqual("1Sam.1.1")
p.include_apocrypha(false)
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.O. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.º. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.O SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1.º SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1O. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1º. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1O SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1º SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 S 1:1").osis()).toEqual("1Sam.1.1")
`
true
describe "Localized book 2Kgs (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.o. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.º. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.o Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.º Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2o. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2º. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2o Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2º Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Reyes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Rees 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Reye 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Reys 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Ryes 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Ree 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Res 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Rey 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Rye 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Rys 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Re 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Rs 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Ry 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 R 1:1").osis()).toEqual("2Kgs.1.1")
p.include_apocrypha(false)
expect(p.parse("SEGUNDO REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.O. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.º. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.O REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2.º REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2O. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2º. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2O REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2º REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REYE 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REYS 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RYES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REE 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RES 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 REY 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RYE 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RYS 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RE 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RS 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 RY 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 R 1:1").osis()).toEqual("2Kgs.1.1")
`
true
describe "Localized book 1Kgs (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Primer Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.o. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.º. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.o Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.º Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1o. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1º. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1o Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1º Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Reyes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Rees 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Reye 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Reys 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Ryes 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Ree 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Res 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Rey 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Rye 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Rys 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Re 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Rs 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Ry 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 R 1:1").osis()).toEqual("1Kgs.1.1")
p.include_apocrypha(false)
expect(p.parse("PRIMERO REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRIMER REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.O. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.º. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.O REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1.º REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1O. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1º. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1O REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1º REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I REYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REYE 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REYS 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RYES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REE 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RES 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 REY 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RYE 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RYS 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RE 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RS 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 RY 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 R 1:1").osis()).toEqual("1Kgs.1.1")
`
true
describe "Localized book 2Chr (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Segundo Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.o. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.o. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.o Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.o Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2o. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2o. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2o Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2o Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Cronicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Crónicas 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Cron 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Crón 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Cro 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Cró 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Cr 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("SEGUNDO CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("SEGUNDO CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.O. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.O. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.O CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.O CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2.º CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2O. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2O. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2O CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2O CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2º CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRONICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRÓNICAS 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRÓN 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRO 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CRÓ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 CR 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1")
`
true
describe "Localized book 1Chr (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Primero Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Primer Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Primer Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.o. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.o. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.o Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.o Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1o. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1o. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1o Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1o Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Cronicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Crónicas 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Cron 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Crón 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Cro 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Cró 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Cr 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("PRIMERO CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRIMERO CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRIMER CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRIMER CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.O. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.O. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.O CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.O CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1.º CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1O. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1O. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1O CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1O CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1º CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I CRONICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I CRÓNICAS 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRÓN 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRO 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CRÓ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 CR 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1")
`
true
describe "Localized book Ezra (es)", ->
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 (es)", ->
`
expect(p.parse("Esdras 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Esdr 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Esd 1:1").osis()).toEqual("Ezra.1.1")
p.include_apocrypha(false)
expect(p.parse("ESDRAS 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("ESDR 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("ESD 1:1").osis()).toEqual("Ezra.1.1")
`
true
describe "Localized book Neh (es)", ->
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 (es)", ->
`
expect(p.parse("Nehemias 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemías 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Ne 1:1").osis()).toEqual("Neh.1.1")
p.include_apocrypha(false)
expect(p.parse("NEHEMIAS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMÍAS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NE 1:1").osis()).toEqual("Neh.1.1")
`
true
describe "Localized book GkEsth (es)", ->
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 (es)", ->
`
expect(p.parse("Ester (Griego) 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester (griego) 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester Griego 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester griego 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Est Gr 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1")
`
true
describe "Localized book Esth (es)", ->
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 (es)", ->
`
expect(p.parse("Ester 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")
expect(p.parse("Es 1:1").osis()).toEqual("Esth.1.1")
p.include_apocrypha(false)
expect(p.parse("ESTER 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")
expect(p.parse("ES 1:1").osis()).toEqual("Esth.1.1")
`
true
describe "Localized book Job (es)", ->
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 (es)", ->
`
expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("Jb 1:1").osis()).toEqual("Job.1.1")
p.include_apocrypha(false)
expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("JB 1:1").osis()).toEqual("Job.1.1")
`
true
describe "Localized book Ps (es)", ->
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 (es)", ->
`
expect(p.parse("Salmos 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Salmo 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Salm 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Sal 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")
expect(p.parse("Sl 1:1").osis()).toEqual("Ps.1.1")
p.include_apocrypha(false)
expect(p.parse("SALMOS 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("SALMO 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("SALM 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("SAL 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")
expect(p.parse("SL 1:1").osis()).toEqual("Ps.1.1")
`
true
describe "Localized book PrAzar (es)", ->
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 (es)", ->
`
expect(p.parse("Cantico de Azarias 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Cantico de Azarías 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Cántico de Azarias 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Cántico de Azarías 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Oracion de Azarias 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Oracion de Azarías 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Oración de Azarias 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Oración de Azarías 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Azarias 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Azarías 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Or Azar 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Or Az 1:1").osis()).toEqual("PrAzar.1.1")
`
true
describe "Localized book Prov (es)", ->
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 (es)", ->
`
expect(p.parse("Probverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Porverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Preverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Proberbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Proverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Poverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Preverbio 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Provebios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Proverbio 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prverbios 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prverbio 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prvbos 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prvbo 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prvbs 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prvb 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Pro 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prv 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Pr 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Pv 1:1").osis()).toEqual("Prov.1.1")
p.include_apocrypha(false)
expect(p.parse("PROBVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PORVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PREVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROBERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("POVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PREVERBIO 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROVEBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROVERBIO 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVERBIOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVERBIO 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVBOS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVBO 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVBS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRVB 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRO 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRV 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PR 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PV 1:1").osis()).toEqual("Prov.1.1")
`
true
describe "Localized book Eccl (es)", ->
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 (es)", ->
`
expect(p.parse("Ecclesiastices 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiasticés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiasties 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiastiés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiastices 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiasticés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiasties 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiastiés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessaité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclessiité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiastes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiastés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiistes 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiistés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesaité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecclesiité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiaste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiasté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiates 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiatés 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiiste 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiisté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiites 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiités 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessaité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclessiité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesaité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiate 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiaté 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiite 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eclesiité 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eccles 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecles 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecc 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ecl 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Ec 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Qo 1:1").osis()).toEqual("Eccl.1.1")
p.include_apocrypha(false)
expect(p.parse("ECCLESIASTICES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTICÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTIES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTIÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTICES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTICÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTIES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTIÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSAITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESSIITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIISTES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIISTÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESAITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLESIITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIASTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIATES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIATÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIISTE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIISTÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIITES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIITÉS 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSAITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESSIITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESAITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIATE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIATÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIITE 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLESIITÉ 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCLES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECLES 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECC 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECL 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("EC 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("QO 1:1").osis()).toEqual("Eccl.1.1")
`
true
describe "Localized book SgThree (es)", ->
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 (es)", ->
`
expect(p.parse("El Canto de los Tres Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los Tres Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los Tres Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los Tres Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los Tres Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los Tres Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los Tres Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Canto de los 3 Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("El Himno de los 3 Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jovenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jóvenes Hebreos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jovenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jovenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jóvenes Judios 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jóvenes Judíos 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los Tres Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los Tres Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Canto de los 3 Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Himno de los 3 Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tres Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tres Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("3 Jovenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("3 Jóvenes 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Ct 3 Jo 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Ct 3 Jó 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1")
`
true
describe "Localized book Song (es)", ->
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 (es)", ->
`
expect(p.parse("El Cantar de los Cantares 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Cantare de los Cantares 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Cantar de los Cantares 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Cantares 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Cant 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Can 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Cnt 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Ct 1:1").osis()).toEqual("Song.1.1")
p.include_apocrypha(false)
expect(p.parse("EL CANTAR DE LOS CANTARES 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CANTARE DE LOS CANTARES 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CANTAR DE LOS CANTARES 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CANTARES 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CANT 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CAN 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CNT 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("CT 1:1").osis()).toEqual("Song.1.1")
`
true
describe "Localized book Jer (es)", ->
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 (es)", ->
`
expect(p.parse("Jeremias 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jeremías 1:1").osis()).toEqual("Jer.1.1")
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("Jere 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jr 1:1").osis()).toEqual("Jer.1.1")
p.include_apocrypha(false)
expect(p.parse("JEREMIAS 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMÍAS 1:1").osis()).toEqual("Jer.1.1")
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("JERE 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JR 1:1").osis()).toEqual("Jer.1.1")
`
true
describe "Localized book Ezek (es)", ->
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 (es)", ->
`
expect(p.parse("Ezeequiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezeiquiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziequiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziiquiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezeequel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezeiquel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezequial 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezequiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziequel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziiquel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziquiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezequel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eziquel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezequ 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezeq 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Eze 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezq 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ez 1:1").osis()).toEqual("Ezek.1.1")
p.include_apocrypha(false)
expect(p.parse("EZEEQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEIQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIEQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIIQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEEQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEIQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEQUIAL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIEQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIIQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIQUIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZIQUEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEQU 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEQ 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZE 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZQ 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZ 1:1").osis()).toEqual("Ezek.1.1")
`
true
describe "Localized book PI:NAME:<NAME>END_PI (es)", ->
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 (es)", ->
`
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Da 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Dl 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Dn 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 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DA 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DL 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DN 1:1").osis()).toEqual("Dan.1.1")
`
true
describe "Localized book Hos (es)", ->
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 (es)", ->
`
expect(p.parse("Oseas 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Os 1:1").osis()).toEqual("Hos.1.1")
p.include_apocrypha(false)
expect(p.parse("OSEAS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("OS 1:1").osis()).toEqual("Hos.1.1")
`
true
describe "Localized book Joel (es)", ->
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 (es)", ->
`
expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("Joe 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("JOE 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("JL 1:1").osis()).toEqual("Joel.1.1")
`
true
describe "Localized book Amos (es)", ->
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 (es)", ->
`
expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Amós 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Amo 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Ams 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Amó 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ÓS 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AMO 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AMS 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AMÓ 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AM 1:1").osis()).toEqual("Amos.1.1")
`
true
describe "Localized book Obad (es)", ->
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 (es)", ->
`
expect(p.parse("Abdias 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdías 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abd 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Ab 1:1").osis()).toEqual("Obad.1.1")
p.include_apocrypha(false)
expect(p.parse("ABDIAS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDÍAS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABD 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("AB 1:1").osis()).toEqual("Obad.1.1")
`
true
describe "Localized book PI:NAME:<NAME>END_PIah (es)", ->
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_PIah (es)", ->
`
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jonas 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("PI:NAME:<NAME>END_PIás 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jns 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jon 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("JONÁS 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JNS 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JON 1:1").osis()).toEqual("Jonah.1.1")
`
true
describe "Localized book PI:NAME:<NAME>END_PIic (es)", ->
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 (es)", ->
`
expect(p.parse("Miqueas 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Miq 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mi 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mq 1:1").osis()).toEqual("Mic.1.1")
p.include_apocrypha(false)
expect(p.parse("MIQUEAS 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MIQ 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MI 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MQ 1:1").osis()).toEqual("Mic.1.1")
`
true
describe "Localized book Nah (es)", ->
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 (es)", ->
`
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("Nahu 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Nahú 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Na 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Nh 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("NAHU 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NAHÚ 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NA 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NH 1:1").osis()).toEqual("Nah.1.1")
`
true
describe "Localized book Hab (es)", ->
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 (es)", ->
`
expect(p.parse("Habbacac 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Habbacuc 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Habacac 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Habacuc 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Habc 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("HABBACAC 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HABBACUC 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HABACAC 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HABACUC 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HABC 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1")
`
true
describe "Localized book Zeph (es)", ->
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 (es)", ->
`
expect(p.parse("Sofonias 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofonías 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sof 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sf 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("So 1:1").osis()).toEqual("Zeph.1.1")
p.include_apocrypha(false)
expect(p.parse("SOFONIAS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONÍAS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOF 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SF 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SO 1:1").osis()).toEqual("Zeph.1.1")
`
true
describe "Localized book Hag (es)", ->
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 (es)", ->
`
expect(p.parse("Haggeo 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Hageo 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Ageo 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Ag 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Hg 1:1").osis()).toEqual("Hag.1.1")
p.include_apocrypha(false)
expect(p.parse("HAGGEO 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("HAGEO 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("AGEO 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("AG 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("HG 1:1").osis()).toEqual("Hag.1.1")
`
true
describe "Localized book Zech (es)", ->
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 (es)", ->
`
expect(p.parse("Zacarias 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacarías 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacar 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zac 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Za 1:1").osis()).toEqual("Zech.1.1")
p.include_apocrypha(false)
expect(p.parse("ZACARIAS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACARÍAS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACAR 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZAC 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZA 1:1").osis()).toEqual("Zech.1.1")
`
true
describe "Localized book Mal (es)", ->
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 (es)", ->
`
expect(p.parse("Malaquias 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Malaquías 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Malaqu 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Mala 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Ml 1:1").osis()).toEqual("Mal.1.1")
p.include_apocrypha(false)
expect(p.parse("MALAQUIAS 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALAQUÍAS 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALAQU 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALA 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("ML 1:1").osis()).toEqual("Mal.1.1")
`
true
describe "Localized book PI:NAME:<NAME>END_PIatt (es)", ->
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 (es)", ->
`
expect(p.parse("El Evangelio de Mateo 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Evangelio de Mateo 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("San Mateo 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Mateo 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Mat 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Mt 1:1").osis()).toEqual("Matt.1.1")
p.include_apocrypha(false)
expect(p.parse("EL EVANGELIO DE MATEO 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("EVANGELIO DE MATEO 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("SAN MATEO 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATEO 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MAT 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MT 1:1").osis()).toEqual("Matt.1.1")
`
true
describe "Localized book 2Macc (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Segundo Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabbeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabbeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabbeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabeeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.o Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2.º Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabbeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabeeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabeos 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Maccabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2o Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2º Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macabeo 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Macc 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Mac 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Mc 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 M 1:1").osis()).toEqual("2Macc.1.1")
`
true
describe "Localized book 3Macc (es)", ->
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 (es)", ->
`
expect(p.parse("Tercero Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercero Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tercer Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabbeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabbeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabbeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabeeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.o Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3.º Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabbeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabeeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabeos 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Maccabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3o Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3º Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macabeo 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Macc 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Mac 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Mc 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 M 1:1").osis()).toEqual("3Macc.1.1")
`
true
describe "Localized book 4Macc (es)", ->
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 (es)", ->
`
expect(p.parse("Cuarto Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Cuarto Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabbeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabbeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabbeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabeeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.o Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4.º Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabbeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabeeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabeos 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Maccabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4o Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4º Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macabeo 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Macc 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Mac 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Mc 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 M 1:1").osis()).toEqual("4Macc.1.1")
`
true
describe "Localized book 1Macc (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primero Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Primer Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabbeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.o Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1.º Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabbeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabbeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabeeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1o Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1º Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabbeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabeeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabeos 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Maccabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Macabeo 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Macc 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Mac 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Mc 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 M 1:1").osis()).toEqual("1Macc.1.1")
`
true
describe "Localized book Mark (es)", ->
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 (es)", ->
`
expect(p.parse("El Evangelio de Marcos 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Evangelio de Marcos 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("San Marcos 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Marcos 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mrcos 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Marc 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mar 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mrc 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mc 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mr 1:1").osis()).toEqual("Mark.1.1")
p.include_apocrypha(false)
expect(p.parse("EL EVANGELIO DE MARCOS 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("EVANGELIO DE MARCOS 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("SAN MARCOS 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARCOS 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MRCOS 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARC 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MAR 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MRC 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MC 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MR 1:1").osis()).toEqual("Mark.1.1")
`
true
describe "Localized book Luke (es)", ->
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 (es)", ->
`
expect(p.parse("El Evangelio de Lucas 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Evangelio de Lucas 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("San Lucas 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lucas 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Luc 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lc 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lu 1:1").osis()).toEqual("Luke.1.1")
p.include_apocrypha(false)
expect(p.parse("EL EVANGELIO DE LUCAS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("EVANGELIO DE LUCAS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("SAN LUCAS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUCAS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUC 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LC 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LU 1:1").osis()).toEqual("Luke.1.1")
`
true
describe "Localized book 1John (es)", ->
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 (es)", ->
`
expect(p.parse("Primero San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primero Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Primer Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I San Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I San Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I San Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I San Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.o Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1o Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Jaan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Jaun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Juan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Juun 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Jn 1:1").osis()).toEqual("1John.1.1")
p.include_apocrypha(false)
expect(p.parse("PRIMERO SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMERO JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRIMER JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I SAN JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I SAN JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I SAN JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I SAN JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.O JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1.º JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1O JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1º JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JAAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JAUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JUAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JUUN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JN 1:1").osis()).toEqual("1John.1.1")
`
true
describe "Localized book 2John (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Segundo Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 San Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 San Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 San Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 San Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.o Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2o Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Jaan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Jaun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Juan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Juun 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Jn 1:1").osis()).toEqual("2John.1.1")
p.include_apocrypha(false)
expect(p.parse("SEGUNDO SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("SEGUNDO JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 SAN JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 SAN JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 SAN JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 SAN JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.O JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2.º JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2O JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2º JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JAAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JAUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JUAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JUUN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JN 1:1").osis()).toEqual("2John.1.1")
`
true
describe "Localized book 3John (es)", ->
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 (es)", ->
`
expect(p.parse("Tercero San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercero Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tercer Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 San Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 San Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 San Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 San Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.o Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3o Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Jaan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Jaun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Juan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Juun 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Jn 1:1").osis()).toEqual("3John.1.1")
p.include_apocrypha(false)
expect(p.parse("TERCERO SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCERO JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TERCER JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 SAN JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 SAN JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 SAN JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 SAN JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.O JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3.º JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3O JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3º JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JAAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JAUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JUAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JUUN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JN 1:1").osis()).toEqual("3John.1.1")
`
true
describe "Localized book PI:NAME:<NAME>END_PI (es)", ->
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 (es)", ->
`
expect(p.parse("El Evangelio de Jaan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("El Evangelio de Jaun 1:1").osis()).toEqual("John.1.1")
expect(p.parse("El Evangelio de Juan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("El Evangelio de Juun 1:1").osis()).toEqual("John.1.1")
expect(p.parse("San Juan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Jaan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Jaun 1:1").osis()).toEqual("John.1.1")
expect(p.parse("John 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Juan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Juun 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Jn 1:1").osis()).toEqual("John.1.1")
p.include_apocrypha(false)
expect(p.parse("EL EVANGELIO DE JAAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("EL EVANGELIO DE JAUN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("EL EVANGELIO DE JUAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("EL EVANGELIO DE JUUN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("SAN JUAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JAAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JAUN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JUAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JUUN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JN 1:1").osis()).toEqual("John.1.1")
`
true
describe "Localized book Acts (es)", ->
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 (es)", ->
`
expect(p.parse("Los Hechos de los Apostoles 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Los Hechos de los Apóstoles 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hechos de los Apostoles 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hechos de los Apóstoles 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Los Hechos 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hechos 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hech 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hch 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hec 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Hc 1:1").osis()).toEqual("Acts.1.1")
p.include_apocrypha(false)
expect(p.parse("LOS HECHOS DE LOS APOSTOLES 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("LOS HECHOS DE LOS APÓSTOLES 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HECHOS DE LOS APOSTOLES 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HECHOS DE LOS APÓSTOLES 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("LOS HECHOS 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HECHOS 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HECH 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HCH 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HEC 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("HC 1:1").osis()).toEqual("Acts.1.1")
`
true
describe "Localized book Rom (es)", ->
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 (es)", ->
`
expect(p.parse("Romanos 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Romano 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rmns 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Roms 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rmn 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rms 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Ros 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rm 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Ro 1:1").osis()).toEqual("Rom.1.1")
p.include_apocrypha(false)
expect(p.parse("ROMANOS 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROMANO 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RMNS 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROMS 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RMN 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RMS 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROS 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RO 1:1").osis()).toEqual("Rom.1.1")
`
true
describe "Localized book 2Cor (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.o. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.º. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.o Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.º Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2o. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2º. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2o Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2º Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Corintios 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Corinti 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Corini 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Corint 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Corin 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Cor 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Co 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("SEGUNDO CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.O. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.º. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.O CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.º CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2O. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2º. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2O CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2º CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CORINTIOS 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CORINTI 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CORINI 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CORINT 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CORIN 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 COR 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 CO 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1")
`
true
describe "Localized book 1Cor (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Primer Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.o. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.º. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.o Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.º Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1o. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1º. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1o Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1º Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I Corintios 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Corinti 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Corini 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Corint 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Corin 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Cor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Co 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("PRIMERO CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRIMER CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.O. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.º. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.O CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.º CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1O. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1º. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1O CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1º CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I CORINTIOS 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CORINTI 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CORINI 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CORINT 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CORIN 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 COR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 CO 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1")
`
true
describe "Localized book Gal (es)", ->
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 (es)", ->
`
expect(p.parse("Galatas 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gálatas 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Galat 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gálat 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gál 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Ga 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gá 1:1").osis()).toEqual("Gal.1.1")
p.include_apocrypha(false)
expect(p.parse("GALATAS 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GÁLATAS 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GALAT 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GÁLAT 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GÁL 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GA 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GÁ 1:1").osis()).toEqual("Gal.1.1")
`
true
describe "Localized book Eph (es)", ->
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 PI:NAME:<NAME>END_PI (es)", ->
`
expect(p.parse("Efesios 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efes 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efe 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("EFESIOS 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFES 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFE 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 (es)", ->
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 (es)", ->
`
expect(p.parse("Filipenses 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Filip 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Fili 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")
expect(p.parse("Flp 1:1").osis()).toEqual("Phil.1.1")
p.include_apocrypha(false)
expect(p.parse("FILIPENSES 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILIP 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILI 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")
expect(p.parse("FLP 1:1").osis()).toEqual("Phil.1.1")
`
true
describe "Localized book Col (es)", ->
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 (es)", ->
`
expect(p.parse("Colosenses 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Colos 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1")
p.include_apocrypha(false)
expect(p.parse("COLOSENSES 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("COLOS 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1")
`
true
describe "Localized book 2Thess (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Segundo Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Segundo Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Segundo Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.o Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonicenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonisenses 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2o Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonicense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonisense 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Thess 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tes 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Ts 1:1").osis()).toEqual("2Thess.1.1")
p.include_apocrypha(false)
expect(p.parse("SEGUNDO TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("SEGUNDO TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("SEGUNDO TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("SEGUNDO TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.O TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2.º TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONICENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONISENSES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2O TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2º TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONICENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONISENSE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 THESS 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TES 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TS 1:1").osis()).toEqual("2Thess.1.1")
`
true
describe "Localized book 1Thess (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primero Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primer Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primer Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primero Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primero Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primer Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Primer Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.o Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1o Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonicenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonisenses 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonicense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonisense 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Thess 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tes 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Ts 1:1").osis()).toEqual("1Thess.1.1")
p.include_apocrypha(false)
expect(p.parse("PRIMERO TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMERO TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMER TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMER TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMERO TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMERO TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMER TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRIMER TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.O TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1.º TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1O TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1º TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONICENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONISENSES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONICENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONISENSE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 THESS 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TES 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TS 1:1").osis()).toEqual("1Thess.1.1")
`
true
describe "Localized book 2Tim (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.o. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.º. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.o Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.º Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2o. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2º. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2o Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2º Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Timoteo 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Ti 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Tm 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("SEGUNDO TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.O. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.º. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.O TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2.º TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2O. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2º. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2O TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2º TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIMOTEO 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1")
`
true
describe "Localized book 1Tim (es)", ->
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 (es)", ->
`
expect(p.parse("Primero Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Primer Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.o. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.º. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.o Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.º Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1o. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1º. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1o Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1º Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Timoteo 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Ti 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Tm 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("PRIMERO TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRIMER TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.O. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.º. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.O TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1.º TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1O. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1º. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1O TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1º TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TIMOTEO 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1")
`
true
describe "Localized book Titus (es)", ->
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 (es)", ->
`
expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Tito 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Tit 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Ti 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Tt 1:1").osis()).toEqual("Titus.1.1")
p.include_apocrypha(false)
expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TITO 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TIT 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TI 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TT 1:1").osis()).toEqual("Titus.1.1")
`
true
describe "Localized book Phlm (es)", ->
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 (es)", ->
`
expect(p.parse("Filemon 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Filemón 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Filem 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Flmn 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Flm 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Fmn 1:1").osis()).toEqual("Phlm.1.1")
p.include_apocrypha(false)
expect(p.parse("FILEMON 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FILEMÓN 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FILEM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FLMN 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FLM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FMN 1:1").osis()).toEqual("Phlm.1.1")
`
true
describe "Localized book Heb (es)", ->
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 (es)", ->
`
expect(p.parse("Hebeees 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeeos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeers 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeoes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeoos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeors 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heberes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heberos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heberrs 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboees 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboeos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboers 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebooes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebooos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboors 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebores 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboros 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heborrs 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrees 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebreos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrers 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebroes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebroos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrors 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrres 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrros 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrrrs 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebees 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebeos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebers 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heboos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebors 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebreo 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebres 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebros 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrrs 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebes 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebos 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrs 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebr 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("He 1:1").osis()).toEqual("Heb.1.1")
p.include_apocrypha(false)
expect(p.parse("HEBEEES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEEOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEERS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEOES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEOOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEORS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBERES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEROS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBERRS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOEES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOEOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOERS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOOES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOOOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOORS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBORES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOROS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBORRS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBREES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBREOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRERS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBROES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBROOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRORS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRRES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRROS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRRRS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBEOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBERS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBORS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBREO 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBROS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRRS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBES 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBOS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBRS 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBR 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HE 1:1").osis()).toEqual("Heb.1.1")
`
true
describe "Localized book Jas (es)", ->
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 (es)", ->
`
expect(p.parse("Santiago 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Sant 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Stg 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("St 1:1").osis()).toEqual("Jas.1.1")
p.include_apocrypha(false)
expect(p.parse("SANTIAGO 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("SANT 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("STG 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("ST 1:1").osis()).toEqual("Jas.1.1")
`
true
describe "Localized book 2Pet (es)", ->
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 (es)", ->
`
expect(p.parse("Segundo San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.o. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.o San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2o. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Segundo Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2o San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 San Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.o. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.o Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2o. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2o Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Pedro 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Ped 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Pd 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Pe 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 P 1:1").osis()).toEqual("2Pet.1.1")
p.include_apocrypha(false)
expect(p.parse("SEGUNDO SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.O. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.O SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2O. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("SEGUNDO PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2O SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 SAN PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.O. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.O PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2.º PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2O. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2O PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2º PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PEDRO 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PED 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PD 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PE 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 P 1:1").osis()).toEqual("2Pet.1.1")
`
true
describe "Localized book 1Pet (es)", ->
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 (es)", ->
`
expect(p.parse("Primero San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Primer San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.o. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.o San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1o. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Primero Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1o San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Primer Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I San Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.o. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.o Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1o. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1o Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Pedro 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Ped 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Pd 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Pe 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 P 1:1").osis()).toEqual("1Pet.1.1")
p.include_apocrypha(false)
expect(p.parse("PRIMERO SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRIMER SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.O. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.O SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1O. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRIMERO PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1O SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRIMER PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I SAN PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.O. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.O PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1.º PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1O. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1O PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1º PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PEDRO 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PED 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PD 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PE 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 P 1:1").osis()).toEqual("1Pet.1.1")
`
true
describe "Localized book Jude (es)", ->
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 (es)", ->
`
expect(p.parse("San Judas 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Judas 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Jdas 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("Jd 1:1").osis()).toEqual("Jude.1.1")
p.include_apocrypha(false)
expect(p.parse("SAN JUDAS 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDAS 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JDAS 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("JD 1:1").osis()).toEqual("Jude.1.1")
`
true
describe "Localized book Tob (es)", ->
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 (es)", ->
`
expect(p.parse("Tobit 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobi 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobt 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tb 1:1").osis()).toEqual("Tob.1.1")
`
true
describe "Localized book Jdt (es)", ->
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 (es)", ->
`
expect(p.parse("Judit 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Jdit 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Judt 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1")
`
true
describe "Localized book Bar (es)", ->
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 (es)", ->
`
expect(p.parse("Baruc 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Ba 1:1").osis()).toEqual("Bar.1.1")
`
true
describe "Localized book Sus (es)", ->
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 (es)", ->
`
expect(p.parse("Susana 1:1").osis()).toEqual("Sus.1.1")
expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1")
`
true
describe "Localized book Hab,Hag (es)", ->
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,Hag (es)", ->
`
expect(p.parse("Ha 1:1").osis()).toEqual("Hab.1.1")
p.include_apocrypha(false)
expect(p.parse("HA 1:1").osis()).toEqual("Hab.1.1")
`
true
describe "Localized book Heb,Hab (es)", ->
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,Hab (es)", ->
`
expect(p.parse("Hb 1:1").osis()).toEqual("Heb.1.1")
p.include_apocrypha(false)
expect(p.parse("HB 1:1").osis()).toEqual("Heb.1.1")
`
true
describe "Localized book PI:NAME:<NAME>END_PI,Job,PI:NAME:<NAME>END_PI,Joel (es)", ->
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,PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI,JoPI:NAME:<NAME>END_PI (es)", ->
`
expect(p.parse("Jo 1:1").osis()).toEqual("Jonah.1.1")
p.include_apocrypha(false)
expect(p.parse("JO 1:1").osis()).toEqual("Jonah.1.1")
`
true
describe "Localized book Jude,Judg (es)", ->
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,Judg (es)", ->
`
expect(p.parse("Ju 1:1").osis()).toEqual("Jude.1.1")
p.include_apocrypha(false)
expect(p.parse("JU 1:1").osis()).toEqual("Jude.1.1")
`
true
describe "Localized book PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI (es)", ->
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,PI:NAME:<NAME>END_PI,PI:NAME:<NAME>END_PI (es)", ->
`
expect(p.parse("Ma 1:1").osis()).toEqual("Matt.1.1")
p.include_apocrypha(false)
expect(p.parse("MA 1:1").osis()).toEqual("Matt.1.1")
`
true
describe "Localized book Phil,Phlm (es)", ->
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,Phlm (es)", ->
`
expect(p.parse("Fil 1:1").osis()).toEqual("Phil.1.1")
p.include_apocrypha(false)
expect(p.parse("FIL 1:1").osis()).toEqual("Phil.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 ["es"]
it "should handle ranges (es)", ->
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"
expect(p.parse("Titus 1:1 al 2").osis()).toEqual "Titus.1.1-Titus.1.2"
expect(p.parse("Matt 1al2").osis()).toEqual "Matt.1-Matt.2"
expect(p.parse("Phlm 2 AL 3").osis()).toEqual "Phlm.1.2-Phlm.1.3"
it "should handle chapters (es)", ->
expect(p.parse("Titus 1:1, capítulos 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPÍTULOS 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, capitulos 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPITULOS 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, capítulo 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPÍTULO 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, capitulo 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPITULO 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, caps. 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPS. 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, caps 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAPS 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, cap. 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAP. 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, cap 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 CAP 6").osis()).toEqual "Matt.3.4,Matt.6"
it "should handle verses (es)", ->
expect(p.parse("Exod 1:1 versículos 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERSÍCULOS 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 versiculos 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERSICULOS 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 versículo 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERSÍCULO 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 versiculo 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERSICULO 6").osis()).toEqual "Phlm.1.6"
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"
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"
expect(p.parse("Exod 1:1 ver. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VER. 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 ver 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VER 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vss. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VSS. 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vss 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VSS 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vs. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VS. 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vs 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VS 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vv. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VV. 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 vv 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VV 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 v. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm V. 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 v 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm V 6").osis()).toEqual "Phlm.1.6"
it "should handle 'and' (es)", ->
expect(p.parse("Exod 1:1 y 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm 2 Y 6").osis()).toEqual "Phlm.1.2,Phlm.1.6"
it "should handle titles (es)", ->
expect(p.parse("Ps 3 subtítulo, 4:2, 5:subtítulo").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 SUBTÍTULO, 4:2, 5:SUBTÍTULO").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("Ps 3 subtitulo, 4:2, 5:subtitulo").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 SUBTITULO, 4:2, 5:SUBTITULO").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("Ps 3 título, 4:2, 5:título").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 TÍTULO, 4:2, 5:TÍTULO").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("Ps 3 titulo, 4:2, 5:titulo").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 TITULO, 4:2, 5:TITULO").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("Ps 3 tít, 4:2, 5:tít").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 TÍT, 4:2, 5:TÍT").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
it "should handle 'ff' (es)", ->
expect(p.parse("Rev 3y siguientes, 4:2y siguientes").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
expect(p.parse("REV 3 Y SIGUIENTES, 4:2 Y SIGUIENTES").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
expect(p.parse("Rev 3y sig, 4:2y sig").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
expect(p.parse("REV 3 Y SIG, 4:2 Y SIG").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
it "should handle translations (es)", ->
expect(p.parse("Lev 1 (DHH)").osis_and_translations()).toEqual [["Lev.1", "DHH"]]
expect(p.parse("lev 1 dhh").osis_and_translations()).toEqual [["Lev.1", "DHH"]]
expect(p.parse("Lev 1 (LBLA)").osis_and_translations()).toEqual [["Lev.1", "LBLA"]]
expect(p.parse("lev 1 lbla").osis_and_translations()).toEqual [["Lev.1", "LBLA"]]
expect(p.parse("Lev 1 (NBLH)").osis_and_translations()).toEqual [["Lev.1", "NBLH"]]
expect(p.parse("lev 1 nblh").osis_and_translations()).toEqual [["Lev.1", "NBLH"]]
expect(p.parse("Lev 1 (NTV)").osis_and_translations()).toEqual [["Lev.1", "NTV"]]
expect(p.parse("lev 1 ntv").osis_and_translations()).toEqual [["Lev.1", "NTV"]]
expect(p.parse("Lev 1 (NVI)").osis_and_translations()).toEqual [["Lev.1", "NVI"]]
expect(p.parse("lev 1 nvi").osis_and_translations()).toEqual [["Lev.1", "NVI"]]
expect(p.parse("Lev 1 (RVR)").osis_and_translations()).toEqual [["Lev.1", "RVR"]]
expect(p.parse("lev 1 rvr").osis_and_translations()).toEqual [["Lev.1", "RVR"]]
expect(p.parse("Lev 1 (RVR1960)").osis_and_translations()).toEqual [["Lev.1", "RVR1960"]]
expect(p.parse("lev 1 rvr1960").osis_and_translations()).toEqual [["Lev.1", "RVR1960"]]
expect(p.parse("Lev 1 (TLA)").osis_and_translations()).toEqual [["Lev.1", "TLA"]]
expect(p.parse("lev 1 tla").osis_and_translations()).toEqual [["Lev.1", "TLA"]]
it "should handle book ranges (es)", ->
p.set_options {book_alone_strategy: "full", book_range_strategy: "include"}
expect(p.parse("1.º á 3.º Jaan").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º al 3.º Jaan").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º á 3.º Jaun").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º al 3.º Jaun").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º á 3.º Juan").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º al 3.º Juan").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º á 3.º Juun").osis()).toEqual "1John.1-3John.1"
expect(p.parse("1.º al 3.º Juun").osis()).toEqual "1John.1-3John.1"
it "should handle boundaries (es)", ->
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": "e: 1\n Content: messageContent\n FromUserName: fromUser\n ToUserName: toUser\n LocalID: msgId\n Cli",
"end": 1174,
"score": 0.9895610809326172,
"start": 1166,
"tag": "USERNAME",
"value": "fromUser"
},
{
"context": "Content\n FromUserName: fromUser\n ToUserName: toUser\n LocalID: msgId\n ClientMsgId: msgId\n param",
"end": 1197,
"score": 0.9935449361801147,
"start": 1191,
"tag": "USERNAME",
"value": "toUser"
},
{
"context": "e: 1\n Content: messageContent\n FromUserName: fromUser\n ToUserName: toUser\n LocalID: msgId\n Cli",
"end": 1550,
"score": 0.936094343662262,
"start": 1542,
"tag": "USERNAME",
"value": "fromUser"
},
{
"context": "Content\n FromUserName: fromUser\n ToUserName: toUser\n LocalID: msgId\n ClientMsgId: msgId\n param",
"end": 1573,
"score": 0.9896732568740845,
"start": 1567,
"tag": "USERNAME",
"value": "toUser"
},
{
"context": "post_sync url, params\n return res\n\ngetOplog = (myUserName, callback = null) ->\n url = config.baseUrl + con",
"end": 1994,
"score": 0.8962274193763733,
"start": 1984,
"tag": "USERNAME",
"value": "myUserName"
},
{
"context": "markName\": config.onlineRemarkName\n \"UserName\": myUserName\n log.info \"params #{params}\", params\n if callba",
"end": 2193,
"score": 0.9989391565322876,
"start": 2183,
"tag": "USERNAME",
"value": "myUserName"
},
{
"context": "ary = \"--#{boundaryInContentType}\"\n boundaryKey = \"#{boundary}#{newLine}\"\n endBoundary = \"\\r\\n\\r\\n--#{boundaryInContentTyp",
"end": 3861,
"score": 0.9985663294792175,
"start": 3838,
"tag": "KEY",
"value": "\"#{boundary}#{newLine}\""
},
{
"context": ": UPLOAD_MEDIA_TYPE_ATTACHMENT\n \"FromUserName\": fromUser\n \"ToUserName\": toUser\n \"FileMd5\": fileMd5\n ",
"end": 5773,
"score": 0.999284029006958,
"start": 5765,
"tag": "USERNAME",
"value": "fromUser"
},
{
"context": "ENT\n \"FromUserName\": fromUser\n \"ToUserName\": toUser\n \"FileMd5\": fileMd5\n content += \"#{jsons uplo",
"end": 5798,
"score": 0.9992460012435913,
"start": 5792,
"tag": "USERNAME",
"value": "toUser"
},
{
"context": " Type: 3\n MediaId: mediaId\n FromUserName: fromUser\n ToUserName: toUser\n LocalID: msgId\n Cli",
"end": 8295,
"score": 0.999180793762207,
"start": 8287,
"tag": "USERNAME",
"value": "fromUser"
},
{
"context": "mediaId\n FromUserName: fromUser\n ToUserName: toUser\n LocalID: msgId\n ClientMsgId: msgId\n param",
"end": 8318,
"score": 0.9992061853408813,
"start": 8312,
"tag": "USERNAME",
"value": "toUser"
},
{
"context": "mojiFlag: 2\n MediaId: mediaId\n FromUserName: fromUser\n ToUserName: toUser\n LocalID: msgId\n Cli",
"end": 8746,
"score": 0.9937326908111572,
"start": 8738,
"tag": "USERNAME",
"value": "fromUser"
},
{
"context": "mediaId\n FromUserName: fromUser\n ToUserName: toUser\n LocalID: msgId\n ClientMsgId: msgId\n param",
"end": 8769,
"score": 0.9962241649627686,
"start": 8763,
"tag": "USERNAME",
"value": "toUser"
}
] | src/wxApi.coffee | npmmirror/Hubot-WeChat | 416 | # node.js deps
path = require 'path'
fs = require 'fs'
util = require 'util'
jsons = JSON.stringify
# npm deps
_ = require 'lodash'
md5 = require 'file-md5'
# app deps
config = require '../src/config'
client = require '../src/httpclient'
log = require '../src/wxLog'
{HttpCodes, WxResCodes} = require '../src/constants'
getContact = (callback = null) ->
url = config.baseUrl + config.getContactUrl
if callback
params = {} # For extension
res = client.get url, params, callback
else
res = client.get_sync url
return res
getBatchContact = (groupInfo, callback = null) ->
url = config.baseUrl + config.batchGetContactUrl
groupList = []
for key of groupInfo
groupList.push({"UserName": key, "ChatRoomId": ""})
params =
"BaseRequest": _getBaseRequest()
"Count": groupList.length
"List": groupList
if callback
client.post {url:url}, params, callback
else
res = client.post_sync url, params
return res
sendMessage = (fromUser, toUser, messageContent, callback) ->
url = config.baseUrl + config.sendMsgUrl
msgId = _getMsgIdFromTimeStamp()
m =
Type: 1
Content: messageContent
FromUserName: fromUser
ToUserName: toUser
LocalID: msgId
ClientMsgId: msgId
params =
"BaseRequest": _getBaseRequest()
"Msg": m
client.post {url:url}, params, callback
sendSyncMessage = (fromUser, toUser, messageContent) ->
url = config.baseUrl + config.sendMsgUrl
msgId = _getMsgIdFromTimeStamp()
m =
Type: 1
Content: messageContent
FromUserName: fromUser
ToUserName: toUser
LocalID: msgId
ClientMsgId: msgId
params =
"BaseRequest": _getBaseRequest()
"Msg": m
res = client.post_sync url, params
return res
getInit = (callback = null) ->
url = config.baseUrl + config.getWebwxInit
params =
"BaseRequest": _getBaseRequest()
if callback
client.post {url:url}, params, callback
else
res = client.post_sync url, params
return res
getOplog = (myUserName, callback = null) ->
url = config.baseUrl + config.getWebwxOplog
params =
"BaseRequest": _getBaseRequest()
"CmdId": 2
"RemarkName": config.onlineRemarkName
"UserName": myUserName
log.info "params #{params}", params
if callback
client.post {url:url}, params, callback
else
res = client.post_sync url, params
return res
asyncWebWxSync = (synckey, callback) ->
url = config.baseUrl + config.getWebwxSync
params =
"BaseRequest": _getBaseRequest()
"SyncKey": synckey
"rr": -602451563 ## Todo: what is rr?
client.post {url:url}, params, callback
###########################
# Synchronization webWxSync
###########################
webWxSync = (synckey, callback) ->
url = config.baseUrl + config.getWebwxSync
params =
"BaseRequest": _getBaseRequest()
"SyncKey": synckey
"rr": -602451563 ## Todo: what is rr?
res = client.post_sync url, params
return res
syncCheck = (synckey, syncCheckCounter, callback) ->
url = config.baseSyncChkUrl + config.syncCheck
syncKeyList = []
_.each synckey.List, (value) ->
tempList = []
_.forIn value, (value) ->
tempList.push value
syncKeyList.push(_.join(tempList, "_"))
syncKeyStr = _.join(syncKeyList, "|")
query = "r=" + _getMsgIdFromTimeStamp() + "&skey=" + config.Skey + "&sid=" + config.Sid + "&uin=" + config.Uin + "&deviceid=" + config.DeviceID + "&syncKey=" + syncKeyStr + "&_=" + syncCheckCounter
url = url + "?" +query
params = {}
client.get url, params, callback
webWxUploadAndSendMedia = (fromUser, toUser, filePath) ->
url = config.baseUploadUrl + config.webWxUploadMedia + "?f=json"
newLine = "\r\n"
new2Lines = "\r\n\r\n"
boundaryInContentType = "----WebKitFormBoundaryacBe9jJZzIeqONeW" # + Math.random().toString(16)
boundary = "--#{boundaryInContentType}"
boundaryKey = "#{boundary}#{newLine}"
endBoundary = "\r\n\r\n--#{boundaryInContentType}--\r\n"
UPLOAD_MEDIA_TYPE_ATTACHMENT = 4
file = fs.openSync filePath, 'r'
stats = fs.statSync filePath
fileName = path.basename filePath
ext = (fileName.split ".")[1]
fileMd5 = md5 filePath, null
log.debug "stats: %j", stats
log.debug "file MD5 #{fileMd5}"
wuFileType =
"jpg": "WU_FILE_0"
"jpeg": "WU_FILE_0"
"png": "WU_FILE_0"
"gif": "WU_FILE_3"
mediaType =
"jpg": "image/jpeg"
"jpeg": "image/jpeg"
"png": "image/png"
"gif": "image/gif"
mediaT =
"jpg": "pic"
"jpeg": "pic"
"png": "pic"
"gif": "doc"
content = boundaryKey
content = "Content-Disposition: form-data; name=\"id\"#{new2Lines}"
content += "#{wuFileType[ext]}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"name\"#{new2Lines}"
content += "#{fileName}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"type\"#{new2Lines}"
content += "#{mediaType[ext]}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"lastModifiedDate\"#{new2Lines}"
content += "#{stats.mtime}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"size\"#{new2Lines}"
content += "#{stats.size}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"mediatype\"#{new2Lines}"
#content += "#{file.ext? "pic" then "doc"}#{newLine}"
content += "#{mediaT[ext]}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"uploadmediarequest\"#{new2Lines}"
uploadmediarequest =
"UploadType": 2
"BaseRequest": _getBaseRequest()
"ClientMediaId": +new Date
"TotalLen": stats.size
"StartPos": 0
"DataLen": stats.size
"MediaType": UPLOAD_MEDIA_TYPE_ATTACHMENT
"FromUserName": fromUser
"ToUserName": toUser
"FileMd5": fileMd5
content += "#{jsons uploadmediarequest}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"webwx_data_ticket\"#{new2Lines}"
cookieItems = config.cookie.split ";"
ticket = _.find(cookieItems, (x) ->
return x.indexOf("webwx_data_ticket") != -1
).split("=")[1]
content += "#{ticket}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"pass_ticket\"#{new2Lines}"
#content += "jfL17ewPjc7ArkA84QGNyxpnL7bq7ZEaUJ8x4r/MzsliajJ8F1KT4RIQB73Zn9IW#{newLine}"
content += "undefined#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"filename\"; filename=\"#{fileName}\"#{newLine}"
content += "Content-Type: #{mediaType[ext]}#{new2Lines}"
log.debug "stats size: " + stats.size
contentLength = Buffer.byteLength(content) + Buffer.byteLength(endBoundary) + stats.size
header =
"Accept": "*/*"
"Accept-Encoding": "gzip, deflate"
"Accept-Language": "en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4"
"Content-Length": contentLength
"Connection": config.connection
"Content-Type": "multipart/form-data; boundary=#{boundaryInContentType}"
# "Host": "file2.wx.qq.com"
# "Origin": "https://wx2.qq.com"
# "Referer": "https://wx2.qq.com/"
options =
"url": url
"headers": header
params =
"boundary": boundary
"endBoundary": endBoundary
"filePath": filePath
log.debug "upload content:\n#{content}"
log.debug "params: %j", params
client.upload_file options, params, content, (body) ->
log.debug "upload file done\n", body
try
jsonBody = JSON.parse body
# log.debug "jsonBody: %j", jsonBody
if jsonBody.BaseResponse.Ret is 0
mediaId = jsonBody.MediaId
if ext isnt "gif"
sendImage fromUser, toUser, mediaId, (resp, resBody, opts) ->
log.debug "sendImageToUser", jsons resBody
else
sendEmotion fromUser, toUser, mediaId, (resp, resBody, opts) ->
log.debug "sendEmotionToUser", jsons resBody
else
log.error "Upload media failed, RC: #{jsonBody.BaseResponse.Ret}"
catch error
log.error "Failed to parse as JSON, #{error}"
sendImage = (fromUser, toUser, mediaId, callback) ->
log.debug "mediaId: #{mediaId}"
url = config.baseUrl + config.webwxsendmsgimg + "?fun=async&f=json"
msgId = _getMsgIdFromTimeStamp()
m =
Type: 3
MediaId: mediaId
FromUserName: fromUser
ToUserName: toUser
LocalID: msgId
ClientMsgId: msgId
params =
"BaseRequest": _getBaseRequest()
"Msg": m
"Scene": 0
client.post {url:url}, params, callback
sendEmotion = (fromUser, toUser, mediaId, callback) ->
log.debug "mediaId: #{mediaId}"
url = config.baseUrl + "/webwxsendemoticon" + "?fun=sys"
msgId = _getMsgIdFromTimeStamp()
m =
Type: 47
EmojiFlag: 2
MediaId: mediaId
FromUserName: fromUser
ToUserName: toUser
LocalID: msgId
ClientMsgId: msgId
params =
"BaseRequest": _getBaseRequest()
"Msg": m
"Scene": 0
client.post {url:url}, params, callback
_getBaseRequest = () ->
return r =
Uin: config.Uin
Sid: config.Sid
Skey: config.Skey
DeviceID: config.DeviceID
_getRandom = (max, min) ->
return Math.floor(Math.random() * (max - min)) + min
_getMsgIdFromTimeStamp = () ->
return new Date().getTime().toString() + _getRandom 9999, 1000
module.exports = {
getContact
getBatchContact
getInit
getOplog
asyncWebWxSync
webWxSync
syncCheck
sendMessage
sendSyncMessage
webWxUploadAndSendMedia
sendImage
_getMsgIdFromTimeStamp
}
| 177860 | # node.js deps
path = require 'path'
fs = require 'fs'
util = require 'util'
jsons = JSON.stringify
# npm deps
_ = require 'lodash'
md5 = require 'file-md5'
# app deps
config = require '../src/config'
client = require '../src/httpclient'
log = require '../src/wxLog'
{HttpCodes, WxResCodes} = require '../src/constants'
getContact = (callback = null) ->
url = config.baseUrl + config.getContactUrl
if callback
params = {} # For extension
res = client.get url, params, callback
else
res = client.get_sync url
return res
getBatchContact = (groupInfo, callback = null) ->
url = config.baseUrl + config.batchGetContactUrl
groupList = []
for key of groupInfo
groupList.push({"UserName": key, "ChatRoomId": ""})
params =
"BaseRequest": _getBaseRequest()
"Count": groupList.length
"List": groupList
if callback
client.post {url:url}, params, callback
else
res = client.post_sync url, params
return res
sendMessage = (fromUser, toUser, messageContent, callback) ->
url = config.baseUrl + config.sendMsgUrl
msgId = _getMsgIdFromTimeStamp()
m =
Type: 1
Content: messageContent
FromUserName: fromUser
ToUserName: toUser
LocalID: msgId
ClientMsgId: msgId
params =
"BaseRequest": _getBaseRequest()
"Msg": m
client.post {url:url}, params, callback
sendSyncMessage = (fromUser, toUser, messageContent) ->
url = config.baseUrl + config.sendMsgUrl
msgId = _getMsgIdFromTimeStamp()
m =
Type: 1
Content: messageContent
FromUserName: fromUser
ToUserName: toUser
LocalID: msgId
ClientMsgId: msgId
params =
"BaseRequest": _getBaseRequest()
"Msg": m
res = client.post_sync url, params
return res
getInit = (callback = null) ->
url = config.baseUrl + config.getWebwxInit
params =
"BaseRequest": _getBaseRequest()
if callback
client.post {url:url}, params, callback
else
res = client.post_sync url, params
return res
getOplog = (myUserName, callback = null) ->
url = config.baseUrl + config.getWebwxOplog
params =
"BaseRequest": _getBaseRequest()
"CmdId": 2
"RemarkName": config.onlineRemarkName
"UserName": myUserName
log.info "params #{params}", params
if callback
client.post {url:url}, params, callback
else
res = client.post_sync url, params
return res
asyncWebWxSync = (synckey, callback) ->
url = config.baseUrl + config.getWebwxSync
params =
"BaseRequest": _getBaseRequest()
"SyncKey": synckey
"rr": -602451563 ## Todo: what is rr?
client.post {url:url}, params, callback
###########################
# Synchronization webWxSync
###########################
webWxSync = (synckey, callback) ->
url = config.baseUrl + config.getWebwxSync
params =
"BaseRequest": _getBaseRequest()
"SyncKey": synckey
"rr": -602451563 ## Todo: what is rr?
res = client.post_sync url, params
return res
syncCheck = (synckey, syncCheckCounter, callback) ->
url = config.baseSyncChkUrl + config.syncCheck
syncKeyList = []
_.each synckey.List, (value) ->
tempList = []
_.forIn value, (value) ->
tempList.push value
syncKeyList.push(_.join(tempList, "_"))
syncKeyStr = _.join(syncKeyList, "|")
query = "r=" + _getMsgIdFromTimeStamp() + "&skey=" + config.Skey + "&sid=" + config.Sid + "&uin=" + config.Uin + "&deviceid=" + config.DeviceID + "&syncKey=" + syncKeyStr + "&_=" + syncCheckCounter
url = url + "?" +query
params = {}
client.get url, params, callback
webWxUploadAndSendMedia = (fromUser, toUser, filePath) ->
url = config.baseUploadUrl + config.webWxUploadMedia + "?f=json"
newLine = "\r\n"
new2Lines = "\r\n\r\n"
boundaryInContentType = "----WebKitFormBoundaryacBe9jJZzIeqONeW" # + Math.random().toString(16)
boundary = "--#{boundaryInContentType}"
boundaryKey = <KEY>
endBoundary = "\r\n\r\n--#{boundaryInContentType}--\r\n"
UPLOAD_MEDIA_TYPE_ATTACHMENT = 4
file = fs.openSync filePath, 'r'
stats = fs.statSync filePath
fileName = path.basename filePath
ext = (fileName.split ".")[1]
fileMd5 = md5 filePath, null
log.debug "stats: %j", stats
log.debug "file MD5 #{fileMd5}"
wuFileType =
"jpg": "WU_FILE_0"
"jpeg": "WU_FILE_0"
"png": "WU_FILE_0"
"gif": "WU_FILE_3"
mediaType =
"jpg": "image/jpeg"
"jpeg": "image/jpeg"
"png": "image/png"
"gif": "image/gif"
mediaT =
"jpg": "pic"
"jpeg": "pic"
"png": "pic"
"gif": "doc"
content = boundaryKey
content = "Content-Disposition: form-data; name=\"id\"#{new2Lines}"
content += "#{wuFileType[ext]}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"name\"#{new2Lines}"
content += "#{fileName}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"type\"#{new2Lines}"
content += "#{mediaType[ext]}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"lastModifiedDate\"#{new2Lines}"
content += "#{stats.mtime}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"size\"#{new2Lines}"
content += "#{stats.size}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"mediatype\"#{new2Lines}"
#content += "#{file.ext? "pic" then "doc"}#{newLine}"
content += "#{mediaT[ext]}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"uploadmediarequest\"#{new2Lines}"
uploadmediarequest =
"UploadType": 2
"BaseRequest": _getBaseRequest()
"ClientMediaId": +new Date
"TotalLen": stats.size
"StartPos": 0
"DataLen": stats.size
"MediaType": UPLOAD_MEDIA_TYPE_ATTACHMENT
"FromUserName": fromUser
"ToUserName": toUser
"FileMd5": fileMd5
content += "#{jsons uploadmediarequest}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"webwx_data_ticket\"#{new2Lines}"
cookieItems = config.cookie.split ";"
ticket = _.find(cookieItems, (x) ->
return x.indexOf("webwx_data_ticket") != -1
).split("=")[1]
content += "#{ticket}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"pass_ticket\"#{new2Lines}"
#content += "jfL17ewPjc7ArkA84QGNyxpnL7bq7ZEaUJ8x4r/MzsliajJ8F1KT4RIQB73Zn9IW#{newLine}"
content += "undefined#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"filename\"; filename=\"#{fileName}\"#{newLine}"
content += "Content-Type: #{mediaType[ext]}#{new2Lines}"
log.debug "stats size: " + stats.size
contentLength = Buffer.byteLength(content) + Buffer.byteLength(endBoundary) + stats.size
header =
"Accept": "*/*"
"Accept-Encoding": "gzip, deflate"
"Accept-Language": "en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4"
"Content-Length": contentLength
"Connection": config.connection
"Content-Type": "multipart/form-data; boundary=#{boundaryInContentType}"
# "Host": "file2.wx.qq.com"
# "Origin": "https://wx2.qq.com"
# "Referer": "https://wx2.qq.com/"
options =
"url": url
"headers": header
params =
"boundary": boundary
"endBoundary": endBoundary
"filePath": filePath
log.debug "upload content:\n#{content}"
log.debug "params: %j", params
client.upload_file options, params, content, (body) ->
log.debug "upload file done\n", body
try
jsonBody = JSON.parse body
# log.debug "jsonBody: %j", jsonBody
if jsonBody.BaseResponse.Ret is 0
mediaId = jsonBody.MediaId
if ext isnt "gif"
sendImage fromUser, toUser, mediaId, (resp, resBody, opts) ->
log.debug "sendImageToUser", jsons resBody
else
sendEmotion fromUser, toUser, mediaId, (resp, resBody, opts) ->
log.debug "sendEmotionToUser", jsons resBody
else
log.error "Upload media failed, RC: #{jsonBody.BaseResponse.Ret}"
catch error
log.error "Failed to parse as JSON, #{error}"
sendImage = (fromUser, toUser, mediaId, callback) ->
log.debug "mediaId: #{mediaId}"
url = config.baseUrl + config.webwxsendmsgimg + "?fun=async&f=json"
msgId = _getMsgIdFromTimeStamp()
m =
Type: 3
MediaId: mediaId
FromUserName: fromUser
ToUserName: toUser
LocalID: msgId
ClientMsgId: msgId
params =
"BaseRequest": _getBaseRequest()
"Msg": m
"Scene": 0
client.post {url:url}, params, callback
sendEmotion = (fromUser, toUser, mediaId, callback) ->
log.debug "mediaId: #{mediaId}"
url = config.baseUrl + "/webwxsendemoticon" + "?fun=sys"
msgId = _getMsgIdFromTimeStamp()
m =
Type: 47
EmojiFlag: 2
MediaId: mediaId
FromUserName: fromUser
ToUserName: toUser
LocalID: msgId
ClientMsgId: msgId
params =
"BaseRequest": _getBaseRequest()
"Msg": m
"Scene": 0
client.post {url:url}, params, callback
_getBaseRequest = () ->
return r =
Uin: config.Uin
Sid: config.Sid
Skey: config.Skey
DeviceID: config.DeviceID
_getRandom = (max, min) ->
return Math.floor(Math.random() * (max - min)) + min
_getMsgIdFromTimeStamp = () ->
return new Date().getTime().toString() + _getRandom 9999, 1000
module.exports = {
getContact
getBatchContact
getInit
getOplog
asyncWebWxSync
webWxSync
syncCheck
sendMessage
sendSyncMessage
webWxUploadAndSendMedia
sendImage
_getMsgIdFromTimeStamp
}
| true | # node.js deps
path = require 'path'
fs = require 'fs'
util = require 'util'
jsons = JSON.stringify
# npm deps
_ = require 'lodash'
md5 = require 'file-md5'
# app deps
config = require '../src/config'
client = require '../src/httpclient'
log = require '../src/wxLog'
{HttpCodes, WxResCodes} = require '../src/constants'
getContact = (callback = null) ->
url = config.baseUrl + config.getContactUrl
if callback
params = {} # For extension
res = client.get url, params, callback
else
res = client.get_sync url
return res
getBatchContact = (groupInfo, callback = null) ->
url = config.baseUrl + config.batchGetContactUrl
groupList = []
for key of groupInfo
groupList.push({"UserName": key, "ChatRoomId": ""})
params =
"BaseRequest": _getBaseRequest()
"Count": groupList.length
"List": groupList
if callback
client.post {url:url}, params, callback
else
res = client.post_sync url, params
return res
sendMessage = (fromUser, toUser, messageContent, callback) ->
url = config.baseUrl + config.sendMsgUrl
msgId = _getMsgIdFromTimeStamp()
m =
Type: 1
Content: messageContent
FromUserName: fromUser
ToUserName: toUser
LocalID: msgId
ClientMsgId: msgId
params =
"BaseRequest": _getBaseRequest()
"Msg": m
client.post {url:url}, params, callback
sendSyncMessage = (fromUser, toUser, messageContent) ->
url = config.baseUrl + config.sendMsgUrl
msgId = _getMsgIdFromTimeStamp()
m =
Type: 1
Content: messageContent
FromUserName: fromUser
ToUserName: toUser
LocalID: msgId
ClientMsgId: msgId
params =
"BaseRequest": _getBaseRequest()
"Msg": m
res = client.post_sync url, params
return res
getInit = (callback = null) ->
url = config.baseUrl + config.getWebwxInit
params =
"BaseRequest": _getBaseRequest()
if callback
client.post {url:url}, params, callback
else
res = client.post_sync url, params
return res
getOplog = (myUserName, callback = null) ->
url = config.baseUrl + config.getWebwxOplog
params =
"BaseRequest": _getBaseRequest()
"CmdId": 2
"RemarkName": config.onlineRemarkName
"UserName": myUserName
log.info "params #{params}", params
if callback
client.post {url:url}, params, callback
else
res = client.post_sync url, params
return res
asyncWebWxSync = (synckey, callback) ->
url = config.baseUrl + config.getWebwxSync
params =
"BaseRequest": _getBaseRequest()
"SyncKey": synckey
"rr": -602451563 ## Todo: what is rr?
client.post {url:url}, params, callback
###########################
# Synchronization webWxSync
###########################
webWxSync = (synckey, callback) ->
url = config.baseUrl + config.getWebwxSync
params =
"BaseRequest": _getBaseRequest()
"SyncKey": synckey
"rr": -602451563 ## Todo: what is rr?
res = client.post_sync url, params
return res
syncCheck = (synckey, syncCheckCounter, callback) ->
url = config.baseSyncChkUrl + config.syncCheck
syncKeyList = []
_.each synckey.List, (value) ->
tempList = []
_.forIn value, (value) ->
tempList.push value
syncKeyList.push(_.join(tempList, "_"))
syncKeyStr = _.join(syncKeyList, "|")
query = "r=" + _getMsgIdFromTimeStamp() + "&skey=" + config.Skey + "&sid=" + config.Sid + "&uin=" + config.Uin + "&deviceid=" + config.DeviceID + "&syncKey=" + syncKeyStr + "&_=" + syncCheckCounter
url = url + "?" +query
params = {}
client.get url, params, callback
webWxUploadAndSendMedia = (fromUser, toUser, filePath) ->
url = config.baseUploadUrl + config.webWxUploadMedia + "?f=json"
newLine = "\r\n"
new2Lines = "\r\n\r\n"
boundaryInContentType = "----WebKitFormBoundaryacBe9jJZzIeqONeW" # + Math.random().toString(16)
boundary = "--#{boundaryInContentType}"
boundaryKey = PI:KEY:<KEY>END_PI
endBoundary = "\r\n\r\n--#{boundaryInContentType}--\r\n"
UPLOAD_MEDIA_TYPE_ATTACHMENT = 4
file = fs.openSync filePath, 'r'
stats = fs.statSync filePath
fileName = path.basename filePath
ext = (fileName.split ".")[1]
fileMd5 = md5 filePath, null
log.debug "stats: %j", stats
log.debug "file MD5 #{fileMd5}"
wuFileType =
"jpg": "WU_FILE_0"
"jpeg": "WU_FILE_0"
"png": "WU_FILE_0"
"gif": "WU_FILE_3"
mediaType =
"jpg": "image/jpeg"
"jpeg": "image/jpeg"
"png": "image/png"
"gif": "image/gif"
mediaT =
"jpg": "pic"
"jpeg": "pic"
"png": "pic"
"gif": "doc"
content = boundaryKey
content = "Content-Disposition: form-data; name=\"id\"#{new2Lines}"
content += "#{wuFileType[ext]}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"name\"#{new2Lines}"
content += "#{fileName}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"type\"#{new2Lines}"
content += "#{mediaType[ext]}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"lastModifiedDate\"#{new2Lines}"
content += "#{stats.mtime}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"size\"#{new2Lines}"
content += "#{stats.size}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"mediatype\"#{new2Lines}"
#content += "#{file.ext? "pic" then "doc"}#{newLine}"
content += "#{mediaT[ext]}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"uploadmediarequest\"#{new2Lines}"
uploadmediarequest =
"UploadType": 2
"BaseRequest": _getBaseRequest()
"ClientMediaId": +new Date
"TotalLen": stats.size
"StartPos": 0
"DataLen": stats.size
"MediaType": UPLOAD_MEDIA_TYPE_ATTACHMENT
"FromUserName": fromUser
"ToUserName": toUser
"FileMd5": fileMd5
content += "#{jsons uploadmediarequest}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"webwx_data_ticket\"#{new2Lines}"
cookieItems = config.cookie.split ";"
ticket = _.find(cookieItems, (x) ->
return x.indexOf("webwx_data_ticket") != -1
).split("=")[1]
content += "#{ticket}#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"pass_ticket\"#{new2Lines}"
#content += "jfL17ewPjc7ArkA84QGNyxpnL7bq7ZEaUJ8x4r/MzsliajJ8F1KT4RIQB73Zn9IW#{newLine}"
content += "undefined#{newLine}"
content += boundaryKey
content += "Content-Disposition: form-data; name=\"filename\"; filename=\"#{fileName}\"#{newLine}"
content += "Content-Type: #{mediaType[ext]}#{new2Lines}"
log.debug "stats size: " + stats.size
contentLength = Buffer.byteLength(content) + Buffer.byteLength(endBoundary) + stats.size
header =
"Accept": "*/*"
"Accept-Encoding": "gzip, deflate"
"Accept-Language": "en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4"
"Content-Length": contentLength
"Connection": config.connection
"Content-Type": "multipart/form-data; boundary=#{boundaryInContentType}"
# "Host": "file2.wx.qq.com"
# "Origin": "https://wx2.qq.com"
# "Referer": "https://wx2.qq.com/"
options =
"url": url
"headers": header
params =
"boundary": boundary
"endBoundary": endBoundary
"filePath": filePath
log.debug "upload content:\n#{content}"
log.debug "params: %j", params
client.upload_file options, params, content, (body) ->
log.debug "upload file done\n", body
try
jsonBody = JSON.parse body
# log.debug "jsonBody: %j", jsonBody
if jsonBody.BaseResponse.Ret is 0
mediaId = jsonBody.MediaId
if ext isnt "gif"
sendImage fromUser, toUser, mediaId, (resp, resBody, opts) ->
log.debug "sendImageToUser", jsons resBody
else
sendEmotion fromUser, toUser, mediaId, (resp, resBody, opts) ->
log.debug "sendEmotionToUser", jsons resBody
else
log.error "Upload media failed, RC: #{jsonBody.BaseResponse.Ret}"
catch error
log.error "Failed to parse as JSON, #{error}"
sendImage = (fromUser, toUser, mediaId, callback) ->
log.debug "mediaId: #{mediaId}"
url = config.baseUrl + config.webwxsendmsgimg + "?fun=async&f=json"
msgId = _getMsgIdFromTimeStamp()
m =
Type: 3
MediaId: mediaId
FromUserName: fromUser
ToUserName: toUser
LocalID: msgId
ClientMsgId: msgId
params =
"BaseRequest": _getBaseRequest()
"Msg": m
"Scene": 0
client.post {url:url}, params, callback
sendEmotion = (fromUser, toUser, mediaId, callback) ->
log.debug "mediaId: #{mediaId}"
url = config.baseUrl + "/webwxsendemoticon" + "?fun=sys"
msgId = _getMsgIdFromTimeStamp()
m =
Type: 47
EmojiFlag: 2
MediaId: mediaId
FromUserName: fromUser
ToUserName: toUser
LocalID: msgId
ClientMsgId: msgId
params =
"BaseRequest": _getBaseRequest()
"Msg": m
"Scene": 0
client.post {url:url}, params, callback
_getBaseRequest = () ->
return r =
Uin: config.Uin
Sid: config.Sid
Skey: config.Skey
DeviceID: config.DeviceID
_getRandom = (max, min) ->
return Math.floor(Math.random() * (max - min)) + min
_getMsgIdFromTimeStamp = () ->
return new Date().getTime().toString() + _getRandom 9999, 1000
module.exports = {
getContact
getBatchContact
getInit
getOplog
asyncWebWxSync
webWxSync
syncCheck
sendMessage
sendSyncMessage
webWxUploadAndSendMedia
sendImage
_getMsgIdFromTimeStamp
}
|
[
{
"context": "it \"creates a new task\", ->\n form.setName \"New task\"\n form.submitButton.click()\n\n expec",
"end": 2008,
"score": 0.9892337322235107,
"start": 2000,
"tag": "NAME",
"value": "New task"
}
] | client/test/integration/tasks_scenario.coffee | lucassus/angular-coffee-seed | 2 | expect = require("./helpers/expect")
utils = require("./helpers/utils")
TasksPage = require("./helpers/page_objects/tasks_page")
describe "Tasks page", ->
tasksPage = null
beforeEach ->
browser.get "/#/tasks"
tasksPage = new TasksPage()
it "displays a valid page title", ->
expect(browser.getCurrentUrl()).to.eventually.match /#\/tasks$/
expect(browser.getTitle()).to.eventually.eq "Angular Seed"
describe "tasks list", ->
it "displays all tasks", ->
expect(tasksPage.tasksCount()).to.eventually.eq 3
expect(tasksPage.remaining.getText()).to.eventually.eq "2 of 3 remaining"
task = tasksPage.taskAt(0)
expect(task.isCompleted()).to.eventually.be.false
completedTask = tasksPage.taskAt(2)
expect(completedTask.isCompleted()).to.eventually.be.true
describe "click on `archive` button", ->
beforeEach ->
tasksPage.archiveButton.click()
it "archives all completed tasks", ->
expect(tasksPage.tasksCount()).to.eventually.eq 2
expect(tasksPage.remaining.getText()).to.eventually.eq "2 of 2 remaining"
describe "click on task's checkbox", ->
task = null
describe "when a task is not completed", ->
beforeEach ->
task = tasksPage.taskAt(1)
task.checkbox.click()
it "marks the task as completed", ->
expect(task.isCompleted()).to.eventually.be.true
expect(tasksPage.remaining.getText()).to.eventually.eq "1 of 3 remaining"
describe "when a task is completed", ->
beforeEach ->
task = tasksPage.taskAt(2)
task.checkbox.click()
it "marks the task as not completed", ->
expect(task.isCompleted()).to.eventually.be.false
expect(tasksPage.remaining.getText()).to.eventually.eq "3 of 3 remaining"
describe "new task form", ->
form = null
beforeEach -> form = tasksPage.form
describe "fill in the name and click `create` button", ->
it "creates a new task", ->
form.setName "New task"
form.submitButton.click()
expect(tasksPage.tasksCount()).to.eventually.eq 4
expect(tasksPage.remaining.getText()).to.eventually.eq "3 of 4 remaining"
task = tasksPage.taskAt(2)
expect(task.isCompleted()).to.eventually.be.false
expect(task.label.getText()).to.eventually.eq "New task"
| 211620 | expect = require("./helpers/expect")
utils = require("./helpers/utils")
TasksPage = require("./helpers/page_objects/tasks_page")
describe "Tasks page", ->
tasksPage = null
beforeEach ->
browser.get "/#/tasks"
tasksPage = new TasksPage()
it "displays a valid page title", ->
expect(browser.getCurrentUrl()).to.eventually.match /#\/tasks$/
expect(browser.getTitle()).to.eventually.eq "Angular Seed"
describe "tasks list", ->
it "displays all tasks", ->
expect(tasksPage.tasksCount()).to.eventually.eq 3
expect(tasksPage.remaining.getText()).to.eventually.eq "2 of 3 remaining"
task = tasksPage.taskAt(0)
expect(task.isCompleted()).to.eventually.be.false
completedTask = tasksPage.taskAt(2)
expect(completedTask.isCompleted()).to.eventually.be.true
describe "click on `archive` button", ->
beforeEach ->
tasksPage.archiveButton.click()
it "archives all completed tasks", ->
expect(tasksPage.tasksCount()).to.eventually.eq 2
expect(tasksPage.remaining.getText()).to.eventually.eq "2 of 2 remaining"
describe "click on task's checkbox", ->
task = null
describe "when a task is not completed", ->
beforeEach ->
task = tasksPage.taskAt(1)
task.checkbox.click()
it "marks the task as completed", ->
expect(task.isCompleted()).to.eventually.be.true
expect(tasksPage.remaining.getText()).to.eventually.eq "1 of 3 remaining"
describe "when a task is completed", ->
beforeEach ->
task = tasksPage.taskAt(2)
task.checkbox.click()
it "marks the task as not completed", ->
expect(task.isCompleted()).to.eventually.be.false
expect(tasksPage.remaining.getText()).to.eventually.eq "3 of 3 remaining"
describe "new task form", ->
form = null
beforeEach -> form = tasksPage.form
describe "fill in the name and click `create` button", ->
it "creates a new task", ->
form.setName "<NAME>"
form.submitButton.click()
expect(tasksPage.tasksCount()).to.eventually.eq 4
expect(tasksPage.remaining.getText()).to.eventually.eq "3 of 4 remaining"
task = tasksPage.taskAt(2)
expect(task.isCompleted()).to.eventually.be.false
expect(task.label.getText()).to.eventually.eq "New task"
| true | expect = require("./helpers/expect")
utils = require("./helpers/utils")
TasksPage = require("./helpers/page_objects/tasks_page")
describe "Tasks page", ->
tasksPage = null
beforeEach ->
browser.get "/#/tasks"
tasksPage = new TasksPage()
it "displays a valid page title", ->
expect(browser.getCurrentUrl()).to.eventually.match /#\/tasks$/
expect(browser.getTitle()).to.eventually.eq "Angular Seed"
describe "tasks list", ->
it "displays all tasks", ->
expect(tasksPage.tasksCount()).to.eventually.eq 3
expect(tasksPage.remaining.getText()).to.eventually.eq "2 of 3 remaining"
task = tasksPage.taskAt(0)
expect(task.isCompleted()).to.eventually.be.false
completedTask = tasksPage.taskAt(2)
expect(completedTask.isCompleted()).to.eventually.be.true
describe "click on `archive` button", ->
beforeEach ->
tasksPage.archiveButton.click()
it "archives all completed tasks", ->
expect(tasksPage.tasksCount()).to.eventually.eq 2
expect(tasksPage.remaining.getText()).to.eventually.eq "2 of 2 remaining"
describe "click on task's checkbox", ->
task = null
describe "when a task is not completed", ->
beforeEach ->
task = tasksPage.taskAt(1)
task.checkbox.click()
it "marks the task as completed", ->
expect(task.isCompleted()).to.eventually.be.true
expect(tasksPage.remaining.getText()).to.eventually.eq "1 of 3 remaining"
describe "when a task is completed", ->
beforeEach ->
task = tasksPage.taskAt(2)
task.checkbox.click()
it "marks the task as not completed", ->
expect(task.isCompleted()).to.eventually.be.false
expect(tasksPage.remaining.getText()).to.eventually.eq "3 of 3 remaining"
describe "new task form", ->
form = null
beforeEach -> form = tasksPage.form
describe "fill in the name and click `create` button", ->
it "creates a new task", ->
form.setName "PI:NAME:<NAME>END_PI"
form.submitButton.click()
expect(tasksPage.tasksCount()).to.eventually.eq 4
expect(tasksPage.remaining.getText()).to.eventually.eq "3 of 4 remaining"
task = tasksPage.taskAt(2)
expect(task.isCompleted()).to.eventually.be.false
expect(task.label.getText()).to.eventually.eq "New task"
|
[
{
"context": "info.port, auth:\n\t\t\tusername: auth[0]\n\t\t\tpassword: auth[1]\n\telse\n\t\tclient = new(cradle.Connection)(info.h",
"end": 357,
"score": 0.6810984015464783,
"start": 353,
"tag": "PASSWORD",
"value": "auth"
}
] | src/scripts/store-messages-couchdb.coffee | iangreenleaf/hubot-scripts | 2 | Url = require "url"
cradle = require "cradle"
# sets up hooks to persist all messages into couchdb.
module.exports = (robot) ->
info = Url.parse process.env.HUBOT_COUCHDB_URL || 'http://localhost:5984'
if info.auth
auth = info.auth.split(":")
client = new(cradle.Connection) info.hostname, info.port, auth:
username: auth[0]
password: auth[1]
else
client = new(cradle.Connection)(info.hostname, info.port)
db = client.database(if info.pathname != '/' then info.pathname.slice(1) else "hubot-storage")
robot.hear /.*$/i, (msg) ->
message = msg.message
message.date = new Date
# ignore topic and other messages
return if typeof message.user.id == 'undefined'
db.save message, (err, res) ->
if err then console.error(err) | 107675 | Url = require "url"
cradle = require "cradle"
# sets up hooks to persist all messages into couchdb.
module.exports = (robot) ->
info = Url.parse process.env.HUBOT_COUCHDB_URL || 'http://localhost:5984'
if info.auth
auth = info.auth.split(":")
client = new(cradle.Connection) info.hostname, info.port, auth:
username: auth[0]
password: <PASSWORD>[1]
else
client = new(cradle.Connection)(info.hostname, info.port)
db = client.database(if info.pathname != '/' then info.pathname.slice(1) else "hubot-storage")
robot.hear /.*$/i, (msg) ->
message = msg.message
message.date = new Date
# ignore topic and other messages
return if typeof message.user.id == 'undefined'
db.save message, (err, res) ->
if err then console.error(err) | true | Url = require "url"
cradle = require "cradle"
# sets up hooks to persist all messages into couchdb.
module.exports = (robot) ->
info = Url.parse process.env.HUBOT_COUCHDB_URL || 'http://localhost:5984'
if info.auth
auth = info.auth.split(":")
client = new(cradle.Connection) info.hostname, info.port, auth:
username: auth[0]
password: PI:PASSWORD:<PASSWORD>END_PI[1]
else
client = new(cradle.Connection)(info.hostname, info.port)
db = client.database(if info.pathname != '/' then info.pathname.slice(1) else "hubot-storage")
robot.hear /.*$/i, (msg) ->
message = msg.message
message.date = new Date
# ignore topic and other messages
return if typeof message.user.id == 'undefined'
db.save message, (err, res) ->
if err then console.error(err) |
[
{
"context": "y ID: #{collectionkey}\" if isNaN(libid)\n\n key = '' + path[0]\n col = null\n for name in path\n ",
"end": 893,
"score": 0.7300098538398743,
"start": 889,
"tag": "KEY",
"value": "'' +"
}
] | chrome/content/zotero-better-bibtex/web-endpoints.coffee | edwinksl/zotero-better-bibtex | 0 | Zotero.BetterBibTeX.endpoints = { }
Zotero.BetterBibTeX.endpoints.collection = { supportedMethods: ['GET'] }
Zotero.BetterBibTeX.endpoints.collection.init = (url, data, sendResponseCallback) ->
try
collection = url.query['']
catch err
collection = null
if not collection
sendResponseCallback(501, 'text/plain', 'Could not export bibliography: no path')
return
try
path = collection.split('.')
if path.length == 1
sendResponseCallback(404, 'text/plain', "Could not export bibliography '#{collection}': no format specified")
return
translator = path.pop()
path = path.join('.')
path = "/0/#{path}" if path.charAt(0) != '/'
path = path.split('/')
### removes empty field before first '/' ###
path.shift()
libid = parseInt(path.shift())
throw "Not a valid library ID: #{collectionkey}" if isNaN(libid)
key = '' + path[0]
col = null
for name in path
children = Zotero.getCollections(col?.id, false, libid)
col = null
for child in children
if child.name.toLowerCase() is name.toLowerCase()
col = child
break
if not col then break
col ||= Zotero.Collections.getByLibraryAndKey(libid, key)
throw "#{collectionkey} not found" unless col
deferred = Q.defer()
Zotero.BetterBibTeX.translate(Zotero.BetterBibTeX.getTranslator(translator), {collection: col}, Zotero.BetterBibTeX.displayOptions(url), (err, result) ->
if err
deferred.reject(err)
else
deferred.fulfill(result)
)
sendResponseCallback(200, 'text/plain', deferred.promise)
catch err
Zotero.BetterBibTeX.log("Could not export bibliography '#{collection}", err)
sendResponseCallback(404, 'text/plain', "Could not export bibliography '#{collection}': #{err}")
Zotero.BetterBibTeX.endpoints.library = { supportedMethods: ['GET'] }
Zotero.BetterBibTeX.endpoints.library.init = (url, data, sendResponseCallback) ->
try
library = url.query['']
catch err
library = null
if not library
sendResponseCallback(501, 'text/plain', 'Could not export bibliography: no path')
return
try
params = /^\/?([0-9]+)?\/?library.(.*)$/.exec(library)
libid = params[1]
format = params[2]
if libid && not Zotero.Libraries.exists(libid)
sendResponseCallback(404, 'text/plain', "Could not export bibliography: library '#{library}' does not exist")
return
if !format
sendResponseCallback(404, 'text/plain', "Could not export bibliography '#{library}': no format specified")
return
translator = Zotero.BetterBibTeX.getTranslator(format)
if !translator
sendResponseCallback(404, 'text/plain', "Could not export bibliography '#{library}': unsupported format #{format}")
return
deferred = Q.defer()
Zotero.BetterBibTeX.translate(translator, {library: libid}, Zotero.BetterBibTeX.displayOptions(url), (err, result) ->
if err
deferred.reject(err)
else
deferred.fulfill(result)
)
sendResponseCallback(200, 'text/plain', deferred.promise)
catch err
Zotero.BetterBibTeX.log("Could not export bibliography '#{library}'", err)
sendResponseCallback(404, 'text/plain', "Could not export bibliography '#{library}': #{err}")
Zotero.BetterBibTeX.endpoints.selected = { supportedMethods: ['GET'] }
Zotero.BetterBibTeX.endpoints.selected.init = (url, data, sendResponseCallback) ->
try
translator = url.query['']
catch err
translator = null
if not translator
sendResponseCallback(501, 'text/plain', 'Could not export bibliography: no path')
return
zoteroPane = Zotero.getActiveZoteroPane()
items = Zotero.Items.get((item.id for item of zoteroPane.getSelectedItems()))
deferred = Q.defer()
Zotero.BetterBibTeX.translate(Zotero.BetterBibTeX.getTranslator(translator), {items: items}, Zotero.BetterBibTeX.displayOptions(url), (err, result) ->
if err
deferred.reject(err)
else
deferred.fulfill(result)
)
sendResponseCallback(200, 'text/plain', deferred.promise)
Zotero.BetterBibTeX.endpoints.schomd = { supportedMethods: ['POST'] }
Zotero.BetterBibTeX.endpoints.schomd.init = (url, data, sendResponseCallback) ->
req = JSON.parse(data)
response = []
throw new Error('batch requests are not supported') if Array.isArray(req)
try
switch req.method
when 'citations', 'citation', 'bibliography', 'bibliographyhtml', 'bibliographybbl', 'bibtex', 'search'
### the schomd methods search by citekey -- the cache needs to be fully primed for this to work ###
Zotero.BetterBibTeX.keymanager.prime()
result = Zotero.BetterBibTeX.schomd[req.method].apply(Zotero.BetterBibTeX.schomd, req.params)
if typeof result?.then == 'function'
result = result.then((result) ->
return JSON.stringify({
jsonrpc: (if req.jsonrpc then req.jsonrpc else undefined)
id: (if req.id || (typeof req.id) == 'number' then req.id else null)
result
})
).catch((e) ->
return JSON.stringify({
jsonrpc: (if req.jsonrpc then req.jsonrpc else undefined)
id: (if req.id || (typeof req.id) == 'number' then req.id else null)
result: e.message
})
)
else
result = JSON.stringify({
jsonrpc: (if req.jsonrpc then req.jsonrpc else undefined)
id: (if req.id || (typeof req.id) == 'number' then req.id else null)
result
})
else throw("Unsupported method '#{req.method}'")
catch err
result = JSON.stringify({jsonrpc: '2.0', error: {code: 5000, message: '' + err + "\n" + err.stack}, id: null})
return sendResponseCallback(200, 'application/json', result)
Zotero.BetterBibTeX.endpoints.cayw = { supportedMethods: ['GET'] }
Zotero.BetterBibTeX.endpoints.cayw.init = (url, data, sendResponseCallback) ->
if url.query.probe
sendResponseCallback(200, 'text/plain', 'ready')
return
doc = new Zotero.BetterBibTeX.CAYW.Document(url.query || {})
deferred = Q.defer()
io = new Zotero.BetterBibTeX.CAYW.CitationEditInterface(deferred, url.query || {}, doc)
if Zotero.Prefs.get('integration.useClassicAddCitationDialog')
Zotero.Integration.displayDialog(doc, 'chrome://zotero/content/integration/addCitationDialog.xul', 'alwaysRaised,resizable', io)
else
mode = if !Zotero.isMac and Zotero.Prefs.get('integration.keepAddCitationDialogRaised') then 'popup' else 'alwaysRaised'
Zotero.Integration.displayDialog(doc, 'chrome://zotero/content/integration/quickFormat.xul', mode, io)
sendResponseCallback(200, 'text/plain', deferred.promise)
Zotero.BetterBibTeX.endpoints.cacheActivity =
supportedMethods: ['GET']
init: (url, data, sendResponseCallback) ->
try
dataURL = url.query['']
catch err
dataURL = null
if dataURL
# someone thinks HTML-loaded javascripts are harmful. If that were true, you have bigger problems than this
# people.
return sendResponseCallback(200, 'text/html', Zotero.File.getContentsFromURL('resource://zotero-better-bibtex/reports/cacheActivity.txt'))
Zotero.BetterBibTeX.addCacheHistory()
timestamp = (date) ->
date = [date.getHours(), date.getMinutes(), date.getSeconds()]
date = (('0' + dp).slice(-2) for dp in date)
return date.join(':')
data = ([timestamp(dp.timestamp), dp.serialized.hit, dp.serialized.miss, dp.serialized.clear, dp.cache.hit, dp.cache.miss, dp.cache.clear] for dp in Zotero.BetterBibTeX.cacheHistory)
return sendResponseCallback(200, 'application/json', JSON.stringify(data))
| 139429 | Zotero.BetterBibTeX.endpoints = { }
Zotero.BetterBibTeX.endpoints.collection = { supportedMethods: ['GET'] }
Zotero.BetterBibTeX.endpoints.collection.init = (url, data, sendResponseCallback) ->
try
collection = url.query['']
catch err
collection = null
if not collection
sendResponseCallback(501, 'text/plain', 'Could not export bibliography: no path')
return
try
path = collection.split('.')
if path.length == 1
sendResponseCallback(404, 'text/plain', "Could not export bibliography '#{collection}': no format specified")
return
translator = path.pop()
path = path.join('.')
path = "/0/#{path}" if path.charAt(0) != '/'
path = path.split('/')
### removes empty field before first '/' ###
path.shift()
libid = parseInt(path.shift())
throw "Not a valid library ID: #{collectionkey}" if isNaN(libid)
key = <KEY> path[0]
col = null
for name in path
children = Zotero.getCollections(col?.id, false, libid)
col = null
for child in children
if child.name.toLowerCase() is name.toLowerCase()
col = child
break
if not col then break
col ||= Zotero.Collections.getByLibraryAndKey(libid, key)
throw "#{collectionkey} not found" unless col
deferred = Q.defer()
Zotero.BetterBibTeX.translate(Zotero.BetterBibTeX.getTranslator(translator), {collection: col}, Zotero.BetterBibTeX.displayOptions(url), (err, result) ->
if err
deferred.reject(err)
else
deferred.fulfill(result)
)
sendResponseCallback(200, 'text/plain', deferred.promise)
catch err
Zotero.BetterBibTeX.log("Could not export bibliography '#{collection}", err)
sendResponseCallback(404, 'text/plain', "Could not export bibliography '#{collection}': #{err}")
Zotero.BetterBibTeX.endpoints.library = { supportedMethods: ['GET'] }
Zotero.BetterBibTeX.endpoints.library.init = (url, data, sendResponseCallback) ->
try
library = url.query['']
catch err
library = null
if not library
sendResponseCallback(501, 'text/plain', 'Could not export bibliography: no path')
return
try
params = /^\/?([0-9]+)?\/?library.(.*)$/.exec(library)
libid = params[1]
format = params[2]
if libid && not Zotero.Libraries.exists(libid)
sendResponseCallback(404, 'text/plain', "Could not export bibliography: library '#{library}' does not exist")
return
if !format
sendResponseCallback(404, 'text/plain', "Could not export bibliography '#{library}': no format specified")
return
translator = Zotero.BetterBibTeX.getTranslator(format)
if !translator
sendResponseCallback(404, 'text/plain', "Could not export bibliography '#{library}': unsupported format #{format}")
return
deferred = Q.defer()
Zotero.BetterBibTeX.translate(translator, {library: libid}, Zotero.BetterBibTeX.displayOptions(url), (err, result) ->
if err
deferred.reject(err)
else
deferred.fulfill(result)
)
sendResponseCallback(200, 'text/plain', deferred.promise)
catch err
Zotero.BetterBibTeX.log("Could not export bibliography '#{library}'", err)
sendResponseCallback(404, 'text/plain', "Could not export bibliography '#{library}': #{err}")
Zotero.BetterBibTeX.endpoints.selected = { supportedMethods: ['GET'] }
Zotero.BetterBibTeX.endpoints.selected.init = (url, data, sendResponseCallback) ->
try
translator = url.query['']
catch err
translator = null
if not translator
sendResponseCallback(501, 'text/plain', 'Could not export bibliography: no path')
return
zoteroPane = Zotero.getActiveZoteroPane()
items = Zotero.Items.get((item.id for item of zoteroPane.getSelectedItems()))
deferred = Q.defer()
Zotero.BetterBibTeX.translate(Zotero.BetterBibTeX.getTranslator(translator), {items: items}, Zotero.BetterBibTeX.displayOptions(url), (err, result) ->
if err
deferred.reject(err)
else
deferred.fulfill(result)
)
sendResponseCallback(200, 'text/plain', deferred.promise)
Zotero.BetterBibTeX.endpoints.schomd = { supportedMethods: ['POST'] }
Zotero.BetterBibTeX.endpoints.schomd.init = (url, data, sendResponseCallback) ->
req = JSON.parse(data)
response = []
throw new Error('batch requests are not supported') if Array.isArray(req)
try
switch req.method
when 'citations', 'citation', 'bibliography', 'bibliographyhtml', 'bibliographybbl', 'bibtex', 'search'
### the schomd methods search by citekey -- the cache needs to be fully primed for this to work ###
Zotero.BetterBibTeX.keymanager.prime()
result = Zotero.BetterBibTeX.schomd[req.method].apply(Zotero.BetterBibTeX.schomd, req.params)
if typeof result?.then == 'function'
result = result.then((result) ->
return JSON.stringify({
jsonrpc: (if req.jsonrpc then req.jsonrpc else undefined)
id: (if req.id || (typeof req.id) == 'number' then req.id else null)
result
})
).catch((e) ->
return JSON.stringify({
jsonrpc: (if req.jsonrpc then req.jsonrpc else undefined)
id: (if req.id || (typeof req.id) == 'number' then req.id else null)
result: e.message
})
)
else
result = JSON.stringify({
jsonrpc: (if req.jsonrpc then req.jsonrpc else undefined)
id: (if req.id || (typeof req.id) == 'number' then req.id else null)
result
})
else throw("Unsupported method '#{req.method}'")
catch err
result = JSON.stringify({jsonrpc: '2.0', error: {code: 5000, message: '' + err + "\n" + err.stack}, id: null})
return sendResponseCallback(200, 'application/json', result)
Zotero.BetterBibTeX.endpoints.cayw = { supportedMethods: ['GET'] }
Zotero.BetterBibTeX.endpoints.cayw.init = (url, data, sendResponseCallback) ->
if url.query.probe
sendResponseCallback(200, 'text/plain', 'ready')
return
doc = new Zotero.BetterBibTeX.CAYW.Document(url.query || {})
deferred = Q.defer()
io = new Zotero.BetterBibTeX.CAYW.CitationEditInterface(deferred, url.query || {}, doc)
if Zotero.Prefs.get('integration.useClassicAddCitationDialog')
Zotero.Integration.displayDialog(doc, 'chrome://zotero/content/integration/addCitationDialog.xul', 'alwaysRaised,resizable', io)
else
mode = if !Zotero.isMac and Zotero.Prefs.get('integration.keepAddCitationDialogRaised') then 'popup' else 'alwaysRaised'
Zotero.Integration.displayDialog(doc, 'chrome://zotero/content/integration/quickFormat.xul', mode, io)
sendResponseCallback(200, 'text/plain', deferred.promise)
Zotero.BetterBibTeX.endpoints.cacheActivity =
supportedMethods: ['GET']
init: (url, data, sendResponseCallback) ->
try
dataURL = url.query['']
catch err
dataURL = null
if dataURL
# someone thinks HTML-loaded javascripts are harmful. If that were true, you have bigger problems than this
# people.
return sendResponseCallback(200, 'text/html', Zotero.File.getContentsFromURL('resource://zotero-better-bibtex/reports/cacheActivity.txt'))
Zotero.BetterBibTeX.addCacheHistory()
timestamp = (date) ->
date = [date.getHours(), date.getMinutes(), date.getSeconds()]
date = (('0' + dp).slice(-2) for dp in date)
return date.join(':')
data = ([timestamp(dp.timestamp), dp.serialized.hit, dp.serialized.miss, dp.serialized.clear, dp.cache.hit, dp.cache.miss, dp.cache.clear] for dp in Zotero.BetterBibTeX.cacheHistory)
return sendResponseCallback(200, 'application/json', JSON.stringify(data))
| true | Zotero.BetterBibTeX.endpoints = { }
Zotero.BetterBibTeX.endpoints.collection = { supportedMethods: ['GET'] }
Zotero.BetterBibTeX.endpoints.collection.init = (url, data, sendResponseCallback) ->
try
collection = url.query['']
catch err
collection = null
if not collection
sendResponseCallback(501, 'text/plain', 'Could not export bibliography: no path')
return
try
path = collection.split('.')
if path.length == 1
sendResponseCallback(404, 'text/plain', "Could not export bibliography '#{collection}': no format specified")
return
translator = path.pop()
path = path.join('.')
path = "/0/#{path}" if path.charAt(0) != '/'
path = path.split('/')
### removes empty field before first '/' ###
path.shift()
libid = parseInt(path.shift())
throw "Not a valid library ID: #{collectionkey}" if isNaN(libid)
key = PI:KEY:<KEY>END_PI path[0]
col = null
for name in path
children = Zotero.getCollections(col?.id, false, libid)
col = null
for child in children
if child.name.toLowerCase() is name.toLowerCase()
col = child
break
if not col then break
col ||= Zotero.Collections.getByLibraryAndKey(libid, key)
throw "#{collectionkey} not found" unless col
deferred = Q.defer()
Zotero.BetterBibTeX.translate(Zotero.BetterBibTeX.getTranslator(translator), {collection: col}, Zotero.BetterBibTeX.displayOptions(url), (err, result) ->
if err
deferred.reject(err)
else
deferred.fulfill(result)
)
sendResponseCallback(200, 'text/plain', deferred.promise)
catch err
Zotero.BetterBibTeX.log("Could not export bibliography '#{collection}", err)
sendResponseCallback(404, 'text/plain', "Could not export bibliography '#{collection}': #{err}")
Zotero.BetterBibTeX.endpoints.library = { supportedMethods: ['GET'] }
Zotero.BetterBibTeX.endpoints.library.init = (url, data, sendResponseCallback) ->
try
library = url.query['']
catch err
library = null
if not library
sendResponseCallback(501, 'text/plain', 'Could not export bibliography: no path')
return
try
params = /^\/?([0-9]+)?\/?library.(.*)$/.exec(library)
libid = params[1]
format = params[2]
if libid && not Zotero.Libraries.exists(libid)
sendResponseCallback(404, 'text/plain', "Could not export bibliography: library '#{library}' does not exist")
return
if !format
sendResponseCallback(404, 'text/plain', "Could not export bibliography '#{library}': no format specified")
return
translator = Zotero.BetterBibTeX.getTranslator(format)
if !translator
sendResponseCallback(404, 'text/plain', "Could not export bibliography '#{library}': unsupported format #{format}")
return
deferred = Q.defer()
Zotero.BetterBibTeX.translate(translator, {library: libid}, Zotero.BetterBibTeX.displayOptions(url), (err, result) ->
if err
deferred.reject(err)
else
deferred.fulfill(result)
)
sendResponseCallback(200, 'text/plain', deferred.promise)
catch err
Zotero.BetterBibTeX.log("Could not export bibliography '#{library}'", err)
sendResponseCallback(404, 'text/plain', "Could not export bibliography '#{library}': #{err}")
Zotero.BetterBibTeX.endpoints.selected = { supportedMethods: ['GET'] }
Zotero.BetterBibTeX.endpoints.selected.init = (url, data, sendResponseCallback) ->
try
translator = url.query['']
catch err
translator = null
if not translator
sendResponseCallback(501, 'text/plain', 'Could not export bibliography: no path')
return
zoteroPane = Zotero.getActiveZoteroPane()
items = Zotero.Items.get((item.id for item of zoteroPane.getSelectedItems()))
deferred = Q.defer()
Zotero.BetterBibTeX.translate(Zotero.BetterBibTeX.getTranslator(translator), {items: items}, Zotero.BetterBibTeX.displayOptions(url), (err, result) ->
if err
deferred.reject(err)
else
deferred.fulfill(result)
)
sendResponseCallback(200, 'text/plain', deferred.promise)
Zotero.BetterBibTeX.endpoints.schomd = { supportedMethods: ['POST'] }
Zotero.BetterBibTeX.endpoints.schomd.init = (url, data, sendResponseCallback) ->
req = JSON.parse(data)
response = []
throw new Error('batch requests are not supported') if Array.isArray(req)
try
switch req.method
when 'citations', 'citation', 'bibliography', 'bibliographyhtml', 'bibliographybbl', 'bibtex', 'search'
### the schomd methods search by citekey -- the cache needs to be fully primed for this to work ###
Zotero.BetterBibTeX.keymanager.prime()
result = Zotero.BetterBibTeX.schomd[req.method].apply(Zotero.BetterBibTeX.schomd, req.params)
if typeof result?.then == 'function'
result = result.then((result) ->
return JSON.stringify({
jsonrpc: (if req.jsonrpc then req.jsonrpc else undefined)
id: (if req.id || (typeof req.id) == 'number' then req.id else null)
result
})
).catch((e) ->
return JSON.stringify({
jsonrpc: (if req.jsonrpc then req.jsonrpc else undefined)
id: (if req.id || (typeof req.id) == 'number' then req.id else null)
result: e.message
})
)
else
result = JSON.stringify({
jsonrpc: (if req.jsonrpc then req.jsonrpc else undefined)
id: (if req.id || (typeof req.id) == 'number' then req.id else null)
result
})
else throw("Unsupported method '#{req.method}'")
catch err
result = JSON.stringify({jsonrpc: '2.0', error: {code: 5000, message: '' + err + "\n" + err.stack}, id: null})
return sendResponseCallback(200, 'application/json', result)
Zotero.BetterBibTeX.endpoints.cayw = { supportedMethods: ['GET'] }
Zotero.BetterBibTeX.endpoints.cayw.init = (url, data, sendResponseCallback) ->
if url.query.probe
sendResponseCallback(200, 'text/plain', 'ready')
return
doc = new Zotero.BetterBibTeX.CAYW.Document(url.query || {})
deferred = Q.defer()
io = new Zotero.BetterBibTeX.CAYW.CitationEditInterface(deferred, url.query || {}, doc)
if Zotero.Prefs.get('integration.useClassicAddCitationDialog')
Zotero.Integration.displayDialog(doc, 'chrome://zotero/content/integration/addCitationDialog.xul', 'alwaysRaised,resizable', io)
else
mode = if !Zotero.isMac and Zotero.Prefs.get('integration.keepAddCitationDialogRaised') then 'popup' else 'alwaysRaised'
Zotero.Integration.displayDialog(doc, 'chrome://zotero/content/integration/quickFormat.xul', mode, io)
sendResponseCallback(200, 'text/plain', deferred.promise)
Zotero.BetterBibTeX.endpoints.cacheActivity =
supportedMethods: ['GET']
init: (url, data, sendResponseCallback) ->
try
dataURL = url.query['']
catch err
dataURL = null
if dataURL
# someone thinks HTML-loaded javascripts are harmful. If that were true, you have bigger problems than this
# people.
return sendResponseCallback(200, 'text/html', Zotero.File.getContentsFromURL('resource://zotero-better-bibtex/reports/cacheActivity.txt'))
Zotero.BetterBibTeX.addCacheHistory()
timestamp = (date) ->
date = [date.getHours(), date.getMinutes(), date.getSeconds()]
date = (('0' + dp).slice(-2) for dp in date)
return date.join(':')
data = ([timestamp(dp.timestamp), dp.serialized.hit, dp.serialized.miss, dp.serialized.clear, dp.cache.hit, dp.cache.miss, dp.cache.clear] for dp in Zotero.BetterBibTeX.cacheHistory)
return sendResponseCallback(200, 'application/json', JSON.stringify(data))
|
[
{
"context": "view Prevent usage of deprecated methods\n# @author Yannick Croissant\n# @author Scott Feeney\n# @author Sergei Startsev\n",
"end": 84,
"score": 0.9998761415481567,
"start": 67,
"tag": "NAME",
"value": "Yannick Croissant"
},
{
"context": "ated methods\n# @author Yannick Croissant\n# @author Scott Feeney\n# @author Sergei Startsev\n###\n'use strict'\n\n# ---",
"end": 107,
"score": 0.9998592138290405,
"start": 95,
"tag": "NAME",
"value": "Scott Feeney"
},
{
"context": "Yannick Croissant\n# @author Scott Feeney\n# @author Sergei Startsev\n###\n'use strict'\n\n# -----------------------------",
"end": 133,
"score": 0.9998844265937805,
"start": 118,
"tag": "NAME",
"value": "Sergei Startsev"
}
] | src/tests/rules/no-deprecated.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Prevent usage of deprecated methods
# @author Yannick Croissant
# @author Scott Feeney
# @author Sergei Startsev
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/no-deprecated'
{RuleTester} = require 'eslint'
path = require 'path'
errorMessage = (oldMethod, version, newMethod, refs) ->
newMethod = if newMethod then ", use #{newMethod} instead" else ''
refs = if refs then ", see #{refs}" else ''
"#{oldMethod} is deprecated since React #{version}#{newMethod}#{refs}"
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-deprecated', rule,
valid: [
# Not deprecated
"element = React.createElement('p', {}, null)"
'clone = React.cloneElement(element)'
'ReactDOM.render(element, container)'
'ReactDOM.unmountComponentAtNode(container)'
'ReactDOM.findDOMNode(instance)'
'ReactDOMServer.renderToString(element)'
'ReactDOMServer.renderToStaticMarkup(element)'
,
code: '''
Foo = createReactClass({
render: ->
})
'''
,
# Non-React
code: '''
Foo = createReactClassNonReact({
componentWillMount: ->,
componentWillReceiveProps: ->,
componentWillUpdate: ->
})
'''
,
code: '''
Foo = {
componentWillMount: ->,
componentWillReceiveProps: ->,
componentWillUpdate: ->
}
'''
,
code: '''
class Foo
constructor: ->
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
,
# Deprecated in a later version
code: 'React.renderComponent()', settings: react: version: '0.11.0'
,
code: 'React.createClass()', settings: react: version: '15.4.0'
,
code: 'PropTypes', settings: react: version: '15.4.0'
,
code: '''
class Foo extends React.Component
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
settings: react: version: '16.2.0'
]
invalid: [
code: 'React.renderComponent()'
errors: [
message: errorMessage 'React.renderComponent', '0.12.0', 'React.render'
]
,
code: 'Foo.renderComponent()'
settings: react: pragma: 'Foo'
errors: [
message: errorMessage 'Foo.renderComponent', '0.12.0', 'Foo.render'
]
,
code: '###* @jsx Foo ### Foo.renderComponent()'
errors: [
message: errorMessage 'Foo.renderComponent', '0.12.0', 'Foo.render'
]
,
code: 'this.transferPropsTo()'
errors: [
message: errorMessage(
'this.transferPropsTo'
'0.12.0'
'spread operator ({...})'
)
]
,
code: 'React.addons.TestUtils'
errors: [
message: errorMessage(
'React.addons.TestUtils'
'15.5.0'
'ReactDOM.TestUtils'
)
]
,
code: 'React.addons.classSet()'
errors: [
message: errorMessage(
'React.addons.classSet'
'0.13.0'
'the npm module classnames'
)
]
,
code: 'React.render(element, container)'
errors: [message: errorMessage 'React.render', '0.14.0', 'ReactDOM.render']
,
code: 'React.unmountComponentAtNode(container)'
errors: [
message: errorMessage(
'React.unmountComponentAtNode'
'0.14.0'
'ReactDOM.unmountComponentAtNode'
)
]
,
code: 'React.findDOMNode(instance)'
errors: [
message: errorMessage(
'React.findDOMNode'
'0.14.0'
'ReactDOM.findDOMNode'
)
]
,
code: 'React.renderToString(element)'
errors: [
message: errorMessage(
'React.renderToString'
'0.14.0'
'ReactDOMServer.renderToString'
)
]
,
code: 'React.renderToStaticMarkup(element)'
errors: [
message: errorMessage(
'React.renderToStaticMarkup'
'0.14.0'
'ReactDOMServer.renderToStaticMarkup'
)
]
,
code: 'React.createClass({})'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
]
,
code: 'Foo.createClass({})'
settings: react: pragma: 'Foo'
errors: [
message: errorMessage(
'Foo.createClass'
'15.5.0'
'the npm module create-react-class'
)
]
,
code: 'React.PropTypes'
errors: [
message: errorMessage(
'React.PropTypes'
'15.5.0'
'the npm module prop-types'
)
]
,
code: "{createClass} = require('react')"
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
]
,
code: "{createClass, PropTypes} = require('react')"
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
,
message: errorMessage(
'React.PropTypes'
'15.5.0'
'the npm module prop-types'
)
]
,
code: "import {createClass} from 'react'"
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
]
,
code: "import {createClass, PropTypes} from 'react'"
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
,
message: errorMessage(
'React.PropTypes'
'15.5.0'
'the npm module prop-types'
)
]
,
code: '''
import React from 'react'
{createClass, PropTypes} = React
'''
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
,
message: errorMessage(
'React.PropTypes'
'15.5.0'
'the npm module prop-types'
)
]
,
code: "import {printDOM} from 'react-addons-perf'"
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'ReactPerf.printDOM'
'15.0.0'
'ReactPerf.printOperations'
)
]
,
code: '''
import ReactPerf from 'react-addons-perf'
{printDOM} = ReactPerf
'''
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'ReactPerf.printDOM'
'15.0.0'
'ReactPerf.printOperations'
)
]
,
code: 'React.DOM.div'
errors: [
message: errorMessage(
'React.DOM'
'15.6.0'
'the npm module react-dom-factories'
)
]
,
code: '''
class Bar extends React.PureComponent
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 2
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 4
column: 3
]
,
code: '''
Foo = ->
class Bar extends React.PureComponent
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 3
column: 5
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 4
column: 5
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 5
column: 5
]
,
code: '''
class Bar extends PureComponent
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 2
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 4
column: 3
]
,
code: '''
class Foo extends React.Component
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 2
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 4
column: 3
]
,
code: '''
class Foo extends Component
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 2
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 4
column: 3
]
,
code: '''
Foo = createReactClass({
componentWillMount: ->,
componentWillReceiveProps: ->,
componentWillUpdate: ->
})
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 2
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 4
column: 3
]
,
code: '''
class Foo extends React.Component
constructor: ->
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 4
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 5
column: 3
]
]
| 8420 | ###*
# @fileoverview Prevent usage of deprecated methods
# @author <NAME>
# @author <NAME>
# @author <NAME>
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/no-deprecated'
{RuleTester} = require 'eslint'
path = require 'path'
errorMessage = (oldMethod, version, newMethod, refs) ->
newMethod = if newMethod then ", use #{newMethod} instead" else ''
refs = if refs then ", see #{refs}" else ''
"#{oldMethod} is deprecated since React #{version}#{newMethod}#{refs}"
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-deprecated', rule,
valid: [
# Not deprecated
"element = React.createElement('p', {}, null)"
'clone = React.cloneElement(element)'
'ReactDOM.render(element, container)'
'ReactDOM.unmountComponentAtNode(container)'
'ReactDOM.findDOMNode(instance)'
'ReactDOMServer.renderToString(element)'
'ReactDOMServer.renderToStaticMarkup(element)'
,
code: '''
Foo = createReactClass({
render: ->
})
'''
,
# Non-React
code: '''
Foo = createReactClassNonReact({
componentWillMount: ->,
componentWillReceiveProps: ->,
componentWillUpdate: ->
})
'''
,
code: '''
Foo = {
componentWillMount: ->,
componentWillReceiveProps: ->,
componentWillUpdate: ->
}
'''
,
code: '''
class Foo
constructor: ->
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
,
# Deprecated in a later version
code: 'React.renderComponent()', settings: react: version: '0.11.0'
,
code: 'React.createClass()', settings: react: version: '15.4.0'
,
code: 'PropTypes', settings: react: version: '15.4.0'
,
code: '''
class Foo extends React.Component
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
settings: react: version: '16.2.0'
]
invalid: [
code: 'React.renderComponent()'
errors: [
message: errorMessage 'React.renderComponent', '0.12.0', 'React.render'
]
,
code: 'Foo.renderComponent()'
settings: react: pragma: 'Foo'
errors: [
message: errorMessage 'Foo.renderComponent', '0.12.0', 'Foo.render'
]
,
code: '###* @jsx Foo ### Foo.renderComponent()'
errors: [
message: errorMessage 'Foo.renderComponent', '0.12.0', 'Foo.render'
]
,
code: 'this.transferPropsTo()'
errors: [
message: errorMessage(
'this.transferPropsTo'
'0.12.0'
'spread operator ({...})'
)
]
,
code: 'React.addons.TestUtils'
errors: [
message: errorMessage(
'React.addons.TestUtils'
'15.5.0'
'ReactDOM.TestUtils'
)
]
,
code: 'React.addons.classSet()'
errors: [
message: errorMessage(
'React.addons.classSet'
'0.13.0'
'the npm module classnames'
)
]
,
code: 'React.render(element, container)'
errors: [message: errorMessage 'React.render', '0.14.0', 'ReactDOM.render']
,
code: 'React.unmountComponentAtNode(container)'
errors: [
message: errorMessage(
'React.unmountComponentAtNode'
'0.14.0'
'ReactDOM.unmountComponentAtNode'
)
]
,
code: 'React.findDOMNode(instance)'
errors: [
message: errorMessage(
'React.findDOMNode'
'0.14.0'
'ReactDOM.findDOMNode'
)
]
,
code: 'React.renderToString(element)'
errors: [
message: errorMessage(
'React.renderToString'
'0.14.0'
'ReactDOMServer.renderToString'
)
]
,
code: 'React.renderToStaticMarkup(element)'
errors: [
message: errorMessage(
'React.renderToStaticMarkup'
'0.14.0'
'ReactDOMServer.renderToStaticMarkup'
)
]
,
code: 'React.createClass({})'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
]
,
code: 'Foo.createClass({})'
settings: react: pragma: 'Foo'
errors: [
message: errorMessage(
'Foo.createClass'
'15.5.0'
'the npm module create-react-class'
)
]
,
code: 'React.PropTypes'
errors: [
message: errorMessage(
'React.PropTypes'
'15.5.0'
'the npm module prop-types'
)
]
,
code: "{createClass} = require('react')"
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
]
,
code: "{createClass, PropTypes} = require('react')"
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
,
message: errorMessage(
'React.PropTypes'
'15.5.0'
'the npm module prop-types'
)
]
,
code: "import {createClass} from 'react'"
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
]
,
code: "import {createClass, PropTypes} from 'react'"
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
,
message: errorMessage(
'React.PropTypes'
'15.5.0'
'the npm module prop-types'
)
]
,
code: '''
import React from 'react'
{createClass, PropTypes} = React
'''
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
,
message: errorMessage(
'React.PropTypes'
'15.5.0'
'the npm module prop-types'
)
]
,
code: "import {printDOM} from 'react-addons-perf'"
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'ReactPerf.printDOM'
'15.0.0'
'ReactPerf.printOperations'
)
]
,
code: '''
import ReactPerf from 'react-addons-perf'
{printDOM} = ReactPerf
'''
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'ReactPerf.printDOM'
'15.0.0'
'ReactPerf.printOperations'
)
]
,
code: 'React.DOM.div'
errors: [
message: errorMessage(
'React.DOM'
'15.6.0'
'the npm module react-dom-factories'
)
]
,
code: '''
class Bar extends React.PureComponent
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 2
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 4
column: 3
]
,
code: '''
Foo = ->
class Bar extends React.PureComponent
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 3
column: 5
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 4
column: 5
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 5
column: 5
]
,
code: '''
class Bar extends PureComponent
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 2
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 4
column: 3
]
,
code: '''
class Foo extends React.Component
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 2
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 4
column: 3
]
,
code: '''
class Foo extends Component
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 2
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 4
column: 3
]
,
code: '''
Foo = createReactClass({
componentWillMount: ->,
componentWillReceiveProps: ->,
componentWillUpdate: ->
})
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 2
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 4
column: 3
]
,
code: '''
class Foo extends React.Component
constructor: ->
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 4
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 5
column: 3
]
]
| true | ###*
# @fileoverview Prevent usage of deprecated methods
# @author PI:NAME:<NAME>END_PI
# @author PI:NAME:<NAME>END_PI
# @author PI:NAME:<NAME>END_PI
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/no-deprecated'
{RuleTester} = require 'eslint'
path = require 'path'
errorMessage = (oldMethod, version, newMethod, refs) ->
newMethod = if newMethod then ", use #{newMethod} instead" else ''
refs = if refs then ", see #{refs}" else ''
"#{oldMethod} is deprecated since React #{version}#{newMethod}#{refs}"
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-deprecated', rule,
valid: [
# Not deprecated
"element = React.createElement('p', {}, null)"
'clone = React.cloneElement(element)'
'ReactDOM.render(element, container)'
'ReactDOM.unmountComponentAtNode(container)'
'ReactDOM.findDOMNode(instance)'
'ReactDOMServer.renderToString(element)'
'ReactDOMServer.renderToStaticMarkup(element)'
,
code: '''
Foo = createReactClass({
render: ->
})
'''
,
# Non-React
code: '''
Foo = createReactClassNonReact({
componentWillMount: ->,
componentWillReceiveProps: ->,
componentWillUpdate: ->
})
'''
,
code: '''
Foo = {
componentWillMount: ->,
componentWillReceiveProps: ->,
componentWillUpdate: ->
}
'''
,
code: '''
class Foo
constructor: ->
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
,
# Deprecated in a later version
code: 'React.renderComponent()', settings: react: version: '0.11.0'
,
code: 'React.createClass()', settings: react: version: '15.4.0'
,
code: 'PropTypes', settings: react: version: '15.4.0'
,
code: '''
class Foo extends React.Component
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
settings: react: version: '16.2.0'
]
invalid: [
code: 'React.renderComponent()'
errors: [
message: errorMessage 'React.renderComponent', '0.12.0', 'React.render'
]
,
code: 'Foo.renderComponent()'
settings: react: pragma: 'Foo'
errors: [
message: errorMessage 'Foo.renderComponent', '0.12.0', 'Foo.render'
]
,
code: '###* @jsx Foo ### Foo.renderComponent()'
errors: [
message: errorMessage 'Foo.renderComponent', '0.12.0', 'Foo.render'
]
,
code: 'this.transferPropsTo()'
errors: [
message: errorMessage(
'this.transferPropsTo'
'0.12.0'
'spread operator ({...})'
)
]
,
code: 'React.addons.TestUtils'
errors: [
message: errorMessage(
'React.addons.TestUtils'
'15.5.0'
'ReactDOM.TestUtils'
)
]
,
code: 'React.addons.classSet()'
errors: [
message: errorMessage(
'React.addons.classSet'
'0.13.0'
'the npm module classnames'
)
]
,
code: 'React.render(element, container)'
errors: [message: errorMessage 'React.render', '0.14.0', 'ReactDOM.render']
,
code: 'React.unmountComponentAtNode(container)'
errors: [
message: errorMessage(
'React.unmountComponentAtNode'
'0.14.0'
'ReactDOM.unmountComponentAtNode'
)
]
,
code: 'React.findDOMNode(instance)'
errors: [
message: errorMessage(
'React.findDOMNode'
'0.14.0'
'ReactDOM.findDOMNode'
)
]
,
code: 'React.renderToString(element)'
errors: [
message: errorMessage(
'React.renderToString'
'0.14.0'
'ReactDOMServer.renderToString'
)
]
,
code: 'React.renderToStaticMarkup(element)'
errors: [
message: errorMessage(
'React.renderToStaticMarkup'
'0.14.0'
'ReactDOMServer.renderToStaticMarkup'
)
]
,
code: 'React.createClass({})'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
]
,
code: 'Foo.createClass({})'
settings: react: pragma: 'Foo'
errors: [
message: errorMessage(
'Foo.createClass'
'15.5.0'
'the npm module create-react-class'
)
]
,
code: 'React.PropTypes'
errors: [
message: errorMessage(
'React.PropTypes'
'15.5.0'
'the npm module prop-types'
)
]
,
code: "{createClass} = require('react')"
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
]
,
code: "{createClass, PropTypes} = require('react')"
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
,
message: errorMessage(
'React.PropTypes'
'15.5.0'
'the npm module prop-types'
)
]
,
code: "import {createClass} from 'react'"
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
]
,
code: "import {createClass, PropTypes} from 'react'"
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
,
message: errorMessage(
'React.PropTypes'
'15.5.0'
'the npm module prop-types'
)
]
,
code: '''
import React from 'react'
{createClass, PropTypes} = React
'''
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'React.createClass'
'15.5.0'
'the npm module create-react-class'
)
,
message: errorMessage(
'React.PropTypes'
'15.5.0'
'the npm module prop-types'
)
]
,
code: "import {printDOM} from 'react-addons-perf'"
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'ReactPerf.printDOM'
'15.0.0'
'ReactPerf.printOperations'
)
]
,
code: '''
import ReactPerf from 'react-addons-perf'
{printDOM} = ReactPerf
'''
# parser: 'babel-eslint'
errors: [
message: errorMessage(
'ReactPerf.printDOM'
'15.0.0'
'ReactPerf.printOperations'
)
]
,
code: 'React.DOM.div'
errors: [
message: errorMessage(
'React.DOM'
'15.6.0'
'the npm module react-dom-factories'
)
]
,
code: '''
class Bar extends React.PureComponent
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 2
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 4
column: 3
]
,
code: '''
Foo = ->
class Bar extends React.PureComponent
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 3
column: 5
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 4
column: 5
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 5
column: 5
]
,
code: '''
class Bar extends PureComponent
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 2
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 4
column: 3
]
,
code: '''
class Foo extends React.Component
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 2
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 4
column: 3
]
,
code: '''
class Foo extends Component
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 2
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 4
column: 3
]
,
code: '''
Foo = createReactClass({
componentWillMount: ->,
componentWillReceiveProps: ->,
componentWillUpdate: ->
})
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 2
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 4
column: 3
]
,
code: '''
class Foo extends React.Component
constructor: ->
componentWillMount: ->
componentWillReceiveProps: ->
componentWillUpdate: ->
'''
errors: [
message: errorMessage(
'componentWillMount'
'16.3.0'
'UNSAFE_componentWillMount'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount'
)
type: 'Identifier'
line: 3
column: 3
,
message: errorMessage(
'componentWillReceiveProps'
'16.3.0'
'UNSAFE_componentWillReceiveProps'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops'
)
type: 'Identifier'
line: 4
column: 3
,
message: errorMessage(
'componentWillUpdate'
'16.3.0'
'UNSAFE_componentWillUpdate'
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate'
)
type: 'Identifier'
line: 5
column: 3
]
]
|
[
{
"context": "application/json\"}\n opts.json =\n userName: userName\n password: password\n displayName: displ",
"end": 353,
"score": 0.9993894100189209,
"start": 345,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "ts.json =\n userName: userName\n password: password\n displayName: displayName\n request('POST'",
"end": 378,
"score": 0.9990354776382446,
"start": 370,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "application/json\"}\n opts.json =\n userName: userName\n password: password\n request('POST', \"log",
"end": 697,
"score": 0.9993624091148376,
"start": 689,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "ts.json =\n userName: userName\n password: password\n request('POST', \"login_user\", opts).done( (re",
"end": 722,
"score": 0.9991084337234497,
"start": 714,
"tag": "PASSWORD",
"value": "password"
}
] | webfe/src/services/AuthService.coffee | pequalsnp/portroyal | 2 | request = require 'then-request'
AppDispatcher = require '../AppDispatcher.coffee'
Constants = require '../constants/Constants.coffee'
LoginAction = require '../actions/LoginAction.coffee'
AuthService =
createUser: (userName, password, displayName) ->
opts =
headers: {"Accept": "application/json"}
opts.json =
userName: userName
password: password
displayName: displayName
request('POST', "create_user", opts).done( (res) ->
data = JSON.parse(res.body)
LoginAction.loginUser(data.jwt, data.displayName)
)
loginUser: (userName, password) ->
opts =
headers: {"Accept": "application/json"}
opts.json =
userName: userName
password: password
request('POST', "login_user", opts).done( (res) ->
data = JSON.parse(res.body)
LoginAction.loginUser(data.jwt, data.displayName)
)
logout: ->
LoginAction.logout()
module.exports = AuthService
| 176416 | request = require 'then-request'
AppDispatcher = require '../AppDispatcher.coffee'
Constants = require '../constants/Constants.coffee'
LoginAction = require '../actions/LoginAction.coffee'
AuthService =
createUser: (userName, password, displayName) ->
opts =
headers: {"Accept": "application/json"}
opts.json =
userName: userName
password: <PASSWORD>
displayName: displayName
request('POST', "create_user", opts).done( (res) ->
data = JSON.parse(res.body)
LoginAction.loginUser(data.jwt, data.displayName)
)
loginUser: (userName, password) ->
opts =
headers: {"Accept": "application/json"}
opts.json =
userName: userName
password: <PASSWORD>
request('POST', "login_user", opts).done( (res) ->
data = JSON.parse(res.body)
LoginAction.loginUser(data.jwt, data.displayName)
)
logout: ->
LoginAction.logout()
module.exports = AuthService
| true | request = require 'then-request'
AppDispatcher = require '../AppDispatcher.coffee'
Constants = require '../constants/Constants.coffee'
LoginAction = require '../actions/LoginAction.coffee'
AuthService =
createUser: (userName, password, displayName) ->
opts =
headers: {"Accept": "application/json"}
opts.json =
userName: userName
password: PI:PASSWORD:<PASSWORD>END_PI
displayName: displayName
request('POST', "create_user", opts).done( (res) ->
data = JSON.parse(res.body)
LoginAction.loginUser(data.jwt, data.displayName)
)
loginUser: (userName, password) ->
opts =
headers: {"Accept": "application/json"}
opts.json =
userName: userName
password: PI:PASSWORD:<PASSWORD>END_PI
request('POST', "login_user", opts).done( (res) ->
data = JSON.parse(res.body)
LoginAction.loginUser(data.jwt, data.displayName)
)
logout: ->
LoginAction.logout()
module.exports = AuthService
|
[
{
"context": "ode version.\n#\n# In Node < v0.12, it's:\n# [ 'google-site-verification=TdBjb4jFf-AMZNGvm5BcqvoksmlJ_8G22ARdJp8jLgk',\n# ",
"end": 455,
"score": 0.9457961916923523,
"start": 430,
"tag": "KEY",
"value": "google-site-verification="
},
{
"context": " < v0.12, it's:\n# [ 'google-site-verification=TdBjb4jFf-AMZNGvm5BcqvoksmlJ_8G22ARdJp8jLgk',\n# 'keybase-site-verification=uqzZedLr4yVI",
"end": 498,
"score": 0.9996204376220703,
"start": 455,
"tag": "KEY",
"value": "TdBjb4jFf-AMZNGvm5BcqvoksmlJ_8G22ARdJp8jLgk"
},
{
"context": "f-AMZNGvm5BcqvoksmlJ_8G22ARdJp8jLgk',\n# 'keybase-site-verification=uqzZedLr4yVILSkh6nLfctv5oxrqpp8rFLHsz-0xxy4' ]\n#\n#",
"end": 536,
"score": 0.8457085490226746,
"start": 513,
"tag": "KEY",
"value": "base-site-verification="
},
{
"context": "22ARdJp8jLgk',\n# 'keybase-site-verification=uqzZedLr4yVILSkh6nLfctv5oxrqpp8rFLHsz-0xxy4' ]\n#\n# In Node >= v0.12, it's:\n# [ [ 'google",
"end": 579,
"score": 0.9996188282966614,
"start": 536,
"tag": "KEY",
"value": "uqzZedLr4yVILSkh6nLfctv5oxrqpp8rFLHsz-0xxy4"
},
{
"context": "-0xxy4' ]\n#\n# In Node >= v0.12, it's:\n# [ [ 'google-site-verification=TdBjb4jFf-AMZNGvm5BcqvoksmlJ_8G22ARdJp8jLgk' ],\n# ",
"end": 648,
"score": 0.9414370059967041,
"start": 623,
"tag": "KEY",
"value": "google-site-verification="
},
{
"context": " v0.12, it's:\n# [ [ 'google-site-verification=TdBjb4jFf-AMZNGvm5BcqvoksmlJ_8G22ARdJp8jLgk' ],\n# [ 'keybase-site-verification=uqzZedLr",
"end": 691,
"score": 0.999594509601593,
"start": 648,
"tag": "KEY",
"value": "TdBjb4jFf-AMZNGvm5BcqvoksmlJ_8G22ARdJp8jLgk"
},
{
"context": "ZNGvm5BcqvoksmlJ_8G22ARdJp8jLgk' ],\n# [ 'keybase-site-verification=uqzZedLr4yVILSkh6nLfctv5oxrqpp8rFLHsz-0xxy4' ] ]\n#",
"end": 733,
"score": 0.9437932968139648,
"start": 710,
"tag": "KEY",
"value": "base-site-verification="
},
{
"context": "dJp8jLgk' ],\n# [ 'keybase-site-verification=uqzZedLr4yVILSkh6nLfctv5oxrqpp8rFLHsz-0xxy4' ] ]\n#\n# This method reformats the results into ",
"end": 776,
"score": 0.9996532797813416,
"start": 733,
"tag": "KEY",
"value": "uqzZedLr4yVILSkh6nLfctv5oxrqpp8rFLHsz-0xxy4"
}
] | src/scrapers/dns.iced | jeremyBanks/keybase-proofs | 151 | {BaseScraper} = require './base'
{constants} = require '../constants'
{v_codes} = constants
{decode_sig} = require('kbpgp').ukm
urlmod = require 'url'
{make_ids} = require '../base'
urlmod = require 'url'
dns = require 'dns'
#================================================================================
#
# TXT records come back from node in different formats depending on node version.
#
# In Node < v0.12, it's:
# [ 'google-site-verification=TdBjb4jFf-AMZNGvm5BcqvoksmlJ_8G22ARdJp8jLgk',
# 'keybase-site-verification=uqzZedLr4yVILSkh6nLfctv5oxrqpp8rFLHsz-0xxy4' ]
#
# In Node >= v0.12, it's:
# [ [ 'google-site-verification=TdBjb4jFf-AMZNGvm5BcqvoksmlJ_8G22ARdJp8jLgk' ],
# [ 'keybase-site-verification=uqzZedLr4yVILSkh6nLfctv5oxrqpp8rFLHsz-0xxy4' ] ]
#
# This method reformats the results into Node < 0.12.0 style
#
txt_reformat = (v) ->
if not v? then []
else if v.length is 0 then v
else if Array.isArray(v[0]) then (sv[0] for sv in v)
else v
#================================================================================
exports.DnsScraper = class DnsScraper extends BaseScraper
# ---------------------------------------------------------------------------
constructor: (opts) ->
super opts
# ---------------------------------------------------------------------------
_check_args : (args) ->
if not (args.domain?) then new Error "Bad args to DNS proof: no domain given"
else null
# ---------------------------------------------------------------------------
make_url : ({domain}) -> "dns://#{domain.toLowerCase()}"
url_to_domain : (u) -> urlmod.parse(u)?.hostname
get_tor_error : () -> [ new Error("DNS isn't reliable over tor"), v_codes.TOR_SKIPPED ]
# ---------------------------------------------------------------------------
hunt2 : ({domain}, cb) ->
err = null
out = {}
if not domain?
err = new Error "invalid arguments: expected a domain"
else
url = @make_url { domain }
out =
api_url : url
human_url : url
remote_id : url
rc : v_codes.OK
cb err, out
# ---------------------------------------------------------------------------
_check_api_url : ({api_url,domain}) ->
return (api_url.toLowerCase().indexOf(@make_url {domain}) >= 0)
# ---------------------------------------------------------------------------
# Given a validated signature, check that the payload_text_check matches the sig.
_validate_text_check : ({signature, proof_text_check }) ->
[err, msg] = decode_sig { armored: signature }
if not err?
{med_id} = make_ids msg.body
if proof_text_check.indexOf(med_id) < 0
err = new Error "Bad payload text_check"
return err
# ---------------------------------------------------------------------------
check_status : ({api_url, proof_text_check}, cb) ->
rc = err = null
if not (domain = @url_to_domain(api_url))?
err = new Error "no domain found in URL #{api_url}"
rc = v_codes.CONTENT_FAILURE
else
search_domains = [ domain, [ "_keybase", domain].join(".") ]
for d in search_domains
await @_check_status { domain : d, proof_text_check }, defer err, rc
break if (rc is v_codes.OK)
cb err, rc
# ---------------------------------------------------------------------------
# calls back with a v_code or null if it was ok
_check_status: ({domain, proof_text_check}, cb) ->
@log "+ DNS check for #{domain}"
# We can use a DNS library passed in (in the case of native-dns running on the server)
dnslib = @libs.dns or dns
await dnslib.resolveTxt domain, defer err, records
rc = if err?
@log "| DNS error: #{err}"
v_codes.DNS_ERROR
else if (proof_text_check in txt_reformat(records)) then v_codes.OK
else
@log "| DNS failed; found TXT entries: #{JSON.stringify records}"
v_codes.NOT_FOUND
@log "- DNS check for #{domain} -> #{rc}"
cb err, rc
#================================================================================
| 102602 | {BaseScraper} = require './base'
{constants} = require '../constants'
{v_codes} = constants
{decode_sig} = require('kbpgp').ukm
urlmod = require 'url'
{make_ids} = require '../base'
urlmod = require 'url'
dns = require 'dns'
#================================================================================
#
# TXT records come back from node in different formats depending on node version.
#
# In Node < v0.12, it's:
# [ '<KEY> <KEY>',
# 'key<KEY> <KEY>' ]
#
# In Node >= v0.12, it's:
# [ [ '<KEY> <KEY>' ],
# [ 'key<KEY> <KEY>' ] ]
#
# This method reformats the results into Node < 0.12.0 style
#
txt_reformat = (v) ->
if not v? then []
else if v.length is 0 then v
else if Array.isArray(v[0]) then (sv[0] for sv in v)
else v
#================================================================================
exports.DnsScraper = class DnsScraper extends BaseScraper
# ---------------------------------------------------------------------------
constructor: (opts) ->
super opts
# ---------------------------------------------------------------------------
_check_args : (args) ->
if not (args.domain?) then new Error "Bad args to DNS proof: no domain given"
else null
# ---------------------------------------------------------------------------
make_url : ({domain}) -> "dns://#{domain.toLowerCase()}"
url_to_domain : (u) -> urlmod.parse(u)?.hostname
get_tor_error : () -> [ new Error("DNS isn't reliable over tor"), v_codes.TOR_SKIPPED ]
# ---------------------------------------------------------------------------
hunt2 : ({domain}, cb) ->
err = null
out = {}
if not domain?
err = new Error "invalid arguments: expected a domain"
else
url = @make_url { domain }
out =
api_url : url
human_url : url
remote_id : url
rc : v_codes.OK
cb err, out
# ---------------------------------------------------------------------------
_check_api_url : ({api_url,domain}) ->
return (api_url.toLowerCase().indexOf(@make_url {domain}) >= 0)
# ---------------------------------------------------------------------------
# Given a validated signature, check that the payload_text_check matches the sig.
_validate_text_check : ({signature, proof_text_check }) ->
[err, msg] = decode_sig { armored: signature }
if not err?
{med_id} = make_ids msg.body
if proof_text_check.indexOf(med_id) < 0
err = new Error "Bad payload text_check"
return err
# ---------------------------------------------------------------------------
check_status : ({api_url, proof_text_check}, cb) ->
rc = err = null
if not (domain = @url_to_domain(api_url))?
err = new Error "no domain found in URL #{api_url}"
rc = v_codes.CONTENT_FAILURE
else
search_domains = [ domain, [ "_keybase", domain].join(".") ]
for d in search_domains
await @_check_status { domain : d, proof_text_check }, defer err, rc
break if (rc is v_codes.OK)
cb err, rc
# ---------------------------------------------------------------------------
# calls back with a v_code or null if it was ok
_check_status: ({domain, proof_text_check}, cb) ->
@log "+ DNS check for #{domain}"
# We can use a DNS library passed in (in the case of native-dns running on the server)
dnslib = @libs.dns or dns
await dnslib.resolveTxt domain, defer err, records
rc = if err?
@log "| DNS error: #{err}"
v_codes.DNS_ERROR
else if (proof_text_check in txt_reformat(records)) then v_codes.OK
else
@log "| DNS failed; found TXT entries: #{JSON.stringify records}"
v_codes.NOT_FOUND
@log "- DNS check for #{domain} -> #{rc}"
cb err, rc
#================================================================================
| true | {BaseScraper} = require './base'
{constants} = require '../constants'
{v_codes} = constants
{decode_sig} = require('kbpgp').ukm
urlmod = require 'url'
{make_ids} = require '../base'
urlmod = require 'url'
dns = require 'dns'
#================================================================================
#
# TXT records come back from node in different formats depending on node version.
#
# In Node < v0.12, it's:
# [ 'PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI',
# 'keyPI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI' ]
#
# In Node >= v0.12, it's:
# [ [ 'PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI' ],
# [ 'keyPI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI' ] ]
#
# This method reformats the results into Node < 0.12.0 style
#
txt_reformat = (v) ->
if not v? then []
else if v.length is 0 then v
else if Array.isArray(v[0]) then (sv[0] for sv in v)
else v
#================================================================================
exports.DnsScraper = class DnsScraper extends BaseScraper
# ---------------------------------------------------------------------------
constructor: (opts) ->
super opts
# ---------------------------------------------------------------------------
_check_args : (args) ->
if not (args.domain?) then new Error "Bad args to DNS proof: no domain given"
else null
# ---------------------------------------------------------------------------
make_url : ({domain}) -> "dns://#{domain.toLowerCase()}"
url_to_domain : (u) -> urlmod.parse(u)?.hostname
get_tor_error : () -> [ new Error("DNS isn't reliable over tor"), v_codes.TOR_SKIPPED ]
# ---------------------------------------------------------------------------
hunt2 : ({domain}, cb) ->
err = null
out = {}
if not domain?
err = new Error "invalid arguments: expected a domain"
else
url = @make_url { domain }
out =
api_url : url
human_url : url
remote_id : url
rc : v_codes.OK
cb err, out
# ---------------------------------------------------------------------------
_check_api_url : ({api_url,domain}) ->
return (api_url.toLowerCase().indexOf(@make_url {domain}) >= 0)
# ---------------------------------------------------------------------------
# Given a validated signature, check that the payload_text_check matches the sig.
_validate_text_check : ({signature, proof_text_check }) ->
[err, msg] = decode_sig { armored: signature }
if not err?
{med_id} = make_ids msg.body
if proof_text_check.indexOf(med_id) < 0
err = new Error "Bad payload text_check"
return err
# ---------------------------------------------------------------------------
check_status : ({api_url, proof_text_check}, cb) ->
rc = err = null
if not (domain = @url_to_domain(api_url))?
err = new Error "no domain found in URL #{api_url}"
rc = v_codes.CONTENT_FAILURE
else
search_domains = [ domain, [ "_keybase", domain].join(".") ]
for d in search_domains
await @_check_status { domain : d, proof_text_check }, defer err, rc
break if (rc is v_codes.OK)
cb err, rc
# ---------------------------------------------------------------------------
# calls back with a v_code or null if it was ok
_check_status: ({domain, proof_text_check}, cb) ->
@log "+ DNS check for #{domain}"
# We can use a DNS library passed in (in the case of native-dns running on the server)
dnslib = @libs.dns or dns
await dnslib.resolveTxt domain, defer err, records
rc = if err?
@log "| DNS error: #{err}"
v_codes.DNS_ERROR
else if (proof_text_check in txt_reformat(records)) then v_codes.OK
else
@log "| DNS failed; found TXT entries: #{JSON.stringify records}"
v_codes.NOT_FOUND
@log "- DNS check for #{domain} -> #{rc}"
cb err, rc
#================================================================================
|
[
{
"context": "version v3.0.3\"\n \" * @link https://github.com/bymathias/normalize.styl\"\n \" * @author Nicolas Gallagher,",
"end": 593,
"score": 0.9099522233009338,
"start": 584,
"tag": "USERNAME",
"value": "bymathias"
},
{
"context": "ithub.com/bymathias/normalize.styl\"\n \" * @author Nicolas Gallagher, Mathias Brouilly\"\n \" * @license MIT\"\n \" */\"\n ",
"end": 642,
"score": 0.9998624920845032,
"start": 625,
"tag": "NAME",
"value": "Nicolas Gallagher"
},
{
"context": "/normalize.styl\"\n \" * @author Nicolas Gallagher, Mathias Brouilly\"\n \" * @license MIT\"\n \" */\"\n \"\"\n].join(\"\\n\")\n\ns",
"end": 660,
"score": 0.9998502731323242,
"start": 644,
"tag": "NAME",
"value": "Mathias Brouilly"
}
] | tasks/stylus_normalize.coffee | gnicolasarroyo/ZEN.UI | 0 | "use strict"
concat = require "gulp-concat"
header = require "gulp-header"
stylus = require "gulp-stylus"
pkg = require "./../package.json"
banner = [
"/**"
" * normalize.css - Normalize.css is a customisable CSS file that makes browsers render all elements more consistently and in line with modern standards. The project relies on researching the differences between default browser styles in order to precisely target only the styles that need or benefit from normalizing."
" * @source zen.ui.normalize.css"
" * @version v3.0.3"
" * @link https://github.com/bymathias/normalize.styl"
" * @author Nicolas Gallagher, Mathias Brouilly"
" * @license MIT"
" */"
""
].join("\n")
source = [
"source/stylus/normalize.styl"
]
module.exports = (_gulp)->
_gulp.src source
.pipe concat "zen.ui.normalize.styl"
.pipe stylus
compress: true
errors : true
.pipe header banner, pkg: pkg
.pipe _gulp.dest "build/css/"
| 120090 | "use strict"
concat = require "gulp-concat"
header = require "gulp-header"
stylus = require "gulp-stylus"
pkg = require "./../package.json"
banner = [
"/**"
" * normalize.css - Normalize.css is a customisable CSS file that makes browsers render all elements more consistently and in line with modern standards. The project relies on researching the differences between default browser styles in order to precisely target only the styles that need or benefit from normalizing."
" * @source zen.ui.normalize.css"
" * @version v3.0.3"
" * @link https://github.com/bymathias/normalize.styl"
" * @author <NAME>, <NAME>"
" * @license MIT"
" */"
""
].join("\n")
source = [
"source/stylus/normalize.styl"
]
module.exports = (_gulp)->
_gulp.src source
.pipe concat "zen.ui.normalize.styl"
.pipe stylus
compress: true
errors : true
.pipe header banner, pkg: pkg
.pipe _gulp.dest "build/css/"
| true | "use strict"
concat = require "gulp-concat"
header = require "gulp-header"
stylus = require "gulp-stylus"
pkg = require "./../package.json"
banner = [
"/**"
" * normalize.css - Normalize.css is a customisable CSS file that makes browsers render all elements more consistently and in line with modern standards. The project relies on researching the differences between default browser styles in order to precisely target only the styles that need or benefit from normalizing."
" * @source zen.ui.normalize.css"
" * @version v3.0.3"
" * @link https://github.com/bymathias/normalize.styl"
" * @author PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI"
" * @license MIT"
" */"
""
].join("\n")
source = [
"source/stylus/normalize.styl"
]
module.exports = (_gulp)->
_gulp.src source
.pipe concat "zen.ui.normalize.styl"
.pipe stylus
compress: true
errors : true
.pipe header banner, pkg: pkg
.pipe _gulp.dest "build/css/"
|
[
{
"context": "e strict'\n\ndescribe 'maxRowLen :', ->\n names = ['foo', 'bar', 'baz', 'qux']\n exts = ['txt', 'md', 'js",
"end": 56,
"score": 0.9242929220199585,
"start": 53,
"tag": "NAME",
"value": "foo"
},
{
"context": "t'\n\ndescribe 'maxRowLen :', ->\n names = ['foo', 'bar', 'baz', 'qux']\n exts = ['txt', 'md', 'js']\n ar",
"end": 63,
"score": 0.9353630542755127,
"start": 60,
"tag": "NAME",
"value": "bar"
},
{
"context": "cribe 'maxRowLen :', ->\n names = ['foo', 'bar', 'baz', 'qux']\n exts = ['txt', 'md', 'js']\n ar = []\n\n",
"end": 70,
"score": 0.8274196982383728,
"start": 67,
"tag": "NAME",
"value": "baz"
}
] | test/opts/max-row-len.coffee | codekirei/columnize-array | 0 | 'use strict'
describe 'maxRowLen :', ->
names = ['foo', 'bar', 'baz', 'qux']
exts = ['txt', 'md', 'js']
ar = []
names.forEach (name) ->
exts.forEach (ext) ->
ar.push name + '.' + ext
len = 40
res = -> columnize ar, maxRowLen: len
it 'strs', ->
expected =
[ 'foo.txt bar.txt baz.txt qux.txt'
, 'foo.md bar.md baz.md qux.md'
, 'foo.js bar.js baz.js qux.js'
]
actual = res().strs
assert.deepEqual actual, expected
expected.map (str) ->
assert.isTrue str.length <= len
it 'indices', ->
expected =
[ [ 0, 3, 6, 9 ]
, [ 1, 4, 7, 10 ]
, [ 2, 5, 8, 11 ]
]
actual = res().indices
assert.deepEqual actual, expected
| 98663 | 'use strict'
describe 'maxRowLen :', ->
names = ['<NAME>', '<NAME>', '<NAME>', 'qux']
exts = ['txt', 'md', 'js']
ar = []
names.forEach (name) ->
exts.forEach (ext) ->
ar.push name + '.' + ext
len = 40
res = -> columnize ar, maxRowLen: len
it 'strs', ->
expected =
[ 'foo.txt bar.txt baz.txt qux.txt'
, 'foo.md bar.md baz.md qux.md'
, 'foo.js bar.js baz.js qux.js'
]
actual = res().strs
assert.deepEqual actual, expected
expected.map (str) ->
assert.isTrue str.length <= len
it 'indices', ->
expected =
[ [ 0, 3, 6, 9 ]
, [ 1, 4, 7, 10 ]
, [ 2, 5, 8, 11 ]
]
actual = res().indices
assert.deepEqual actual, expected
| true | 'use strict'
describe 'maxRowLen :', ->
names = ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'qux']
exts = ['txt', 'md', 'js']
ar = []
names.forEach (name) ->
exts.forEach (ext) ->
ar.push name + '.' + ext
len = 40
res = -> columnize ar, maxRowLen: len
it 'strs', ->
expected =
[ 'foo.txt bar.txt baz.txt qux.txt'
, 'foo.md bar.md baz.md qux.md'
, 'foo.js bar.js baz.js qux.js'
]
actual = res().strs
assert.deepEqual actual, expected
expected.map (str) ->
assert.isTrue str.length <= len
it 'indices', ->
expected =
[ [ 0, 3, 6, 9 ]
, [ 1, 4, 7, 10 ]
, [ 2, 5, 8, 11 ]
]
actual = res().indices
assert.deepEqual actual, expected
|
[
{
"context": "# @file forces.coffee\n# @Copyright (c) 2017 Taylor Siviter\n# This source code is licensed under the MIT Lice",
"end": 58,
"score": 0.9998148083686829,
"start": 44,
"tag": "NAME",
"value": "Taylor Siviter"
}
] | src/maths/forces.coffee | siviter-t/lampyridae.coffee | 4 | # @file forces.coffee
# @Copyright (c) 2017 Taylor Siviter
# This source code is licensed under the MIT License.
# For full information, see the LICENSE file in the project root.
require 'maths/vec2d'
class Lampyridae.Forces
### A selection of predefined forces that can be added to Lampyridae.ForceParticle
#
# Note these are all written assuming that particles are contained within an array that
# indexes each entity.
###
### Computational Parameters ###
@G: 1.0 # Gravitational strength
### For cases where negligible or no force is experienced. ###
@nullForce: () -> return new Lampyridae.Vec2D 0.0, 0.0
### Pairwise gravitational force of attraction of the ith particle to the jth
#
# The domain of interaction is limited to the radii of the particles (min distance apart)
# and for maximum distance where the force F ~ 0.0005; i.e. when r = 44 * sqrt(G*mi*mj)
# Note: the reverse force (i.e. jth to ith) could be added to the other jth particle.
# Often however, this can be neglected if the ith particle is negligible in mass.
#
# @param parr [Array] The array that keeps track of a set of particles
# @param i [Number] The index of the ith particle (where the force starts from)
# @param j [Number] The index of the jth particle (where the force is directed to)
###
@gravity: (parr, i, j) ->
return parr[i].addForce () =>
distance = parr[i].pos.distanceTo ( parr[j].pos )
massessq = parr[i].mass * parr[j].mass
limit = 44 * Math.sqrt(@G * massessq)
unless parr[i].r + parr[j].r < distance < limit then return @nullForce()
direction = parr[i].pos.directionTo( parr[j].pos )
strength = @G * massessq / (distance * distance)
return direction.scale(strength)
# end class Lampyridae.Forces
module.exports = Lampyridae.Forces
| 105662 | # @file forces.coffee
# @Copyright (c) 2017 <NAME>
# This source code is licensed under the MIT License.
# For full information, see the LICENSE file in the project root.
require 'maths/vec2d'
class Lampyridae.Forces
### A selection of predefined forces that can be added to Lampyridae.ForceParticle
#
# Note these are all written assuming that particles are contained within an array that
# indexes each entity.
###
### Computational Parameters ###
@G: 1.0 # Gravitational strength
### For cases where negligible or no force is experienced. ###
@nullForce: () -> return new Lampyridae.Vec2D 0.0, 0.0
### Pairwise gravitational force of attraction of the ith particle to the jth
#
# The domain of interaction is limited to the radii of the particles (min distance apart)
# and for maximum distance where the force F ~ 0.0005; i.e. when r = 44 * sqrt(G*mi*mj)
# Note: the reverse force (i.e. jth to ith) could be added to the other jth particle.
# Often however, this can be neglected if the ith particle is negligible in mass.
#
# @param parr [Array] The array that keeps track of a set of particles
# @param i [Number] The index of the ith particle (where the force starts from)
# @param j [Number] The index of the jth particle (where the force is directed to)
###
@gravity: (parr, i, j) ->
return parr[i].addForce () =>
distance = parr[i].pos.distanceTo ( parr[j].pos )
massessq = parr[i].mass * parr[j].mass
limit = 44 * Math.sqrt(@G * massessq)
unless parr[i].r + parr[j].r < distance < limit then return @nullForce()
direction = parr[i].pos.directionTo( parr[j].pos )
strength = @G * massessq / (distance * distance)
return direction.scale(strength)
# end class Lampyridae.Forces
module.exports = Lampyridae.Forces
| true | # @file forces.coffee
# @Copyright (c) 2017 PI:NAME:<NAME>END_PI
# This source code is licensed under the MIT License.
# For full information, see the LICENSE file in the project root.
require 'maths/vec2d'
class Lampyridae.Forces
### A selection of predefined forces that can be added to Lampyridae.ForceParticle
#
# Note these are all written assuming that particles are contained within an array that
# indexes each entity.
###
### Computational Parameters ###
@G: 1.0 # Gravitational strength
### For cases where negligible or no force is experienced. ###
@nullForce: () -> return new Lampyridae.Vec2D 0.0, 0.0
### Pairwise gravitational force of attraction of the ith particle to the jth
#
# The domain of interaction is limited to the radii of the particles (min distance apart)
# and for maximum distance where the force F ~ 0.0005; i.e. when r = 44 * sqrt(G*mi*mj)
# Note: the reverse force (i.e. jth to ith) could be added to the other jth particle.
# Often however, this can be neglected if the ith particle is negligible in mass.
#
# @param parr [Array] The array that keeps track of a set of particles
# @param i [Number] The index of the ith particle (where the force starts from)
# @param j [Number] The index of the jth particle (where the force is directed to)
###
@gravity: (parr, i, j) ->
return parr[i].addForce () =>
distance = parr[i].pos.distanceTo ( parr[j].pos )
massessq = parr[i].mass * parr[j].mass
limit = 44 * Math.sqrt(@G * massessq)
unless parr[i].r + parr[j].r < distance < limit then return @nullForce()
direction = parr[i].pos.directionTo( parr[j].pos )
strength = @G * massessq / (distance * distance)
return direction.scale(strength)
# end class Lampyridae.Forces
module.exports = Lampyridae.Forces
|
[
{
"context": "###\n termap - Terminal Map Viewer\n by Michael Strassburger <codepoet@cpan.org>\n\n Minimalistic parser and co",
"end": 60,
"score": 0.9998701810836792,
"start": 40,
"tag": "NAME",
"value": "Michael Strassburger"
},
{
"context": " - Terminal Map Viewer\n by Michael Strassburger <codepoet@cpan.org>\n\n Minimalistic parser and compiler for Mapbox (",
"end": 79,
"score": 0.9999316930770874,
"start": 62,
"tag": "EMAIL",
"value": "codepoet@cpan.org"
}
] | src/Styler.coffee | 82ndAirborneDiv/mapsc | 1 | ###
termap - Terminal Map Viewer
by Michael Strassburger <codepoet@cpan.org>
Minimalistic parser and compiler for Mapbox (Studio) Map Style files
See: https://www.mapbox.com/mapbox-gl-style-spec/
Compiles layer filter instructions into a chain of true/false returning
anonymous functions to improve rendering speed compared to realtime parsing.
###
fs = require 'fs'
module.exports = class Styler
styleById: {}
styleByLayer: {}
constructor: (file) ->
json = JSON.parse fs.readFileSync(file).toString()
@styleName = json.name
@_replaceConstants json.constants, json.layers if json.constants
for style in json.layers
if style.ref and @styleById[style.ref]
for ref in ['type', 'source-layer', 'minzoom', 'maxzoom', 'filter']
if @styleById[style.ref][ref] and not style[ref]
style[ref] = @styleById[style.ref][ref]
style.appliesTo = @_compileFilter style.filter
@styleByLayer[style['source-layer']] ?= []
@styleByLayer[style['source-layer']].push style
@styleById[style.id] = style
getStyleFor: (layer, feature, zoom) ->
return false unless @styleByLayer[layer]
for style in @styleByLayer[layer]
if style.appliesTo feature
return style
return false
_replaceConstants: (constants, tree) ->
for id, node of tree
switch typeof node
when 'object'
continue if node.constructor.name.match /Stream/
@_replaceConstants constants, node
when 'string'
if node.charAt(0) is '@'
tree[id] = constants[node]
null
_compileFilter: (filter) ->
switch filter?[0]
when "all"
filters = (@_compileFilter subFilter for subFilter in filter[1..])
(feature) ->
return false for appliesTo in filters when not appliesTo feature
true
when "any"
filters = (@_compileFilter subFilter for subFilter in filter[1..])
(feature) ->
return true for appliesTo in filters when appliesTo feature
false
when "none"
filters = (@_compileFilter subFilter for subFilter in filter[1..])
(feature) ->
return false for appliesTo in filters when appliesTo feature
true
when "=="
(feature) -> feature.properties[filter[1]] is filter[2]
when "!="
(feature) -> feature.properties[filter[1]] isnt filter[2]
when "in"
(feature) ->
return true for value in filter[2..] when feature.properties[filter[1]] is value
false
when "!in"
(feature) ->
return false for value in filter[2..] when feature.properties[filter[1]] is value
true
when "has"
(feature) -> !!feature.properties[filter[1]]
when "!has"
(feature) -> !feature.properties[filter[1]]
when ">"
(feature) -> feature.properties[filter[1]] > filter[2]
when ">="
(feature) -> feature.properties[filter[1]] >= filter[2]
when "<"
(feature) -> feature.properties[filter[1]] < filter[2]
when "<="
(feature) -> feature.properties[filter[1]] <= filter[2]
else
-> true
| 214340 | ###
termap - Terminal Map Viewer
by <NAME> <<EMAIL>>
Minimalistic parser and compiler for Mapbox (Studio) Map Style files
See: https://www.mapbox.com/mapbox-gl-style-spec/
Compiles layer filter instructions into a chain of true/false returning
anonymous functions to improve rendering speed compared to realtime parsing.
###
fs = require 'fs'
module.exports = class Styler
styleById: {}
styleByLayer: {}
constructor: (file) ->
json = JSON.parse fs.readFileSync(file).toString()
@styleName = json.name
@_replaceConstants json.constants, json.layers if json.constants
for style in json.layers
if style.ref and @styleById[style.ref]
for ref in ['type', 'source-layer', 'minzoom', 'maxzoom', 'filter']
if @styleById[style.ref][ref] and not style[ref]
style[ref] = @styleById[style.ref][ref]
style.appliesTo = @_compileFilter style.filter
@styleByLayer[style['source-layer']] ?= []
@styleByLayer[style['source-layer']].push style
@styleById[style.id] = style
getStyleFor: (layer, feature, zoom) ->
return false unless @styleByLayer[layer]
for style in @styleByLayer[layer]
if style.appliesTo feature
return style
return false
_replaceConstants: (constants, tree) ->
for id, node of tree
switch typeof node
when 'object'
continue if node.constructor.name.match /Stream/
@_replaceConstants constants, node
when 'string'
if node.charAt(0) is '@'
tree[id] = constants[node]
null
_compileFilter: (filter) ->
switch filter?[0]
when "all"
filters = (@_compileFilter subFilter for subFilter in filter[1..])
(feature) ->
return false for appliesTo in filters when not appliesTo feature
true
when "any"
filters = (@_compileFilter subFilter for subFilter in filter[1..])
(feature) ->
return true for appliesTo in filters when appliesTo feature
false
when "none"
filters = (@_compileFilter subFilter for subFilter in filter[1..])
(feature) ->
return false for appliesTo in filters when appliesTo feature
true
when "=="
(feature) -> feature.properties[filter[1]] is filter[2]
when "!="
(feature) -> feature.properties[filter[1]] isnt filter[2]
when "in"
(feature) ->
return true for value in filter[2..] when feature.properties[filter[1]] is value
false
when "!in"
(feature) ->
return false for value in filter[2..] when feature.properties[filter[1]] is value
true
when "has"
(feature) -> !!feature.properties[filter[1]]
when "!has"
(feature) -> !feature.properties[filter[1]]
when ">"
(feature) -> feature.properties[filter[1]] > filter[2]
when ">="
(feature) -> feature.properties[filter[1]] >= filter[2]
when "<"
(feature) -> feature.properties[filter[1]] < filter[2]
when "<="
(feature) -> feature.properties[filter[1]] <= filter[2]
else
-> true
| true | ###
termap - Terminal Map Viewer
by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
Minimalistic parser and compiler for Mapbox (Studio) Map Style files
See: https://www.mapbox.com/mapbox-gl-style-spec/
Compiles layer filter instructions into a chain of true/false returning
anonymous functions to improve rendering speed compared to realtime parsing.
###
fs = require 'fs'
module.exports = class Styler
styleById: {}
styleByLayer: {}
constructor: (file) ->
json = JSON.parse fs.readFileSync(file).toString()
@styleName = json.name
@_replaceConstants json.constants, json.layers if json.constants
for style in json.layers
if style.ref and @styleById[style.ref]
for ref in ['type', 'source-layer', 'minzoom', 'maxzoom', 'filter']
if @styleById[style.ref][ref] and not style[ref]
style[ref] = @styleById[style.ref][ref]
style.appliesTo = @_compileFilter style.filter
@styleByLayer[style['source-layer']] ?= []
@styleByLayer[style['source-layer']].push style
@styleById[style.id] = style
getStyleFor: (layer, feature, zoom) ->
return false unless @styleByLayer[layer]
for style in @styleByLayer[layer]
if style.appliesTo feature
return style
return false
_replaceConstants: (constants, tree) ->
for id, node of tree
switch typeof node
when 'object'
continue if node.constructor.name.match /Stream/
@_replaceConstants constants, node
when 'string'
if node.charAt(0) is '@'
tree[id] = constants[node]
null
_compileFilter: (filter) ->
switch filter?[0]
when "all"
filters = (@_compileFilter subFilter for subFilter in filter[1..])
(feature) ->
return false for appliesTo in filters when not appliesTo feature
true
when "any"
filters = (@_compileFilter subFilter for subFilter in filter[1..])
(feature) ->
return true for appliesTo in filters when appliesTo feature
false
when "none"
filters = (@_compileFilter subFilter for subFilter in filter[1..])
(feature) ->
return false for appliesTo in filters when appliesTo feature
true
when "=="
(feature) -> feature.properties[filter[1]] is filter[2]
when "!="
(feature) -> feature.properties[filter[1]] isnt filter[2]
when "in"
(feature) ->
return true for value in filter[2..] when feature.properties[filter[1]] is value
false
when "!in"
(feature) ->
return false for value in filter[2..] when feature.properties[filter[1]] is value
true
when "has"
(feature) -> !!feature.properties[filter[1]]
when "!has"
(feature) -> !feature.properties[filter[1]]
when ">"
(feature) -> feature.properties[filter[1]] > filter[2]
when ">="
(feature) -> feature.properties[filter[1]] >= filter[2]
when "<"
(feature) -> feature.properties[filter[1]] < filter[2]
when "<="
(feature) -> feature.properties[filter[1]] <= filter[2]
else
-> true
|
[
{
"context": " {\r\n \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n },\r\n {\r\n \"_oid\": \"Member:1017\",\r\n ",
"end": 608,
"score": 0.9858702421188354,
"start": 595,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " {\r\n \"_oid\": \"Member:1017\",\r\n \"Name\": \"Bob McBobertan\"\r\n },\r\n {\r\n \"_oid\": \"Member:1047\",\r\n ",
"end": 685,
"score": 0.9998244047164917,
"start": 671,
"tag": "NAME",
"value": "Bob McBobertan"
},
{
"context": " {\r\n \"_oid\": \"Member:1047\",\r\n \"Name\": \"Ian B\"\r\n },\r\n {\r\n \"_oid\": \"Member:1048\",\r\n ",
"end": 753,
"score": 0.9997715353965759,
"start": 748,
"tag": "NAME",
"value": "Ian B"
},
{
"context": " {\r\n \"_oid\": \"Member:1048\",\r\n \"Name\": \"Ian Culling\"\r\n },\r\n {\r\n \"_oid\": \"Member:1049\",\r\n ",
"end": 827,
"score": 0.999768853187561,
"start": 816,
"tag": "NAME",
"value": "Ian Culling"
},
{
"context": " {\r\n \"_oid\": \"Member:1049\",\r\n \"Name\": \"Matt Higgins\"\r\n }\r\n ]\r\n]\r\n'''\r\n\r\nregisterJson 'url', '{\"fr",
"end": 902,
"score": 0.9997599720954895,
"start": 890,
"tag": "NAME",
"value": "Matt Higgins"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 1177,
"score": 0.985139787197113,
"start": 1164,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 1343,
"score": 0.9675256609916687,
"start": 1330,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 1509,
"score": 0.9458373785018921,
"start": 1496,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 1675,
"score": 0.8772222399711609,
"start": 1662,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 1841,
"score": 0.9995853304862976,
"start": 1828,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 2007,
"score": 0.9995427131652832,
"start": 1994,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:1017\",\r\n \"Name\": \"Bob McBobertan\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 2176,
"score": 0.9998235702514648,
"start": 2162,
"tag": "NAME",
"value": "Bob McBobertan"
},
{
"context": " \"_oid\": \"Member:1017\",\r\n \"Name\": \"Bob McBobertan\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 2345,
"score": 0.999815821647644,
"start": 2331,
"tag": "NAME",
"value": "Bob McBobertan"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 2511,
"score": 0.9996848702430725,
"start": 2498,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 2677,
"score": 0.999640941619873,
"start": 2664,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 2843,
"score": 0.9996809959411621,
"start": 2830,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 3009,
"score": 0.999680757522583,
"start": 2996,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 3175,
"score": 0.999626874923706,
"start": 3162,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 3341,
"score": 0.9995679259300232,
"start": 3328,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 3507,
"score": 0.9995545744895935,
"start": 3494,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 3673,
"score": 0.9991773962974548,
"start": 3660,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 3839,
"score": 0.9991722106933594,
"start": 3826,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 4005,
"score": 0.9992307424545288,
"start": 3992,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 4171,
"score": 0.9991160035133362,
"start": 4158,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 4337,
"score": 0.9993272423744202,
"start": 4324,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 4503,
"score": 0.9992625117301941,
"start": 4490,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 4669,
"score": 0.9993985891342163,
"start": 4656,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 4835,
"score": 0.9992984533309937,
"start": 4822,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 5001,
"score": 0.9994233846664429,
"start": 4988,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 5167,
"score": 0.9992153644561768,
"start": 5154,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 5333,
"score": 0.9992846846580505,
"start": 5320,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 5499,
"score": 0.9990569949150085,
"start": 5486,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 5665,
"score": 0.9990919828414917,
"start": 5652,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 5831,
"score": 0.9989923238754272,
"start": 5818,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 5997,
"score": 0.9990606904029846,
"start": 5984,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 6163,
"score": 0.9990487694740295,
"start": 6150,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 6329,
"score": 0.9992567300796509,
"start": 6316,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 6495,
"score": 0.9992218017578125,
"start": 6482,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 6661,
"score": 0.9992789626121521,
"start": 6648,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 6827,
"score": 0.9991782307624817,
"start": 6814,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 6993,
"score": 0.9991705417633057,
"start": 6980,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 7159,
"score": 0.999054491519928,
"start": 7146,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 7325,
"score": 0.9990977048873901,
"start": 7312,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 7491,
"score": 0.9974800944328308,
"start": 7478,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n {\r\n \"_oid\"",
"end": 7657,
"score": 0.9973093867301941,
"start": 7644,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r\n]\r\n'''\r\n\r\nregis",
"end": 7823,
"score": 0.9978757500648499,
"start": 7810,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 8283,
"score": 0.9980700016021729,
"start": 8270,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n ",
"end": 8580,
"score": 0.9984694123268127,
"start": 8567,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 8782,
"score": 0.9979077577590942,
"start": 8769,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n ",
"end": 9167,
"score": 0.9967776536941528,
"start": 9154,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 9369,
"score": 0.9979873895645142,
"start": 9356,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 9754,
"score": 0.999606192111969,
"start": 9741,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:1017\",\r\n \"Name\": \"Bob McBobertan\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 10054,
"score": 0.9998041391372681,
"start": 10040,
"tag": "NAME",
"value": "Bob McBobertan"
},
{
"context": " \"_oid\": \"Member:1017\",\r\n \"Name\": \"Bob McBobertan\"\r\n }\r\n ]\r\n },\r\n ",
"end": 10354,
"score": 0.9998180270195007,
"start": 10340,
"tag": "NAME",
"value": "Bob McBobertan"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n ",
"end": 10556,
"score": 0.999618649482727,
"start": 10543,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 10758,
"score": 0.9996615648269653,
"start": 10745,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 11231,
"score": 0.9996740818023682,
"start": 11218,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 11528,
"score": 0.9995938539505005,
"start": 11515,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 11825,
"score": 0.9996063113212585,
"start": 11812,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 12122,
"score": 0.9995854496955872,
"start": 12109,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 12419,
"score": 0.9996204972267151,
"start": 12406,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 12716,
"score": 0.9997077584266663,
"start": 12703,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 13013,
"score": 0.9996573328971863,
"start": 13000,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n ",
"end": 13310,
"score": 0.9996387362480164,
"start": 13297,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 13512,
"score": 0.9996359944343567,
"start": 13499,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 13897,
"score": 0.9996405839920044,
"start": 13884,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n ",
"end": 14194,
"score": 0.9989363551139832,
"start": 14181,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n ",
"end": 14396,
"score": 0.9991300106048584,
"start": 14383,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 14598,
"score": 0.9989819526672363,
"start": 14585,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 15071,
"score": 0.9992414712905884,
"start": 15058,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 15368,
"score": 0.9991508722305298,
"start": 15355,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 15665,
"score": 0.9992526173591614,
"start": 15652,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 15962,
"score": 0.999222457408905,
"start": 15949,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 16259,
"score": 0.9994986057281494,
"start": 16246,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 16556,
"score": 0.9995079040527344,
"start": 16543,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n ",
"end": 16853,
"score": 0.9995192289352417,
"start": 16840,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 17055,
"score": 0.9996160268783569,
"start": 17042,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 17352,
"score": 0.9996253848075867,
"start": 17339,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 17649,
"score": 0.9995858073234558,
"start": 17636,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 17946,
"score": 0.9995578527450562,
"start": 17933,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 18331,
"score": 0.9995812773704529,
"start": 18318,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n },\r\n ",
"end": 18628,
"score": 0.9986261129379272,
"start": 18615,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 18830,
"score": 0.9989118576049805,
"start": 18817,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 19127,
"score": 0.9990803003311157,
"start": 19114,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 19424,
"score": 0.9992326498031616,
"start": 19411,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 19721,
"score": 0.9993080496788025,
"start": 19708,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n }\r\n ]\r",
"end": 20018,
"score": 0.9991543292999268,
"start": 20005,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " {\r\n \"_oid\": \"Member:1017\",\r\n \"Name\": \"Bob McBobertan\"\r\n }\r\n ]\r\n]\r\n'''\r\n\r\nregisterJson 'url', '{\"fr",
"end": 20346,
"score": 0.9990535974502563,
"start": 20332,
"tag": "NAME",
"value": "Bob McBobertan"
},
{
"context": " {\r\n \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n },\r\n {\r\n \"_oid\": \"Member:1049\",\r\n ",
"end": 20560,
"score": 0.9605633616447449,
"start": 20547,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " {\r\n \"_oid\": \"Member:1049\",\r\n \"Name\": \"Matt Higgins\"\r\n }\r\n ]\r\n]\r\n'''\r\n\r\nregisterJson 'url', '{\"fr",
"end": 20635,
"score": 0.9998319149017334,
"start": 20623,
"tag": "NAME",
"value": "Matt Higgins"
},
{
"context": " {\r\n \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\"\r\n }\r\n ]\r\n]\r\n'''\r\n\r\nregisterJson 'url', '{\"fr",
"end": 20823,
"score": 0.9591110944747925,
"start": 20810,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " {\r\n \"_oid\": \"Member:20\",\r\n \"Name\": \"Administrator\",\r\n \"ParticipatesInConversations.@Count\": \"3",
"end": 21094,
"score": 0.8769335746765137,
"start": 21081,
"tag": "NAME",
"value": "Administrator"
},
{
"context": " {\r\n \"_oid\": \"Member:1017\",\r\n \"Name\": \"Bob McBobertan\",\r\n \"ParticipatesInConversations.@Count\": \"2",
"end": 24122,
"score": 0.9998582601547241,
"start": 24108,
"tag": "NAME",
"value": "Bob McBobertan"
},
{
"context": " {\r\n \"_oid\": \"Member:1047\",\r\n \"Name\": \"Ian B\",\r\n \"ParticipatesInConversations.@Count\": \"0",
"end": 24487,
"score": 0.9998672604560852,
"start": 24482,
"tag": "NAME",
"value": "Ian B"
},
{
"context": " {\r\n \"_oid\": \"Member:1048\",\r\n \"Name\": \"Ian Culling\",\r\n \"ParticipatesInConversations.@Count\": \"0",
"end": 24653,
"score": 0.9998852610588074,
"start": 24642,
"tag": "NAME",
"value": "Ian Culling"
},
{
"context": " {\r\n \"_oid\": \"Member:1049\",\r\n \"Name\": \"Matt Higgins\",\r\n \"ParticipatesInConversations.@Count\": \"5",
"end": 24820,
"score": 0.9998624324798584,
"start": 24808,
"tag": "NAME",
"value": "Matt Higgins"
},
{
"context": " {\r\n \"_oid\": \"Timebox:1738\",\r\n \"Name\": \"Kanban\"\r\n },\r\n {\r\n \"_oid\": \"Timebox:1666\",\r\n ",
"end": 27027,
"score": 0.7022847533226013,
"start": 27021,
"tag": "NAME",
"value": "Kanban"
}
] | tests/recorded.coffee | versionone/V1.Backbone | 1 | deferred = require('JQDeferred')
module.exports = (url, data) ->
response = fetch(url,data)
throw "\nNo recorded response for:\n#{url}\n#{data}\n" unless response?
deferred().resolve(response)
responses = {}
registerJson = (url, query, response) ->
responses["#{url}:#{query}"] = JSON.parse(response)
registerString = (url, query, response) ->
responses["#{url}:#{query}"] = response
fetch = (url, query) ->
responses["#{url}:#{query}"]
registerJson 'url', '{"from":"Member","select":["Name"]}', '''
[
[
{
"_oid": "Member:20",
"Name": "Administrator"
},
{
"_oid": "Member:1017",
"Name": "Bob McBobertan"
},
{
"_oid": "Member:1047",
"Name": "Ian B"
},
{
"_oid": "Member:1048",
"Name": "Ian Culling"
},
{
"_oid": "Member:1049",
"Name": "Matt Higgins"
}
]
]
'''
registerJson 'url', '{"from":"Expression","select":[{"from":"Author as Member","select":["Name"]}]}', '''
[
[
{
"_oid": "Expression:1008",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1011",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1012",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1013",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1014",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1015",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1019",
"Author": [
{
"_oid": "Member:1017",
"Name": "Bob McBobertan"
}
]
},
{
"_oid": "Expression:1020",
"Author": [
{
"_oid": "Member:1017",
"Name": "Bob McBobertan"
}
]
},
{
"_oid": "Expression:1021",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1022",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1023",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1024",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1025",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1026",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1027",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1028",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1029",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1030",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1031",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1032",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1033",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1034",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1035",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1036",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1037",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1038",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1039",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1040",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1041",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1042",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1043",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1044",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1045",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1046",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1050",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1051",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1052",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1053",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1054",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1067",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1068",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
]
'''
registerJson 'url', '{"from":"Expression","select":[{"from":"ExpressionsInConversation as Expression","select":[{"from":"Author as Member","select":["Name"]}]}]}', '''
[
[
{
"_oid": "Expression:1008",
"ExpressionsInConversation": [
{
"_oid": "Expression:1008",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1011",
"ExpressionsInConversation": [
{
"_oid": "Expression:1011",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1012",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1012",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1013",
"ExpressionsInConversation": [
{
"_oid": "Expression:1013",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1014",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1014",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1015",
"ExpressionsInConversation": [
{
"_oid": "Expression:1015",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1019",
"ExpressionsInConversation": [
{
"_oid": "Expression:1019",
"Author": [
{
"_oid": "Member:1017",
"Name": "Bob McBobertan"
}
]
}
]
},
{
"_oid": "Expression:1020",
"ExpressionsInConversation": [
{
"_oid": "Expression:1020",
"Author": [
{
"_oid": "Member:1017",
"Name": "Bob McBobertan"
}
]
},
{
"_oid": "Expression:1021",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1022",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1021",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1022",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1023",
"ExpressionsInConversation": [
{
"_oid": "Expression:1023",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1024",
"ExpressionsInConversation": [
{
"_oid": "Expression:1024",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1025",
"ExpressionsInConversation": [
{
"_oid": "Expression:1025",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1026",
"ExpressionsInConversation": [
{
"_oid": "Expression:1026",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1027",
"ExpressionsInConversation": [
{
"_oid": "Expression:1027",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1028",
"ExpressionsInConversation": [
{
"_oid": "Expression:1028",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1029",
"ExpressionsInConversation": [
{
"_oid": "Expression:1029",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1030",
"ExpressionsInConversation": [
{
"_oid": "Expression:1030",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1031",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1031",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1032",
"ExpressionsInConversation": [
{
"_oid": "Expression:1032",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1033",
"ExpressionsInConversation": [
{
"_oid": "Expression:1033",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1034",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1035",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1034",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1035",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1036",
"ExpressionsInConversation": [
{
"_oid": "Expression:1036",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1037",
"ExpressionsInConversation": [
{
"_oid": "Expression:1037",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1038",
"ExpressionsInConversation": [
{
"_oid": "Expression:1038",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1039",
"ExpressionsInConversation": [
{
"_oid": "Expression:1039",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1040",
"ExpressionsInConversation": [
{
"_oid": "Expression:1040",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1041",
"ExpressionsInConversation": [
{
"_oid": "Expression:1041",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1042",
"ExpressionsInConversation": [
{
"_oid": "Expression:1042",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1046",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1043",
"ExpressionsInConversation": [
{
"_oid": "Expression:1043",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1044",
"ExpressionsInConversation": [
{
"_oid": "Expression:1044",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1045",
"ExpressionsInConversation": [
{
"_oid": "Expression:1045",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1046",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1050",
"ExpressionsInConversation": [
{
"_oid": "Expression:1050",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1051",
"ExpressionsInConversation": [
{
"_oid": "Expression:1051",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
},
{
"_oid": "Expression:1068",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1052",
"ExpressionsInConversation": [
{
"_oid": "Expression:1052",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1053",
"ExpressionsInConversation": [
{
"_oid": "Expression:1053",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1054",
"ExpressionsInConversation": [
{
"_oid": "Expression:1054",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1067",
"ExpressionsInConversation": [
{
"_oid": "Expression:1067",
"Author": [
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
}
]
},
{
"_oid": "Expression:1068",
"ExpressionsInConversation": []
}
]
]
'''
registerJson 'url', '{"from":"Member","select":["Name"],"where":{"ID":"Member:1017"}}', '''
[
[
{
"_oid": "Member:1017",
"Name": "Bob McBobertan"
}
]
]
'''
registerJson 'url', '{"from":"Member","select":["Name"],"filter":["ParticipatesInConversations.@Count>\'4\'"]}', '''
[
[
{
"_oid": "Member:20",
"Name": "Administrator"
},
{
"_oid": "Member:1049",
"Name": "Matt Higgins"
}
]
]
'''
registerJson 'url', '{"from":"Member","select":["Name"],"where":{"Scopes.@Count":2}}', '''
[
[
{
"_oid": "Member:20",
"Name": "Administrator"
}
]
]
'''
registerJson 'url', '{"from":"Member","select":["Name","ParticipatesInConversations.@Count",{"from":"ParticipatesInConversations as Expression","select":["Content"]}]}', '''
[
[
{
"_oid": "Member:20",
"Name": "Administrator",
"ParticipatesInConversations.@Count": "31",
"ParticipatesInConversations": [
{
"_oid": "Expression:1008",
"Content": "garbage!"
},
{
"_oid": "Expression:1011",
"Content": "test meats"
},
{
"_oid": "Expression:1013",
"Content": "trash!"
},
{
"_oid": "Expression:1015",
"Content": "conversation"
},
{
"_oid": "Expression:1020",
"Content": "hey people?!"
},
{
"_oid": "Expression:1023",
"Content": "moar"
},
{
"_oid": "Expression:1024",
"Content": "moar!!!"
},
{
"_oid": "Expression:1025",
"Content": "MOAR?!?!?!"
},
{
"_oid": "Expression:1026",
"Content": "what?!"
},
{
"_oid": "Expression:1027",
"Content": "maor?!"
},
{
"_oid": "Expression:1028",
"Content": "moar?!"
},
{
"_oid": "Expression:1029",
"Content": "evan MOAR?!"
},
{
"_oid": "Expression:1030",
"Content": "moars?!"
},
{
"_oid": "Expression:1032",
"Content": "here in test space"
},
{
"_oid": "Expression:1033",
"Content": "Talking about test in a space"
},
{
"_oid": "Expression:1036",
"Content": "10"
},
{
"_oid": "Expression:1037",
"Content": "9"
},
{
"_oid": "Expression:1038",
"Content": "8"
},
{
"_oid": "Expression:1039",
"Content": "7"
},
{
"_oid": "Expression:1040",
"Content": "6"
},
{
"_oid": "Expression:1041",
"Content": "5"
},
{
"_oid": "Expression:1042",
"Content": "4"
},
{
"_oid": "Expression:1043",
"Content": "3"
},
{
"_oid": "Expression:1044",
"Content": "2"
},
{
"_oid": "Expression:1045",
"Content": "1"
},
{
"_oid": "Expression:1050",
"Content": "hi"
},
{
"_oid": "Expression:1051",
"Content": "1"
},
{
"_oid": "Expression:1052",
"Content": "2"
},
{
"_oid": "Expression:1053",
"Content": "3"
},
{
"_oid": "Expression:1054",
"Content": "4"
},
{
"_oid": "Expression:1067",
"Content": "Space-ing it up!"
}
]
},
{
"_oid": "Member:1017",
"Name": "Bob McBobertan",
"ParticipatesInConversations.@Count": "2",
"ParticipatesInConversations": [
{
"_oid": "Expression:1019",
"Content": "Herro, anyone?"
},
{
"_oid": "Expression:1020",
"Content": "hey people?!"
}
]
},
{
"_oid": "Member:1047",
"Name": "Ian B",
"ParticipatesInConversations.@Count": "0",
"ParticipatesInConversations": []
},
{
"_oid": "Member:1048",
"Name": "Ian Culling",
"ParticipatesInConversations.@Count": "0",
"ParticipatesInConversations": []
},
{
"_oid": "Member:1049",
"Name": "Matt Higgins",
"ParticipatesInConversations.@Count": "5",
"ParticipatesInConversations": [
{
"_oid": "Expression:1050",
"Content": "hi"
},
{
"_oid": "Expression:1051",
"Content": "1"
},
{
"_oid": "Expression:1052",
"Content": "2"
},
{
"_oid": "Expression:1053",
"Content": "3"
},
{
"_oid": "Expression:1054",
"Content": "4"
}
]
}
]
]
'''
registerJson 'url', "{\"from\":\"Member\"}\n---\n{\"from\":\"ExpressionSpace\"}", '''
[
[
{
"_oid": "Member:20"
},
{
"_oid": "Member:1017"
},
{
"_oid": "Member:1047"
},
{
"_oid": "Member:1048"
},
{
"_oid": "Member:1049"
}
],
[
{
"_oid": "ExpressionSpace:1005"
},
{
"_oid": "ExpressionSpace:1006"
},
{
"_oid": "ExpressionSpace:1007"
},
{
"_oid": "ExpressionSpace:1009"
},
{
"_oid": "ExpressionSpace:1055"
},
{
"_oid": "ExpressionSpace:1056"
},
{
"_oid": "ExpressionSpace:1057"
},
{
"_oid": "ExpressionSpace:1058"
},
{
"_oid": "ExpressionSpace:1059"
},
{
"_oid": "ExpressionSpace:1060"
},
{
"_oid": "ExpressionSpace:1061"
},
{
"_oid": "ExpressionSpace:1062"
},
{
"_oid": "ExpressionSpace:1063"
},
{
"_oid": "ExpressionSpace:1064"
},
{
"_oid": "ExpressionSpace:1065"
},
{
"_oid": "ExpressionSpace:1066"
}
]
]
'''
registerString '/VersionOne/rest-1.v1/Data/Expression', '<Asset></Asset>', '''
<Asset href="/VersionOne.Web/rest-1.v1/Data/Expression/1114/1245" id="Expression:1114:1245">
<Attribute name="Content">Hello</Attribute>
</Asset>
'''
registerJson 'url1', '{"from":"Timebox","sort":["EndDate"],"select":["Name"]}', '''
[
[
{
"_oid": "Timebox:1282",
"Name": "Sprint 1"
},
{
"_oid": "Timebox:1738",
"Name": "Kanban"
},
{
"_oid": "Timebox:1666",
"Name": "Sprint 4"
},
{
"_oid": "Timebox:1469",
"Name": "Sprint 2"
},
{
"_oid": "Timebox:1581",
"Name": "Sprint 3"
},
{
"_oid": "Timebox:1821",
"Name": "Sprint 7"
},
{
"_oid": "Timebox:1272",
"Name": "Month 1"
},
{
"_oid": "Timebox:1552",
"Name": "Month 2"
},
{
"_oid": "Timebox:1775",
"Name": "Sprint 5"
},
{
"_oid": "Timebox:1812",
"Name": "Sprint 6"
},
{
"_oid": "Timebox:1822",
"Name": "Month 3"
},
{
"_oid": "Timebox:2060",
"Name": "Iteration 5"
},
{
"_oid": "Timebox:2058",
"Name": "Iteration 4"
}
]
]
'''
registerJson 'url2', '{"from":"Timebox","sort":["EndDate"],"select":["Name"]}', '''
[
[
{
"_oid": "Timebox:2060",
"Name": "Iteration 5"
},
{
"_oid": "Timebox:1282",
"Name": "Sprint 1"
},
{
"_oid": "Timebox:1272",
"Name": "Month 1"
},
{
"_oid": "Timebox:1469",
"Name": "Sprint 2"
},
{
"_oid": "Timebox:1581",
"Name": "Sprint 3"
},
{
"_oid": "Timebox:1666",
"Name": "Sprint 4"
},
{
"_oid": "Timebox:1552",
"Name": "Month 2"
},
{
"_oid": "Timebox:1775",
"Name": "Sprint 5"
},
{
"_oid": "Timebox:1738",
"Name": "Kanban"
},
{
"_oid": "Timebox:1812",
"Name": "Sprint 6"
},
{
"_oid": "Timebox:1822",
"Name": "Month 3"
},
{
"_oid": "Timebox:1821",
"Name": "Sprint 7"
},
{
"_oid": "Timebox:2058",
"Name": "Iteration 4"
}
]
]
'''
| 19787 | deferred = require('JQDeferred')
module.exports = (url, data) ->
response = fetch(url,data)
throw "\nNo recorded response for:\n#{url}\n#{data}\n" unless response?
deferred().resolve(response)
responses = {}
registerJson = (url, query, response) ->
responses["#{url}:#{query}"] = JSON.parse(response)
registerString = (url, query, response) ->
responses["#{url}:#{query}"] = response
fetch = (url, query) ->
responses["#{url}:#{query}"]
registerJson 'url', '{"from":"Member","select":["Name"]}', '''
[
[
{
"_oid": "Member:20",
"Name": "<NAME>"
},
{
"_oid": "Member:1017",
"Name": "<NAME>"
},
{
"_oid": "Member:1047",
"Name": "<NAME>"
},
{
"_oid": "Member:1048",
"Name": "<NAME>"
},
{
"_oid": "Member:1049",
"Name": "<NAME>"
}
]
]
'''
registerJson 'url', '{"from":"Expression","select":[{"from":"Author as Member","select":["Name"]}]}', '''
[
[
{
"_oid": "Expression:1008",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1011",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1012",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1013",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1014",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1015",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1019",
"Author": [
{
"_oid": "Member:1017",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1020",
"Author": [
{
"_oid": "Member:1017",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1021",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1022",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1023",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1024",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1025",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1026",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1027",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1028",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1029",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1030",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1031",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1032",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1033",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1034",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1035",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1036",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1037",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1038",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1039",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1040",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1041",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1042",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1043",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1044",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1045",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1046",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1050",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1051",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1052",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1053",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1054",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1067",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1068",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
]
'''
registerJson 'url', '{"from":"Expression","select":[{"from":"ExpressionsInConversation as Expression","select":[{"from":"Author as Member","select":["Name"]}]}]}', '''
[
[
{
"_oid": "Expression:1008",
"ExpressionsInConversation": [
{
"_oid": "Expression:1008",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1011",
"ExpressionsInConversation": [
{
"_oid": "Expression:1011",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1012",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1012",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1013",
"ExpressionsInConversation": [
{
"_oid": "Expression:1013",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1014",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1014",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1015",
"ExpressionsInConversation": [
{
"_oid": "Expression:1015",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1019",
"ExpressionsInConversation": [
{
"_oid": "Expression:1019",
"Author": [
{
"_oid": "Member:1017",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1020",
"ExpressionsInConversation": [
{
"_oid": "Expression:1020",
"Author": [
{
"_oid": "Member:1017",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1021",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1022",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1021",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1022",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1023",
"ExpressionsInConversation": [
{
"_oid": "Expression:1023",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1024",
"ExpressionsInConversation": [
{
"_oid": "Expression:1024",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1025",
"ExpressionsInConversation": [
{
"_oid": "Expression:1025",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1026",
"ExpressionsInConversation": [
{
"_oid": "Expression:1026",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1027",
"ExpressionsInConversation": [
{
"_oid": "Expression:1027",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1028",
"ExpressionsInConversation": [
{
"_oid": "Expression:1028",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1029",
"ExpressionsInConversation": [
{
"_oid": "Expression:1029",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1030",
"ExpressionsInConversation": [
{
"_oid": "Expression:1030",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1031",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1031",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1032",
"ExpressionsInConversation": [
{
"_oid": "Expression:1032",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1033",
"ExpressionsInConversation": [
{
"_oid": "Expression:1033",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1034",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1035",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1034",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1035",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1036",
"ExpressionsInConversation": [
{
"_oid": "Expression:1036",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1037",
"ExpressionsInConversation": [
{
"_oid": "Expression:1037",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1038",
"ExpressionsInConversation": [
{
"_oid": "Expression:1038",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1039",
"ExpressionsInConversation": [
{
"_oid": "Expression:1039",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1040",
"ExpressionsInConversation": [
{
"_oid": "Expression:1040",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1041",
"ExpressionsInConversation": [
{
"_oid": "Expression:1041",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1042",
"ExpressionsInConversation": [
{
"_oid": "Expression:1042",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1046",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1043",
"ExpressionsInConversation": [
{
"_oid": "Expression:1043",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1044",
"ExpressionsInConversation": [
{
"_oid": "Expression:1044",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1045",
"ExpressionsInConversation": [
{
"_oid": "Expression:1045",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1046",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1050",
"ExpressionsInConversation": [
{
"_oid": "Expression:1050",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1051",
"ExpressionsInConversation": [
{
"_oid": "Expression:1051",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
},
{
"_oid": "Expression:1068",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1052",
"ExpressionsInConversation": [
{
"_oid": "Expression:1052",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1053",
"ExpressionsInConversation": [
{
"_oid": "Expression:1053",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1054",
"ExpressionsInConversation": [
{
"_oid": "Expression:1054",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1067",
"ExpressionsInConversation": [
{
"_oid": "Expression:1067",
"Author": [
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
}
]
},
{
"_oid": "Expression:1068",
"ExpressionsInConversation": []
}
]
]
'''
registerJson 'url', '{"from":"Member","select":["Name"],"where":{"ID":"Member:1017"}}', '''
[
[
{
"_oid": "Member:1017",
"Name": "<NAME>"
}
]
]
'''
registerJson 'url', '{"from":"Member","select":["Name"],"filter":["ParticipatesInConversations.@Count>\'4\'"]}', '''
[
[
{
"_oid": "Member:20",
"Name": "<NAME>"
},
{
"_oid": "Member:1049",
"Name": "<NAME>"
}
]
]
'''
registerJson 'url', '{"from":"Member","select":["Name"],"where":{"Scopes.@Count":2}}', '''
[
[
{
"_oid": "Member:20",
"Name": "<NAME>"
}
]
]
'''
registerJson 'url', '{"from":"Member","select":["Name","ParticipatesInConversations.@Count",{"from":"ParticipatesInConversations as Expression","select":["Content"]}]}', '''
[
[
{
"_oid": "Member:20",
"Name": "<NAME>",
"ParticipatesInConversations.@Count": "31",
"ParticipatesInConversations": [
{
"_oid": "Expression:1008",
"Content": "garbage!"
},
{
"_oid": "Expression:1011",
"Content": "test meats"
},
{
"_oid": "Expression:1013",
"Content": "trash!"
},
{
"_oid": "Expression:1015",
"Content": "conversation"
},
{
"_oid": "Expression:1020",
"Content": "hey people?!"
},
{
"_oid": "Expression:1023",
"Content": "moar"
},
{
"_oid": "Expression:1024",
"Content": "moar!!!"
},
{
"_oid": "Expression:1025",
"Content": "MOAR?!?!?!"
},
{
"_oid": "Expression:1026",
"Content": "what?!"
},
{
"_oid": "Expression:1027",
"Content": "maor?!"
},
{
"_oid": "Expression:1028",
"Content": "moar?!"
},
{
"_oid": "Expression:1029",
"Content": "evan MOAR?!"
},
{
"_oid": "Expression:1030",
"Content": "moars?!"
},
{
"_oid": "Expression:1032",
"Content": "here in test space"
},
{
"_oid": "Expression:1033",
"Content": "Talking about test in a space"
},
{
"_oid": "Expression:1036",
"Content": "10"
},
{
"_oid": "Expression:1037",
"Content": "9"
},
{
"_oid": "Expression:1038",
"Content": "8"
},
{
"_oid": "Expression:1039",
"Content": "7"
},
{
"_oid": "Expression:1040",
"Content": "6"
},
{
"_oid": "Expression:1041",
"Content": "5"
},
{
"_oid": "Expression:1042",
"Content": "4"
},
{
"_oid": "Expression:1043",
"Content": "3"
},
{
"_oid": "Expression:1044",
"Content": "2"
},
{
"_oid": "Expression:1045",
"Content": "1"
},
{
"_oid": "Expression:1050",
"Content": "hi"
},
{
"_oid": "Expression:1051",
"Content": "1"
},
{
"_oid": "Expression:1052",
"Content": "2"
},
{
"_oid": "Expression:1053",
"Content": "3"
},
{
"_oid": "Expression:1054",
"Content": "4"
},
{
"_oid": "Expression:1067",
"Content": "Space-ing it up!"
}
]
},
{
"_oid": "Member:1017",
"Name": "<NAME>",
"ParticipatesInConversations.@Count": "2",
"ParticipatesInConversations": [
{
"_oid": "Expression:1019",
"Content": "Herro, anyone?"
},
{
"_oid": "Expression:1020",
"Content": "hey people?!"
}
]
},
{
"_oid": "Member:1047",
"Name": "<NAME>",
"ParticipatesInConversations.@Count": "0",
"ParticipatesInConversations": []
},
{
"_oid": "Member:1048",
"Name": "<NAME>",
"ParticipatesInConversations.@Count": "0",
"ParticipatesInConversations": []
},
{
"_oid": "Member:1049",
"Name": "<NAME>",
"ParticipatesInConversations.@Count": "5",
"ParticipatesInConversations": [
{
"_oid": "Expression:1050",
"Content": "hi"
},
{
"_oid": "Expression:1051",
"Content": "1"
},
{
"_oid": "Expression:1052",
"Content": "2"
},
{
"_oid": "Expression:1053",
"Content": "3"
},
{
"_oid": "Expression:1054",
"Content": "4"
}
]
}
]
]
'''
registerJson 'url', "{\"from\":\"Member\"}\n---\n{\"from\":\"ExpressionSpace\"}", '''
[
[
{
"_oid": "Member:20"
},
{
"_oid": "Member:1017"
},
{
"_oid": "Member:1047"
},
{
"_oid": "Member:1048"
},
{
"_oid": "Member:1049"
}
],
[
{
"_oid": "ExpressionSpace:1005"
},
{
"_oid": "ExpressionSpace:1006"
},
{
"_oid": "ExpressionSpace:1007"
},
{
"_oid": "ExpressionSpace:1009"
},
{
"_oid": "ExpressionSpace:1055"
},
{
"_oid": "ExpressionSpace:1056"
},
{
"_oid": "ExpressionSpace:1057"
},
{
"_oid": "ExpressionSpace:1058"
},
{
"_oid": "ExpressionSpace:1059"
},
{
"_oid": "ExpressionSpace:1060"
},
{
"_oid": "ExpressionSpace:1061"
},
{
"_oid": "ExpressionSpace:1062"
},
{
"_oid": "ExpressionSpace:1063"
},
{
"_oid": "ExpressionSpace:1064"
},
{
"_oid": "ExpressionSpace:1065"
},
{
"_oid": "ExpressionSpace:1066"
}
]
]
'''
registerString '/VersionOne/rest-1.v1/Data/Expression', '<Asset></Asset>', '''
<Asset href="/VersionOne.Web/rest-1.v1/Data/Expression/1114/1245" id="Expression:1114:1245">
<Attribute name="Content">Hello</Attribute>
</Asset>
'''
registerJson 'url1', '{"from":"Timebox","sort":["EndDate"],"select":["Name"]}', '''
[
[
{
"_oid": "Timebox:1282",
"Name": "Sprint 1"
},
{
"_oid": "Timebox:1738",
"Name": "<NAME>"
},
{
"_oid": "Timebox:1666",
"Name": "Sprint 4"
},
{
"_oid": "Timebox:1469",
"Name": "Sprint 2"
},
{
"_oid": "Timebox:1581",
"Name": "Sprint 3"
},
{
"_oid": "Timebox:1821",
"Name": "Sprint 7"
},
{
"_oid": "Timebox:1272",
"Name": "Month 1"
},
{
"_oid": "Timebox:1552",
"Name": "Month 2"
},
{
"_oid": "Timebox:1775",
"Name": "Sprint 5"
},
{
"_oid": "Timebox:1812",
"Name": "Sprint 6"
},
{
"_oid": "Timebox:1822",
"Name": "Month 3"
},
{
"_oid": "Timebox:2060",
"Name": "Iteration 5"
},
{
"_oid": "Timebox:2058",
"Name": "Iteration 4"
}
]
]
'''
registerJson 'url2', '{"from":"Timebox","sort":["EndDate"],"select":["Name"]}', '''
[
[
{
"_oid": "Timebox:2060",
"Name": "Iteration 5"
},
{
"_oid": "Timebox:1282",
"Name": "Sprint 1"
},
{
"_oid": "Timebox:1272",
"Name": "Month 1"
},
{
"_oid": "Timebox:1469",
"Name": "Sprint 2"
},
{
"_oid": "Timebox:1581",
"Name": "Sprint 3"
},
{
"_oid": "Timebox:1666",
"Name": "Sprint 4"
},
{
"_oid": "Timebox:1552",
"Name": "Month 2"
},
{
"_oid": "Timebox:1775",
"Name": "Sprint 5"
},
{
"_oid": "Timebox:1738",
"Name": "Kanban"
},
{
"_oid": "Timebox:1812",
"Name": "Sprint 6"
},
{
"_oid": "Timebox:1822",
"Name": "Month 3"
},
{
"_oid": "Timebox:1821",
"Name": "Sprint 7"
},
{
"_oid": "Timebox:2058",
"Name": "Iteration 4"
}
]
]
'''
| true | deferred = require('JQDeferred')
module.exports = (url, data) ->
response = fetch(url,data)
throw "\nNo recorded response for:\n#{url}\n#{data}\n" unless response?
deferred().resolve(response)
responses = {}
registerJson = (url, query, response) ->
responses["#{url}:#{query}"] = JSON.parse(response)
registerString = (url, query, response) ->
responses["#{url}:#{query}"] = response
fetch = (url, query) ->
responses["#{url}:#{query}"]
registerJson 'url', '{"from":"Member","select":["Name"]}', '''
[
[
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
},
{
"_oid": "Member:1017",
"Name": "PI:NAME:<NAME>END_PI"
},
{
"_oid": "Member:1047",
"Name": "PI:NAME:<NAME>END_PI"
},
{
"_oid": "Member:1048",
"Name": "PI:NAME:<NAME>END_PI"
},
{
"_oid": "Member:1049",
"Name": "PI:NAME:<NAME>END_PI"
}
]
]
'''
registerJson 'url', '{"from":"Expression","select":[{"from":"Author as Member","select":["Name"]}]}', '''
[
[
{
"_oid": "Expression:1008",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1011",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1012",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1013",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1014",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1015",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1019",
"Author": [
{
"_oid": "Member:1017",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1020",
"Author": [
{
"_oid": "Member:1017",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1021",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1022",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1023",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1024",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1025",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1026",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1027",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1028",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1029",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1030",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1031",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1032",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1033",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1034",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1035",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1036",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1037",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1038",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1039",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1040",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1041",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1042",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1043",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1044",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1045",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1046",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1050",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1051",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1052",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1053",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1054",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1067",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1068",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
]
'''
registerJson 'url', '{"from":"Expression","select":[{"from":"ExpressionsInConversation as Expression","select":[{"from":"Author as Member","select":["Name"]}]}]}', '''
[
[
{
"_oid": "Expression:1008",
"ExpressionsInConversation": [
{
"_oid": "Expression:1008",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1011",
"ExpressionsInConversation": [
{
"_oid": "Expression:1011",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1012",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1012",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1013",
"ExpressionsInConversation": [
{
"_oid": "Expression:1013",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1014",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1014",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1015",
"ExpressionsInConversation": [
{
"_oid": "Expression:1015",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1019",
"ExpressionsInConversation": [
{
"_oid": "Expression:1019",
"Author": [
{
"_oid": "Member:1017",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1020",
"ExpressionsInConversation": [
{
"_oid": "Expression:1020",
"Author": [
{
"_oid": "Member:1017",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1021",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1022",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1021",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1022",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1023",
"ExpressionsInConversation": [
{
"_oid": "Expression:1023",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1024",
"ExpressionsInConversation": [
{
"_oid": "Expression:1024",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1025",
"ExpressionsInConversation": [
{
"_oid": "Expression:1025",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1026",
"ExpressionsInConversation": [
{
"_oid": "Expression:1026",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1027",
"ExpressionsInConversation": [
{
"_oid": "Expression:1027",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1028",
"ExpressionsInConversation": [
{
"_oid": "Expression:1028",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1029",
"ExpressionsInConversation": [
{
"_oid": "Expression:1029",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1030",
"ExpressionsInConversation": [
{
"_oid": "Expression:1030",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1031",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1031",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1032",
"ExpressionsInConversation": [
{
"_oid": "Expression:1032",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1033",
"ExpressionsInConversation": [
{
"_oid": "Expression:1033",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1034",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1035",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1034",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1035",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1036",
"ExpressionsInConversation": [
{
"_oid": "Expression:1036",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1037",
"ExpressionsInConversation": [
{
"_oid": "Expression:1037",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1038",
"ExpressionsInConversation": [
{
"_oid": "Expression:1038",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1039",
"ExpressionsInConversation": [
{
"_oid": "Expression:1039",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1040",
"ExpressionsInConversation": [
{
"_oid": "Expression:1040",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1041",
"ExpressionsInConversation": [
{
"_oid": "Expression:1041",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1042",
"ExpressionsInConversation": [
{
"_oid": "Expression:1042",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1046",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1043",
"ExpressionsInConversation": [
{
"_oid": "Expression:1043",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1044",
"ExpressionsInConversation": [
{
"_oid": "Expression:1044",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1045",
"ExpressionsInConversation": [
{
"_oid": "Expression:1045",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1046",
"ExpressionsInConversation": []
},
{
"_oid": "Expression:1050",
"ExpressionsInConversation": [
{
"_oid": "Expression:1050",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1051",
"ExpressionsInConversation": [
{
"_oid": "Expression:1051",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
},
{
"_oid": "Expression:1068",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1052",
"ExpressionsInConversation": [
{
"_oid": "Expression:1052",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1053",
"ExpressionsInConversation": [
{
"_oid": "Expression:1053",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1054",
"ExpressionsInConversation": [
{
"_oid": "Expression:1054",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1067",
"ExpressionsInConversation": [
{
"_oid": "Expression:1067",
"Author": [
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
}
]
},
{
"_oid": "Expression:1068",
"ExpressionsInConversation": []
}
]
]
'''
registerJson 'url', '{"from":"Member","select":["Name"],"where":{"ID":"Member:1017"}}', '''
[
[
{
"_oid": "Member:1017",
"Name": "PI:NAME:<NAME>END_PI"
}
]
]
'''
registerJson 'url', '{"from":"Member","select":["Name"],"filter":["ParticipatesInConversations.@Count>\'4\'"]}', '''
[
[
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
},
{
"_oid": "Member:1049",
"Name": "PI:NAME:<NAME>END_PI"
}
]
]
'''
registerJson 'url', '{"from":"Member","select":["Name"],"where":{"Scopes.@Count":2}}', '''
[
[
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI"
}
]
]
'''
registerJson 'url', '{"from":"Member","select":["Name","ParticipatesInConversations.@Count",{"from":"ParticipatesInConversations as Expression","select":["Content"]}]}', '''
[
[
{
"_oid": "Member:20",
"Name": "PI:NAME:<NAME>END_PI",
"ParticipatesInConversations.@Count": "31",
"ParticipatesInConversations": [
{
"_oid": "Expression:1008",
"Content": "garbage!"
},
{
"_oid": "Expression:1011",
"Content": "test meats"
},
{
"_oid": "Expression:1013",
"Content": "trash!"
},
{
"_oid": "Expression:1015",
"Content": "conversation"
},
{
"_oid": "Expression:1020",
"Content": "hey people?!"
},
{
"_oid": "Expression:1023",
"Content": "moar"
},
{
"_oid": "Expression:1024",
"Content": "moar!!!"
},
{
"_oid": "Expression:1025",
"Content": "MOAR?!?!?!"
},
{
"_oid": "Expression:1026",
"Content": "what?!"
},
{
"_oid": "Expression:1027",
"Content": "maor?!"
},
{
"_oid": "Expression:1028",
"Content": "moar?!"
},
{
"_oid": "Expression:1029",
"Content": "evan MOAR?!"
},
{
"_oid": "Expression:1030",
"Content": "moars?!"
},
{
"_oid": "Expression:1032",
"Content": "here in test space"
},
{
"_oid": "Expression:1033",
"Content": "Talking about test in a space"
},
{
"_oid": "Expression:1036",
"Content": "10"
},
{
"_oid": "Expression:1037",
"Content": "9"
},
{
"_oid": "Expression:1038",
"Content": "8"
},
{
"_oid": "Expression:1039",
"Content": "7"
},
{
"_oid": "Expression:1040",
"Content": "6"
},
{
"_oid": "Expression:1041",
"Content": "5"
},
{
"_oid": "Expression:1042",
"Content": "4"
},
{
"_oid": "Expression:1043",
"Content": "3"
},
{
"_oid": "Expression:1044",
"Content": "2"
},
{
"_oid": "Expression:1045",
"Content": "1"
},
{
"_oid": "Expression:1050",
"Content": "hi"
},
{
"_oid": "Expression:1051",
"Content": "1"
},
{
"_oid": "Expression:1052",
"Content": "2"
},
{
"_oid": "Expression:1053",
"Content": "3"
},
{
"_oid": "Expression:1054",
"Content": "4"
},
{
"_oid": "Expression:1067",
"Content": "Space-ing it up!"
}
]
},
{
"_oid": "Member:1017",
"Name": "PI:NAME:<NAME>END_PI",
"ParticipatesInConversations.@Count": "2",
"ParticipatesInConversations": [
{
"_oid": "Expression:1019",
"Content": "Herro, anyone?"
},
{
"_oid": "Expression:1020",
"Content": "hey people?!"
}
]
},
{
"_oid": "Member:1047",
"Name": "PI:NAME:<NAME>END_PI",
"ParticipatesInConversations.@Count": "0",
"ParticipatesInConversations": []
},
{
"_oid": "Member:1048",
"Name": "PI:NAME:<NAME>END_PI",
"ParticipatesInConversations.@Count": "0",
"ParticipatesInConversations": []
},
{
"_oid": "Member:1049",
"Name": "PI:NAME:<NAME>END_PI",
"ParticipatesInConversations.@Count": "5",
"ParticipatesInConversations": [
{
"_oid": "Expression:1050",
"Content": "hi"
},
{
"_oid": "Expression:1051",
"Content": "1"
},
{
"_oid": "Expression:1052",
"Content": "2"
},
{
"_oid": "Expression:1053",
"Content": "3"
},
{
"_oid": "Expression:1054",
"Content": "4"
}
]
}
]
]
'''
registerJson 'url', "{\"from\":\"Member\"}\n---\n{\"from\":\"ExpressionSpace\"}", '''
[
[
{
"_oid": "Member:20"
},
{
"_oid": "Member:1017"
},
{
"_oid": "Member:1047"
},
{
"_oid": "Member:1048"
},
{
"_oid": "Member:1049"
}
],
[
{
"_oid": "ExpressionSpace:1005"
},
{
"_oid": "ExpressionSpace:1006"
},
{
"_oid": "ExpressionSpace:1007"
},
{
"_oid": "ExpressionSpace:1009"
},
{
"_oid": "ExpressionSpace:1055"
},
{
"_oid": "ExpressionSpace:1056"
},
{
"_oid": "ExpressionSpace:1057"
},
{
"_oid": "ExpressionSpace:1058"
},
{
"_oid": "ExpressionSpace:1059"
},
{
"_oid": "ExpressionSpace:1060"
},
{
"_oid": "ExpressionSpace:1061"
},
{
"_oid": "ExpressionSpace:1062"
},
{
"_oid": "ExpressionSpace:1063"
},
{
"_oid": "ExpressionSpace:1064"
},
{
"_oid": "ExpressionSpace:1065"
},
{
"_oid": "ExpressionSpace:1066"
}
]
]
'''
registerString '/VersionOne/rest-1.v1/Data/Expression', '<Asset></Asset>', '''
<Asset href="/VersionOne.Web/rest-1.v1/Data/Expression/1114/1245" id="Expression:1114:1245">
<Attribute name="Content">Hello</Attribute>
</Asset>
'''
registerJson 'url1', '{"from":"Timebox","sort":["EndDate"],"select":["Name"]}', '''
[
[
{
"_oid": "Timebox:1282",
"Name": "Sprint 1"
},
{
"_oid": "Timebox:1738",
"Name": "PI:NAME:<NAME>END_PI"
},
{
"_oid": "Timebox:1666",
"Name": "Sprint 4"
},
{
"_oid": "Timebox:1469",
"Name": "Sprint 2"
},
{
"_oid": "Timebox:1581",
"Name": "Sprint 3"
},
{
"_oid": "Timebox:1821",
"Name": "Sprint 7"
},
{
"_oid": "Timebox:1272",
"Name": "Month 1"
},
{
"_oid": "Timebox:1552",
"Name": "Month 2"
},
{
"_oid": "Timebox:1775",
"Name": "Sprint 5"
},
{
"_oid": "Timebox:1812",
"Name": "Sprint 6"
},
{
"_oid": "Timebox:1822",
"Name": "Month 3"
},
{
"_oid": "Timebox:2060",
"Name": "Iteration 5"
},
{
"_oid": "Timebox:2058",
"Name": "Iteration 4"
}
]
]
'''
registerJson 'url2', '{"from":"Timebox","sort":["EndDate"],"select":["Name"]}', '''
[
[
{
"_oid": "Timebox:2060",
"Name": "Iteration 5"
},
{
"_oid": "Timebox:1282",
"Name": "Sprint 1"
},
{
"_oid": "Timebox:1272",
"Name": "Month 1"
},
{
"_oid": "Timebox:1469",
"Name": "Sprint 2"
},
{
"_oid": "Timebox:1581",
"Name": "Sprint 3"
},
{
"_oid": "Timebox:1666",
"Name": "Sprint 4"
},
{
"_oid": "Timebox:1552",
"Name": "Month 2"
},
{
"_oid": "Timebox:1775",
"Name": "Sprint 5"
},
{
"_oid": "Timebox:1738",
"Name": "Kanban"
},
{
"_oid": "Timebox:1812",
"Name": "Sprint 6"
},
{
"_oid": "Timebox:1822",
"Name": "Month 3"
},
{
"_oid": "Timebox:1821",
"Name": "Sprint 7"
},
{
"_oid": "Timebox:2058",
"Name": "Iteration 4"
}
]
]
'''
|
[
{
"context": "# parsing Java code\n#\n# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# L",
"end": 57,
"score": 0.9998616576194763,
"start": 43,
"tag": "NAME",
"value": "JeongHoon Byun"
},
{
"context": "a code\n#\n# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# Licensed under ",
"end": 71,
"score": 0.8390121459960938,
"start": 63,
"tag": "USERNAME",
"value": "Outsider"
},
{
"context": "static\"\n column: [\n {\n key: \"accstfin\", display: \"access modifier - static - final|vola",
"end": 10840,
"score": 0.8928112983703613,
"start": 10832,
"tag": "KEY",
"value": "accstfin"
},
{
"context": " \"\"\"\n }\n {\n key: \"accfinst\", display: \"access modifier - final|volatile - st",
"end": 11159,
"score": 0.8359470367431641,
"start": 11151,
"tag": "KEY",
"value": "accfinst"
},
{
"context": " \"\"\"\n }\n {\n key: \"finaccst\", display: \"final|volatile - access modifier - st",
"end": 11478,
"score": 0.7603004574775696,
"start": 11470,
"tag": "KEY",
"value": "finaccst"
},
{
"context": " \"\"\"\n }\n {\n key: \"staccfin\", display: \"static - access modifier - final|vola",
"end": 11797,
"score": 0.8029853105545044,
"start": 11789,
"tag": "KEY",
"value": "staccfin"
}
] | src/parser/java-parser.coffee | uppalapatisujitha/CodingConventionofCommitHistory | 421 | # parsing Java code
#
# Copyright (c) 2013 JeongHoon Byun aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
helpers = require '../helpers'
_ = require 'underscore'
javaParser = module.exports =
lang: 'java'
parse: (line, convention, commitUrl) ->
convention = this.indent line, convention, commitUrl
convention = this.blockstatement line, convention, commitUrl
convention = this.constant line, convention, commitUrl
convention = this.conditionstatement line, convention, commitUrl
convention = this.argumentdef line, convention, commitUrl
convention = this.linelength line, convention, commitUrl
convention = this.staticvar line, convention, commitUrl
convention = this.finalstaticorder line, convention, commitUrl
indent: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.indent =
title: "Space vs. Tab"
column: [
{
key: "tab", display: "Tab",
code: """
public String getName() {
// use tab for indentation
return this.name;
}
"""
}
{
key: "space", display: "Space",
code: """
public String getName() {
return this.name;
}
"""
}
]
tab: 0
space: 0
commits: []
) unless convention.indent
tab = /^\t+.*/
space = /^\s+.*/
convention.indent.tab = convention.indent.tab + 1 if tab.test line
convention.indent.space = convention.indent.space + 1 if space.test line
convention.indent.commits.push commitUrl if tab.test(line) or space.test(line)
convention.indent.commits = _.uniq convention.indent.commits
convention
blockstatement: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.blockstatement =
title: "How to write block statement"
column: [
{
key: "onespace", display: "Curlybrace with one space",
code: """
if (height < MIN_HEIGHT) {
//..
}
while (isTrue) {
//..
}
switch (foo) {
//..
}
"""
}
{
key: "nospace", display: "Curlybrace with no space",
code: """
if (height < MIN_HEIGHT){
//..
}
while (isTrue){
//..
}
switch (foo){
//..
}
"""
}
{
key: "newline", display: "Curlybrace at new line",
code: """
if (height < MIN_HEIGHT)
{
//..
}
while (isTrue)
{
//..
}
switch (foo)
{
//..
}
"""
}
]
onespace: 0
nospace: 0
newline: 0
commits: []
) unless convention.blockstatement
onespace = /((if|while|switch|try).*\s+{)|(}\s+(else|catch|finally).*\s+{)/
nospace = /((if|while|switch).*\){)|(try|else|finally){|(}\s*(else|catch|finally).*\){)/
newline = /((if|while|switch).*\)\s*$)|((if|while|switch).*\)\s*\/[\/\*])|(try|else|finally)\s*\/[\/\*]|(^\s*(else|catch|finally))/
convention.blockstatement.onespace = convention.blockstatement.onespace + 1 if onespace.test line
convention.blockstatement.nospace = convention.blockstatement.nospace + 1 if nospace.test line
convention.blockstatement.newline = convention.blockstatement.newline + 1 if newline.test line
convention.blockstatement.commits.push commitUrl if onespace.test(line) or nospace.test(line) or newline.test(line)
convention.blockstatement.commits = _.uniq convention.blockstatement.commits
convention
constant: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.constant =
title: "Constant name is all caps?"
column: [
{
key: "allcaps", display: "Constant name is all caps with underscore(_)",
code: """
final static String FOO_BAR = \"baz\";
static final String FOO_BAR = \"baz\";
"""
}
{
key: "notallcaps", display: "Constant name is not all caps",
code: """
final static String foobar = \"baz\";
static final String foobar = \"baz\";
"""
}
]
allcaps: 0
notallcaps: 0
commits: []
) unless convention.constant
allcaps = /^\s*\w*\s*(static\s+\w*\s*final\s|final\s+\w*\s*static\s)\w+\s[A-Z0-9_]+(\s|=|;)/
notallcaps = /^\s*\w*\s*(static\s+\w*\s*final\s|final\s+\w*\s*static\s)\w+\s[a-zA-Z0-9_]+(\s|=|;)/
convention.constant.allcaps = convention.constant.allcaps + 1 if allcaps.test line
convention.constant.notallcaps = convention.constant.notallcaps + 1 if not allcaps.test(line) and notallcaps.test line
convention.constant.commits.push commitUrl if allcaps.test line or (not allcaps.test(line) and notallcaps.test line)
convention.constant.commits = _.uniq convention.constant.commits
convention
conditionstatement: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.conditionstatement =
title: "How to write conditional statement"
column: [
{
key: "onespace", display: "Condition with one space",
code: """
if (true) {
//...
}
while (true) {
//...
}
switch (v) {
//...
}
"""
}
{
key: "nospace", display: "Condition with no space",
code: """
if(true) {
//...
}
while(true) {
//...
}
switch(v) {
//...
}
"""
}
]
onespace: 0
nospace: 0
commits: []
) unless convention.conditionstatement
onespace = /(if|while|switch)\s+\(/
nospace = /(if|while|switch)\(/
convention.conditionstatement.onespace = convention.conditionstatement.onespace + 1 if onespace.test line
convention.conditionstatement.nospace = convention.conditionstatement.nospace + 1 if nospace.test line
convention.conditionstatement.commits.push commitUrl if onespace.test(line) or nospace.test(line)
convention.conditionstatement.commits = _.uniq convention.conditionstatement.commits
convention
argumentdef: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.argumentdef =
title: "Arguments definition with one space vs. no space"
column: [
{
key: "onespace", display: "One space",
code: """
public void setName( String name ) {
// ...
}
if( isTrue ) {}
while( isTrue ) {}
"""
}
{
key: "nospace", display: "No space",
code: """
public void setName(String name) {
// ...
}
if(isTrue) {}
while(isTrue) {}
"""
}
]
onespace: 0
nospace: 0
commits: []
) unless convention.argumentdef
onespace = /^(\s*|\t*)(\w+\s+\w+\s+\w+|if|while|switch)\s*\(\s+/
nospace = /^(\s*|\t*)(\w+\s+\w+\s+\w+|if|while|switch)\s*\(\S+/
convention.argumentdef.onespace = convention.argumentdef.onespace + 1 if onespace.test line
convention.argumentdef.nospace = convention.argumentdef.nospace + 1 if nospace.test line
convention.argumentdef.commits.push commitUrl if onespace.test(line) or nospace.test(line)
convention.argumentdef.commits = _.uniq convention.argumentdef.commits
convention
linelength: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.linelength =
title: "Line length is over 80 characters?"
column: [
{
key: "char80", display: "Line length is within 80 characters.",
code: "/* width is within 80 characters */"
}
{
key: "char120", display: "Line length is within 120 characters",
code: "/* width is within 120 characters */"
}
{
key: "char150", display: "Line length is within 150 characters",
code: "/* width is within 150 characters */"
}
]
char80: 0
char120: 0
char150: 0
commits: []
) unless convention.linelength
width = line.length
tabcount = line.split('\t').length - 1
# assume tab size is 4 space
width += tabcount * 3
if width < 80
convention.linelength.char80 = convention.linelength.char80 + 1
else if width < 120
convention.linelength.char120 = convention.linelength.char120 + 1
else
convention.linelength.char150 = convention.linelength.char150 + 1
convention.linelength.commits.push commitUrl
convention.linelength.commits = _.uniq convention.linelength.commits
convention
staticvar: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.staticvar =
title: "Use special prefix for staticvar"
column: [
{
key: "prefix", display: "Special prefix",
code: "static String _name;"
}
{
key: "noprefix", display: "No special prefix",
code: "static String name"
}
]
prefix: 0
noprefix: 0
commits: []
) unless convention.staticvar
prefix = /static\s+\w+\s+(_|\$)\w+/
noprefix = /static\s+\w+\s+[^_$]\w+/
convention.staticvar.prefix = convention.staticvar.prefix + 1 if prefix.test line
convention.staticvar.noprefix = convention.staticvar.noprefix + 1 if noprefix.test line
convention.staticvar.commits.push commitUrl if prefix.test(line) or noprefix.test(line)
convention.staticvar.commits = _.uniq convention.staticvar.commits
convention
finalstaticorder: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.finalstaticorder =
title: "order for final and static"
column: [
{
key: "accstfin", display: "access modifier - static - final|volatile",
code: """
public static final String t1 = "";
public static transient final String t2 = "";
transient public static final String t3 = "";
"""
}
{
key: "accfinst", display: "access modifier - final|volatile - static",
code: """
public final static String t1 = "";
public final static transient String t2 = "";
transient public final static String t3 = "";
"""
}
{
key: "finaccst", display: "final|volatile - access modifier - static",
code: """
final public static String t1 = "";
final public static transient String t2 = "";
final transient public static String t3 = "";
"""
}
{
key: "staccfin", display: "static - access modifier - final|volatile",
code: """
static public final String t1 = "";
static public transient final String t2 = "";
static transient public final String t3 = "";
"""
}
]
accstfin: 0
accfinst: 0
finaccst: 0
staccfin: 0
commits: []
) unless convention.finalstaticorder
accstfin = /^\w*\s*(public|private|protected){1}\s+\w*\s*(static){1}\s+\w*\s*(final|volatile){1}\s+\w+\s+[a-zA-Z0-9_]+(\s|=|;)/
accfinst = /^\w*\s*(public|private|protected){1}\s+\w*\s*(final|volatile){1}\s+\w*\s*(static){1}\s+\w+\s+[a-zA-Z0-9_]+(\s|=|;)/
finaccst = /^\w*\s*(final|volatile){1}\s+\w*\s*(public|private|protected){1}\s+\w*\s*(static){1}\s+\w+\s+[a-zA-Z0-9_]+(\s|=|;)/
staccfin = /^\w*\s*(static){1}\s+\w*\s*(public|private|protected){1}\s+\w*\s*(final|volatile){1}\s+\w+\s+[a-zA-Z0-9_]+(\s|=|;)/
convention.finalstaticorder.accstfin = convention.finalstaticorder.accstfin + 1 if accstfin.test line
convention.finalstaticorder.accfinst = convention.finalstaticorder.accfinst + 1 if accfinst.test line
convention.finalstaticorder.finaccst = convention.finalstaticorder.finaccst + 1 if finaccst.test line
convention.finalstaticorder.staccfin = convention.finalstaticorder.staccfin + 1 if staccfin.test line
convention.finalstaticorder.commits.push commitUrl if accstfin.test line or accfinst.test line or finaccst.test line or staccfin.test line
convention.finalstaticorder.commits = _.uniq convention.finalstaticorder.commits
convention
| 60997 | # parsing Java code
#
# Copyright (c) 2013 <NAME> aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
helpers = require '../helpers'
_ = require 'underscore'
javaParser = module.exports =
lang: 'java'
parse: (line, convention, commitUrl) ->
convention = this.indent line, convention, commitUrl
convention = this.blockstatement line, convention, commitUrl
convention = this.constant line, convention, commitUrl
convention = this.conditionstatement line, convention, commitUrl
convention = this.argumentdef line, convention, commitUrl
convention = this.linelength line, convention, commitUrl
convention = this.staticvar line, convention, commitUrl
convention = this.finalstaticorder line, convention, commitUrl
indent: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.indent =
title: "Space vs. Tab"
column: [
{
key: "tab", display: "Tab",
code: """
public String getName() {
// use tab for indentation
return this.name;
}
"""
}
{
key: "space", display: "Space",
code: """
public String getName() {
return this.name;
}
"""
}
]
tab: 0
space: 0
commits: []
) unless convention.indent
tab = /^\t+.*/
space = /^\s+.*/
convention.indent.tab = convention.indent.tab + 1 if tab.test line
convention.indent.space = convention.indent.space + 1 if space.test line
convention.indent.commits.push commitUrl if tab.test(line) or space.test(line)
convention.indent.commits = _.uniq convention.indent.commits
convention
blockstatement: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.blockstatement =
title: "How to write block statement"
column: [
{
key: "onespace", display: "Curlybrace with one space",
code: """
if (height < MIN_HEIGHT) {
//..
}
while (isTrue) {
//..
}
switch (foo) {
//..
}
"""
}
{
key: "nospace", display: "Curlybrace with no space",
code: """
if (height < MIN_HEIGHT){
//..
}
while (isTrue){
//..
}
switch (foo){
//..
}
"""
}
{
key: "newline", display: "Curlybrace at new line",
code: """
if (height < MIN_HEIGHT)
{
//..
}
while (isTrue)
{
//..
}
switch (foo)
{
//..
}
"""
}
]
onespace: 0
nospace: 0
newline: 0
commits: []
) unless convention.blockstatement
onespace = /((if|while|switch|try).*\s+{)|(}\s+(else|catch|finally).*\s+{)/
nospace = /((if|while|switch).*\){)|(try|else|finally){|(}\s*(else|catch|finally).*\){)/
newline = /((if|while|switch).*\)\s*$)|((if|while|switch).*\)\s*\/[\/\*])|(try|else|finally)\s*\/[\/\*]|(^\s*(else|catch|finally))/
convention.blockstatement.onespace = convention.blockstatement.onespace + 1 if onespace.test line
convention.blockstatement.nospace = convention.blockstatement.nospace + 1 if nospace.test line
convention.blockstatement.newline = convention.blockstatement.newline + 1 if newline.test line
convention.blockstatement.commits.push commitUrl if onespace.test(line) or nospace.test(line) or newline.test(line)
convention.blockstatement.commits = _.uniq convention.blockstatement.commits
convention
constant: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.constant =
title: "Constant name is all caps?"
column: [
{
key: "allcaps", display: "Constant name is all caps with underscore(_)",
code: """
final static String FOO_BAR = \"baz\";
static final String FOO_BAR = \"baz\";
"""
}
{
key: "notallcaps", display: "Constant name is not all caps",
code: """
final static String foobar = \"baz\";
static final String foobar = \"baz\";
"""
}
]
allcaps: 0
notallcaps: 0
commits: []
) unless convention.constant
allcaps = /^\s*\w*\s*(static\s+\w*\s*final\s|final\s+\w*\s*static\s)\w+\s[A-Z0-9_]+(\s|=|;)/
notallcaps = /^\s*\w*\s*(static\s+\w*\s*final\s|final\s+\w*\s*static\s)\w+\s[a-zA-Z0-9_]+(\s|=|;)/
convention.constant.allcaps = convention.constant.allcaps + 1 if allcaps.test line
convention.constant.notallcaps = convention.constant.notallcaps + 1 if not allcaps.test(line) and notallcaps.test line
convention.constant.commits.push commitUrl if allcaps.test line or (not allcaps.test(line) and notallcaps.test line)
convention.constant.commits = _.uniq convention.constant.commits
convention
conditionstatement: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.conditionstatement =
title: "How to write conditional statement"
column: [
{
key: "onespace", display: "Condition with one space",
code: """
if (true) {
//...
}
while (true) {
//...
}
switch (v) {
//...
}
"""
}
{
key: "nospace", display: "Condition with no space",
code: """
if(true) {
//...
}
while(true) {
//...
}
switch(v) {
//...
}
"""
}
]
onespace: 0
nospace: 0
commits: []
) unless convention.conditionstatement
onespace = /(if|while|switch)\s+\(/
nospace = /(if|while|switch)\(/
convention.conditionstatement.onespace = convention.conditionstatement.onespace + 1 if onespace.test line
convention.conditionstatement.nospace = convention.conditionstatement.nospace + 1 if nospace.test line
convention.conditionstatement.commits.push commitUrl if onespace.test(line) or nospace.test(line)
convention.conditionstatement.commits = _.uniq convention.conditionstatement.commits
convention
argumentdef: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.argumentdef =
title: "Arguments definition with one space vs. no space"
column: [
{
key: "onespace", display: "One space",
code: """
public void setName( String name ) {
// ...
}
if( isTrue ) {}
while( isTrue ) {}
"""
}
{
key: "nospace", display: "No space",
code: """
public void setName(String name) {
// ...
}
if(isTrue) {}
while(isTrue) {}
"""
}
]
onespace: 0
nospace: 0
commits: []
) unless convention.argumentdef
onespace = /^(\s*|\t*)(\w+\s+\w+\s+\w+|if|while|switch)\s*\(\s+/
nospace = /^(\s*|\t*)(\w+\s+\w+\s+\w+|if|while|switch)\s*\(\S+/
convention.argumentdef.onespace = convention.argumentdef.onespace + 1 if onespace.test line
convention.argumentdef.nospace = convention.argumentdef.nospace + 1 if nospace.test line
convention.argumentdef.commits.push commitUrl if onespace.test(line) or nospace.test(line)
convention.argumentdef.commits = _.uniq convention.argumentdef.commits
convention
linelength: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.linelength =
title: "Line length is over 80 characters?"
column: [
{
key: "char80", display: "Line length is within 80 characters.",
code: "/* width is within 80 characters */"
}
{
key: "char120", display: "Line length is within 120 characters",
code: "/* width is within 120 characters */"
}
{
key: "char150", display: "Line length is within 150 characters",
code: "/* width is within 150 characters */"
}
]
char80: 0
char120: 0
char150: 0
commits: []
) unless convention.linelength
width = line.length
tabcount = line.split('\t').length - 1
# assume tab size is 4 space
width += tabcount * 3
if width < 80
convention.linelength.char80 = convention.linelength.char80 + 1
else if width < 120
convention.linelength.char120 = convention.linelength.char120 + 1
else
convention.linelength.char150 = convention.linelength.char150 + 1
convention.linelength.commits.push commitUrl
convention.linelength.commits = _.uniq convention.linelength.commits
convention
staticvar: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.staticvar =
title: "Use special prefix for staticvar"
column: [
{
key: "prefix", display: "Special prefix",
code: "static String _name;"
}
{
key: "noprefix", display: "No special prefix",
code: "static String name"
}
]
prefix: 0
noprefix: 0
commits: []
) unless convention.staticvar
prefix = /static\s+\w+\s+(_|\$)\w+/
noprefix = /static\s+\w+\s+[^_$]\w+/
convention.staticvar.prefix = convention.staticvar.prefix + 1 if prefix.test line
convention.staticvar.noprefix = convention.staticvar.noprefix + 1 if noprefix.test line
convention.staticvar.commits.push commitUrl if prefix.test(line) or noprefix.test(line)
convention.staticvar.commits = _.uniq convention.staticvar.commits
convention
finalstaticorder: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.finalstaticorder =
title: "order for final and static"
column: [
{
key: "<KEY>", display: "access modifier - static - final|volatile",
code: """
public static final String t1 = "";
public static transient final String t2 = "";
transient public static final String t3 = "";
"""
}
{
key: "<KEY>", display: "access modifier - final|volatile - static",
code: """
public final static String t1 = "";
public final static transient String t2 = "";
transient public final static String t3 = "";
"""
}
{
key: "<KEY>", display: "final|volatile - access modifier - static",
code: """
final public static String t1 = "";
final public static transient String t2 = "";
final transient public static String t3 = "";
"""
}
{
key: "<KEY>", display: "static - access modifier - final|volatile",
code: """
static public final String t1 = "";
static public transient final String t2 = "";
static transient public final String t3 = "";
"""
}
]
accstfin: 0
accfinst: 0
finaccst: 0
staccfin: 0
commits: []
) unless convention.finalstaticorder
accstfin = /^\w*\s*(public|private|protected){1}\s+\w*\s*(static){1}\s+\w*\s*(final|volatile){1}\s+\w+\s+[a-zA-Z0-9_]+(\s|=|;)/
accfinst = /^\w*\s*(public|private|protected){1}\s+\w*\s*(final|volatile){1}\s+\w*\s*(static){1}\s+\w+\s+[a-zA-Z0-9_]+(\s|=|;)/
finaccst = /^\w*\s*(final|volatile){1}\s+\w*\s*(public|private|protected){1}\s+\w*\s*(static){1}\s+\w+\s+[a-zA-Z0-9_]+(\s|=|;)/
staccfin = /^\w*\s*(static){1}\s+\w*\s*(public|private|protected){1}\s+\w*\s*(final|volatile){1}\s+\w+\s+[a-zA-Z0-9_]+(\s|=|;)/
convention.finalstaticorder.accstfin = convention.finalstaticorder.accstfin + 1 if accstfin.test line
convention.finalstaticorder.accfinst = convention.finalstaticorder.accfinst + 1 if accfinst.test line
convention.finalstaticorder.finaccst = convention.finalstaticorder.finaccst + 1 if finaccst.test line
convention.finalstaticorder.staccfin = convention.finalstaticorder.staccfin + 1 if staccfin.test line
convention.finalstaticorder.commits.push commitUrl if accstfin.test line or accfinst.test line or finaccst.test line or staccfin.test line
convention.finalstaticorder.commits = _.uniq convention.finalstaticorder.commits
convention
| true | # parsing Java code
#
# Copyright (c) 2013 PI:NAME:<NAME>END_PI aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
helpers = require '../helpers'
_ = require 'underscore'
javaParser = module.exports =
lang: 'java'
parse: (line, convention, commitUrl) ->
convention = this.indent line, convention, commitUrl
convention = this.blockstatement line, convention, commitUrl
convention = this.constant line, convention, commitUrl
convention = this.conditionstatement line, convention, commitUrl
convention = this.argumentdef line, convention, commitUrl
convention = this.linelength line, convention, commitUrl
convention = this.staticvar line, convention, commitUrl
convention = this.finalstaticorder line, convention, commitUrl
indent: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.indent =
title: "Space vs. Tab"
column: [
{
key: "tab", display: "Tab",
code: """
public String getName() {
// use tab for indentation
return this.name;
}
"""
}
{
key: "space", display: "Space",
code: """
public String getName() {
return this.name;
}
"""
}
]
tab: 0
space: 0
commits: []
) unless convention.indent
tab = /^\t+.*/
space = /^\s+.*/
convention.indent.tab = convention.indent.tab + 1 if tab.test line
convention.indent.space = convention.indent.space + 1 if space.test line
convention.indent.commits.push commitUrl if tab.test(line) or space.test(line)
convention.indent.commits = _.uniq convention.indent.commits
convention
blockstatement: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.blockstatement =
title: "How to write block statement"
column: [
{
key: "onespace", display: "Curlybrace with one space",
code: """
if (height < MIN_HEIGHT) {
//..
}
while (isTrue) {
//..
}
switch (foo) {
//..
}
"""
}
{
key: "nospace", display: "Curlybrace with no space",
code: """
if (height < MIN_HEIGHT){
//..
}
while (isTrue){
//..
}
switch (foo){
//..
}
"""
}
{
key: "newline", display: "Curlybrace at new line",
code: """
if (height < MIN_HEIGHT)
{
//..
}
while (isTrue)
{
//..
}
switch (foo)
{
//..
}
"""
}
]
onespace: 0
nospace: 0
newline: 0
commits: []
) unless convention.blockstatement
onespace = /((if|while|switch|try).*\s+{)|(}\s+(else|catch|finally).*\s+{)/
nospace = /((if|while|switch).*\){)|(try|else|finally){|(}\s*(else|catch|finally).*\){)/
newline = /((if|while|switch).*\)\s*$)|((if|while|switch).*\)\s*\/[\/\*])|(try|else|finally)\s*\/[\/\*]|(^\s*(else|catch|finally))/
convention.blockstatement.onespace = convention.blockstatement.onespace + 1 if onespace.test line
convention.blockstatement.nospace = convention.blockstatement.nospace + 1 if nospace.test line
convention.blockstatement.newline = convention.blockstatement.newline + 1 if newline.test line
convention.blockstatement.commits.push commitUrl if onespace.test(line) or nospace.test(line) or newline.test(line)
convention.blockstatement.commits = _.uniq convention.blockstatement.commits
convention
constant: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.constant =
title: "Constant name is all caps?"
column: [
{
key: "allcaps", display: "Constant name is all caps with underscore(_)",
code: """
final static String FOO_BAR = \"baz\";
static final String FOO_BAR = \"baz\";
"""
}
{
key: "notallcaps", display: "Constant name is not all caps",
code: """
final static String foobar = \"baz\";
static final String foobar = \"baz\";
"""
}
]
allcaps: 0
notallcaps: 0
commits: []
) unless convention.constant
allcaps = /^\s*\w*\s*(static\s+\w*\s*final\s|final\s+\w*\s*static\s)\w+\s[A-Z0-9_]+(\s|=|;)/
notallcaps = /^\s*\w*\s*(static\s+\w*\s*final\s|final\s+\w*\s*static\s)\w+\s[a-zA-Z0-9_]+(\s|=|;)/
convention.constant.allcaps = convention.constant.allcaps + 1 if allcaps.test line
convention.constant.notallcaps = convention.constant.notallcaps + 1 if not allcaps.test(line) and notallcaps.test line
convention.constant.commits.push commitUrl if allcaps.test line or (not allcaps.test(line) and notallcaps.test line)
convention.constant.commits = _.uniq convention.constant.commits
convention
conditionstatement: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.conditionstatement =
title: "How to write conditional statement"
column: [
{
key: "onespace", display: "Condition with one space",
code: """
if (true) {
//...
}
while (true) {
//...
}
switch (v) {
//...
}
"""
}
{
key: "nospace", display: "Condition with no space",
code: """
if(true) {
//...
}
while(true) {
//...
}
switch(v) {
//...
}
"""
}
]
onespace: 0
nospace: 0
commits: []
) unless convention.conditionstatement
onespace = /(if|while|switch)\s+\(/
nospace = /(if|while|switch)\(/
convention.conditionstatement.onespace = convention.conditionstatement.onespace + 1 if onespace.test line
convention.conditionstatement.nospace = convention.conditionstatement.nospace + 1 if nospace.test line
convention.conditionstatement.commits.push commitUrl if onespace.test(line) or nospace.test(line)
convention.conditionstatement.commits = _.uniq convention.conditionstatement.commits
convention
argumentdef: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.argumentdef =
title: "Arguments definition with one space vs. no space"
column: [
{
key: "onespace", display: "One space",
code: """
public void setName( String name ) {
// ...
}
if( isTrue ) {}
while( isTrue ) {}
"""
}
{
key: "nospace", display: "No space",
code: """
public void setName(String name) {
// ...
}
if(isTrue) {}
while(isTrue) {}
"""
}
]
onespace: 0
nospace: 0
commits: []
) unless convention.argumentdef
onespace = /^(\s*|\t*)(\w+\s+\w+\s+\w+|if|while|switch)\s*\(\s+/
nospace = /^(\s*|\t*)(\w+\s+\w+\s+\w+|if|while|switch)\s*\(\S+/
convention.argumentdef.onespace = convention.argumentdef.onespace + 1 if onespace.test line
convention.argumentdef.nospace = convention.argumentdef.nospace + 1 if nospace.test line
convention.argumentdef.commits.push commitUrl if onespace.test(line) or nospace.test(line)
convention.argumentdef.commits = _.uniq convention.argumentdef.commits
convention
linelength: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.linelength =
title: "Line length is over 80 characters?"
column: [
{
key: "char80", display: "Line length is within 80 characters.",
code: "/* width is within 80 characters */"
}
{
key: "char120", display: "Line length is within 120 characters",
code: "/* width is within 120 characters */"
}
{
key: "char150", display: "Line length is within 150 characters",
code: "/* width is within 150 characters */"
}
]
char80: 0
char120: 0
char150: 0
commits: []
) unless convention.linelength
width = line.length
tabcount = line.split('\t').length - 1
# assume tab size is 4 space
width += tabcount * 3
if width < 80
convention.linelength.char80 = convention.linelength.char80 + 1
else if width < 120
convention.linelength.char120 = convention.linelength.char120 + 1
else
convention.linelength.char150 = convention.linelength.char150 + 1
convention.linelength.commits.push commitUrl
convention.linelength.commits = _.uniq convention.linelength.commits
convention
staticvar: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.staticvar =
title: "Use special prefix for staticvar"
column: [
{
key: "prefix", display: "Special prefix",
code: "static String _name;"
}
{
key: "noprefix", display: "No special prefix",
code: "static String name"
}
]
prefix: 0
noprefix: 0
commits: []
) unless convention.staticvar
prefix = /static\s+\w+\s+(_|\$)\w+/
noprefix = /static\s+\w+\s+[^_$]\w+/
convention.staticvar.prefix = convention.staticvar.prefix + 1 if prefix.test line
convention.staticvar.noprefix = convention.staticvar.noprefix + 1 if noprefix.test line
convention.staticvar.commits.push commitUrl if prefix.test(line) or noprefix.test(line)
convention.staticvar.commits = _.uniq convention.staticvar.commits
convention
finalstaticorder: (line, convention, commitUrl) ->
convention = {lang: this.lang} unless convention
(convention.finalstaticorder =
title: "order for final and static"
column: [
{
key: "PI:KEY:<KEY>END_PI", display: "access modifier - static - final|volatile",
code: """
public static final String t1 = "";
public static transient final String t2 = "";
transient public static final String t3 = "";
"""
}
{
key: "PI:KEY:<KEY>END_PI", display: "access modifier - final|volatile - static",
code: """
public final static String t1 = "";
public final static transient String t2 = "";
transient public final static String t3 = "";
"""
}
{
key: "PI:KEY:<KEY>END_PI", display: "final|volatile - access modifier - static",
code: """
final public static String t1 = "";
final public static transient String t2 = "";
final transient public static String t3 = "";
"""
}
{
key: "PI:KEY:<KEY>END_PI", display: "static - access modifier - final|volatile",
code: """
static public final String t1 = "";
static public transient final String t2 = "";
static transient public final String t3 = "";
"""
}
]
accstfin: 0
accfinst: 0
finaccst: 0
staccfin: 0
commits: []
) unless convention.finalstaticorder
accstfin = /^\w*\s*(public|private|protected){1}\s+\w*\s*(static){1}\s+\w*\s*(final|volatile){1}\s+\w+\s+[a-zA-Z0-9_]+(\s|=|;)/
accfinst = /^\w*\s*(public|private|protected){1}\s+\w*\s*(final|volatile){1}\s+\w*\s*(static){1}\s+\w+\s+[a-zA-Z0-9_]+(\s|=|;)/
finaccst = /^\w*\s*(final|volatile){1}\s+\w*\s*(public|private|protected){1}\s+\w*\s*(static){1}\s+\w+\s+[a-zA-Z0-9_]+(\s|=|;)/
staccfin = /^\w*\s*(static){1}\s+\w*\s*(public|private|protected){1}\s+\w*\s*(final|volatile){1}\s+\w+\s+[a-zA-Z0-9_]+(\s|=|;)/
convention.finalstaticorder.accstfin = convention.finalstaticorder.accstfin + 1 if accstfin.test line
convention.finalstaticorder.accfinst = convention.finalstaticorder.accfinst + 1 if accfinst.test line
convention.finalstaticorder.finaccst = convention.finalstaticorder.finaccst + 1 if finaccst.test line
convention.finalstaticorder.staccfin = convention.finalstaticorder.staccfin + 1 if staccfin.test line
convention.finalstaticorder.commits.push commitUrl if accstfin.test line or accfinst.test line or finaccst.test line or staccfin.test line
convention.finalstaticorder.commits = _.uniq convention.finalstaticorder.commits
convention
|
[
{
"context": " alert = {\n key: 'savefail'\n contextcolor: 'danger'\n ",
"end": 4840,
"score": 0.8316352367401123,
"start": 4832,
"tag": "KEY",
"value": "savefail"
},
{
"context": " alert = {\n key: 'savefail'\n contextcolor: 'danger'\n ",
"end": 5861,
"score": 0.7946112155914307,
"start": 5853,
"tag": "KEY",
"value": "savefail"
},
{
"context": " title: 'Success!'\n key: 'savesuccess'\n message: 'Settings saved",
"end": 15779,
"score": 0.9913135170936584,
"start": 15768,
"tag": "KEY",
"value": "savesuccess"
}
] | clients/apps/accountspayable/accountspayable.cjsx | 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.
*/
define([
'react', 'react-dom',
'gettext', 'signals', 'utils',
'jslink/JsLink', 'jslink/ToiSetWatcher', 'jslink/query', 'jslink/commit',
'widgets/amount', 'widgets/date',
'widgets/accountspayable/main',
'widgets/accountspayable/authorize',
'widgets/accountspayable/fileuploader',
'widgets/accountspayable/settings',
'widgets/accountspayable/alerts',
'classnames',
], ->
[React, ReactDOM,
gettext, signals, utils,
JsLink, ToiSetWatcher, query, commit,
Amount, DatePicker,
Main,
Authorize,
Fileuploader,
Settings,
Alerts,
classnames,
] = arguments
gettext.install('client')
_ = gettext.gettext
orgid = document.location.pathname.split('/')[-1..][0]
# Data link setup
jsLink = new JsLink('/jslink')
# Queries
SIattrList = [
'org',
'accounted',
'invoiceState',
'automated',
'recipient',
'invoiceType',
'amount',
'transferMethod',
'pgnum',
'bgnum',
'bankaccount',
'bankclearing',
#'transferAddress',
'invoiceIdentifierType',
'ocr',
'invoiceNumber',
'message',
#'invoiceIdentifier',
'registrationVerification',
'transferVerification',
'invoiceDate',
'dateInvoiceRegistered',
'transferDate',
'dueDate',
'rejected_log',
'images']
startdate=''
stopdate='a'
setQueryDates = (start, stop) =>
console.log('querydates', start, stop)
startdate = start
stopdate = stop or 'a'
supplierInvoiceQuery.link.deactivate()
supplierInvoiceQuery.result = []
supplierInvoiceQuery.toiData = {}
supplierInvoiceQuery.condGroups = []
if start.length > 0 or stop.length > 0
supplierInvoiceQuery.push({'org': orgid, 'transferDate': new query.Operator.Between(startdate, stopdate)})
else
supplierInvoiceQuery.push({'org': orgid})
supplierInvoiceQuery.start()
supplierInvoiceQuery = new query.SortedQuery(
jsLink, 'accounting.SupplierInvoice', {'org': orgid}
)
supplierInvoiceQuery.attrList = SIattrList
supplierInvoiceQuery.sorting = 'transferDate'
accountingYearQuery = new query.SortedQuery(
jsLink, 'accounting.Org', {'id': orgid}
)
accountingYearQuery.attrList = ['current_accounting']
accountsQuery = new query.SortedQuery(
jsLink, 'accounting.Account'
)
accountsQuery.attrList = ['name', 'number']
accountsQuery.sorting = 'number'
seriesQuery = new query.SortedQuery(
jsLink, 'accounting.VerificationSeries'
)
seriesQuery.attrList = ['name', 'description']
providerQuery = new query.SortedQuery(
jsLink, 'accounting.SupplierInvoiceProvider', {'org': orgid}
)
providerQuery.attrList = ['series', 'account', 'bank_account', 'transferVerification_text', 'plusgiro_sending_bank_account']
imageQuery = new query.SortedQuery(
jsLink, 'accounting.InvoiceImage'
)
imageQuery.attrList = ['filename']
verificationsWatcher = new ToiSetWatcher(
jsLink, 'accounting.Verification', ['transactions', 'version', 'series', 'number']
)
transactionsWatcher = new ToiSetWatcher(
jsLink, 'accounting.Transactions', ['account', 'amount', 'text', 'version']
)
recipients = undefined
# Div functions
#_setQueryArgs = (newargs) =>
# newargs['org'] = orgid
# si_query_args = newargs
# supplierInvoiceQuery.start()
# console.log(si_query_args, newargs)
#_delQueryArgs = (delargs) =>
# console.log(si_query_args)
# for arg in delargs
# if arg != 'org'
# delete si_query_args[arg]
# supplierInvoiceQuery.start()
# BLM functions
createSupplierInvoice = (invoice, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.saveSupplierInvoice',
[[orgid],[invoice]], (result) =>
if result.error?
console.log(result.error)
createStatus = 'failure'
alert = {
key: 'savefail'
contextcolor: 'danger'
title: 'Failure!'
message: 'Invoice record could not be created. {err}.'
messageattrs: {
err: utils.get_error_message(result.error)
}
}
renderAlerts([alert])
else
createStatus = 'success'
createResult = result.result
renderAlerts([], [{key: 'savefail'}])
callback(createStatus)
renderApp()
)
updateSupplierInvoice = (toid, invoice, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.saveSupplierInvoice',
[[orgid], [invoice], [toid]], (result) =>
if result.error?
console.log(result.error)
updateStatus = 'failure'
alert = {
key: 'savefail'
contextcolor: 'danger'
title: 'Failure!'
message: 'Failed to save invoice record. {err}.'
messageattrs:
err: utils.get_error_message(result.error)
}
renderAlerts([alert])
else
updateStatus = 'success'
updateResult = result.result
renderAlerts([], [{key: 'savefail'}])
callback(updateStatus)
renderApp()
)
deleteSupplierInvoice = (siToiList) =>
commit.callBlmMethod(
jsLink,
'accounting.deleteSupplierInvoice',
[[orgid], siToiList], (result) =>
if result.error?
deleteStatus = 'failure'
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: 'Delete command failed. {err}'
messageattrs: {err: result.error.args}
}])
else
deleteStatus = 'success'
deleteResult = result.result
if deleteResult.deleted.length > 0
renderAlerts([{
contextcolor: 'success'
title: 'Success!'
message: 'Deleted {del} drafts.'
messageattrs: {
del: deleteResult.deleted.length,
unt: deleteResult.untouched.length
}
}])
renderApp()
)
proposeRecipients = () =>
commit.callBlmMethod(
jsLink,
'accounting.proposeRecipients',
[[orgid]], (result) =>
if result.error?
status = 'failure'
else
status = 'success'
recipients = result.result
renderApp()
)
fetchPredictions = (recipient, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.predictSupplierInvoice',
[[orgid], [recipient]], (result) =>
if result.error?
# Handle failure
predictStatus = 'failure'
else
predictStatus = 'success'
prediction = result.result
callback(prediction)
renderApp()
)
setSIState = (siToiList, newstate, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.setSIState',
[[orgid], siToiList, [newstate]], (result) =>
callback()
if result.error?
updateStatus = 'failure'
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: '{err}.'
messageattrs: {err: utils.get_error_message(result.error)}
}])
else
updateStatus = 'success'
updateResult = result.result
if updateResult['updated'] > 0
renderAlerts([{
contextcolor: 'success'
title: 'Success!'
message: '{mod} of the {sel} selected set to {state}.'
messageattrs: {
mod: updateResult['updated'],
sel: updateResult['selected'],
state: newstate
}
}])
if updateResult['complaints'].length > 0
renderAlerts([{
contextcolor: 'warning'
title: 'Warning!'
message: 'Some states could not be changed due to the following reasons: {reasons}'
messageattrs: {reasons: updateResult['complaints']}
}])
)
enableSIAutomation = (siToiList, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.requestSIAutomation',
[[orgid], siToiList], (result) =>
if result.error?
if result.error.args?
message = result.error.args[0]
else
message = result.error
renderAlerts([
contextcolor: 'danger'
title: 'Failure.'
message: message
])
else
signRef = result.result[0]
renderAuthorization(signRef)
callback()
)
disableSIAutomation = (siToiList, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.disableSIAutomation',
[[orgid], siToiList], (result) =>
callback()
if result.error?
if utils.is_permission_error(result.error)
renderAlerts([
contextcolor: 'danger'
title: 'Permission denied.'
message: 'You do not have permission to schedule automatic payments.'
])
updateStatus = 'failure'
else
updateStatus = 'success'
updateResult = result.result
if updateResult['updated'] > 0
renderAlerts([{
contextcolor: 'success'
title: 'Success!'
message: 'Disabled automated payment for {mod} of the {sel} selected.'
messageattrs: {
mod: updateResult['updated'],
sel: updateResult['selected'],
}
}])
if updateResult['complaints'].length > 0
renderAlerts([{
contextcolor: 'warning'
title: 'Warning!'
message: 'Failed to disable automation for the following reasons: {reasons}'
messageattrs: {reasons: updateResult['complaints']}
}])
)
createTransferVerification = (siToiList, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.createTransferVerification',
[[orgid], siToiList], (result) =>
callback()
if result.error?
updateStatus = 'failure'
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: '{err}.'
messageattrs: {
err: utils.get_error_message(result.error)
}
}])
else
updateStatus = 'success'
updateResult = result.result[0]
renderAlerts([{
contextcolor: 'success'
title: 'Success!'
message: 'Verification number {vers} created, marking {nacc} invoices as accounted.'
messageattrs: {
vers: [ver.number for ver in updateResult['verifications']]
nacc: updateResult['accounted'].length,
}
}])
renderApp()
)
generatePlusgiroFile = (siToiList, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.generatePlusgiroFile',
[[orgid], siToiList], (result) =>
if result.error?
resultStatus = 'failure'
resultData = result.error.args
else
resultStatus = 'success'
resultData = result.result
callback(resultStatus, resultData)
)
generateLBin = (siToiList, callback) =>
# Developer function, disable for production.
# Writes BGC file to /tmp/ on developer machine.
commit.callBlmMethod(
jsLink,
'accounting.writeBankgiroTransferOrder',
[[orgid], siToiList], (result) =>
if result.error?
resultStatus = 'failure'
resultData = {}
else
resultStatus = 'success'
resultData = result.result
callback(resultStatus, resultData)
)
saveSettings = (settings, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.updateSupplierInvoiceProvider',
[[orgid], [settings]], (result) =>
if result.error?
saveProviderStatus = 'failure'
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: 'Unable to save settings.'
}])
else
saveProviderStatus = 'success'
saveProviderResult = result.result
renderAlerts([{
contextcolor: 'success'
title: 'Success!'
key: 'savesuccess'
message: 'Settings saved.'
}])
callback()
renderApp()
)
uploadInvoiceImage = (sitoid, file, filedata) =>
images = []
image = {
name: file.name,
type: file.type,
data: btoa(filedata),
}
images.push(image)
commit.callBlmMethod(
jsLink,
'accounting.uploadInvoiceImage',
[[orgid], [sitoid], images], (result) =>
if result.error?
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: 'Unable to upload image.'
}])
)
removeInvoiceImage = (imagetoid) =>
commit.callBlmMethod(
jsLink,
'accounting.removeInvoiceImage',
[[imagetoid]], (result) =>
if result.error?
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: 'Unable to remove image.'
}])
)
renderApp = () ->
ReactDOM.render(
<div className='row'>
<div className='col'>
<Main
org={orgid}
fetchPredictions={fetchPredictions}
createSupplierInvoice={createSupplierInvoice}
updateSupplierInvoice={updateSupplierInvoice}
deleteSupplierInvoice={deleteSupplierInvoice}
createTransferVerification={createTransferVerification}
setSIState={setSIState}
enableSIAutomation={enableSIAutomation}
disableSIAutomation={disableSIAutomation}
generatePlusgiroFile={generatePlusgiroFile}
generateLBin={generateLBin}
uploadInvoiceImage={uploadInvoiceImage}
removeInvoiceImage={removeInvoiceImage}
setQueryDates={setQueryDates}
supplierInvoiceList={supplierInvoiceQuery.result}
supplierInvoiceTData={supplierInvoiceQuery.toiData}
supplierInvoiceQuery={supplierInvoiceQuery}
verificationsWatcher={verificationsWatcher}
transactionsWatcher={transactionsWatcher}
accountsQuery={accountsQuery}
seriesQuery={seriesQuery}
providerQuery={providerQuery}
imageQuery={imageQuery}
recipients={recipients}
renderAlerts={renderAlerts}
/>
</div>
</div>,
document.getElementById('maintarget')
)
renderAlerts = (alerts, dismiss) ->
ReactDOM.render(
<div className='row'>
<div className='col'>
<Alerts
alerts={alerts}
dismiss={dismiss}
/>
</div>
</div>,
document.getElementById('alertstarget')
)
renderSettings = () ->
ReactDOM.render(
<div className='row'>
<div className='col'>
<Settings
providerQuery={providerQuery}
accountsQuery={accountsQuery}
seriesQuery={seriesQuery}
saveSettings={saveSettings}
/>
</div>
</div>,
document.getElementById('settingstarget')
)
renderAuthorization = (signRef) ->
unmountAuthorizationDialog = ->
ReactDOM.render(
<div></div>,
document.getElementById('authorizetarget')
)
ReactDOM.render(
<div className='row'>
<div className='col'>
<Authorize.AuthorizationWidget
signRef=signRef
jsLink=jsLink
unmount=unmountAuthorizationDialog
/>
</div>
</div>,
document.getElementById('authorizetarget')
)
$('#authorizationModal').modal('show')
signals.connect(supplierInvoiceQuery, 'update', () ->
renderApp()
imageQuery.push({supplierInvoice: @result})
imageQuery.start()
proposeRecipients()
)
signals.connect(accountingYearQuery, 'update', () ->
org = @result[0]
year = @toiData[org]['current_accounting'][0]
accountsQuery.push({'accounting': year})
accountsQuery.start()
seriesQuery.push({'accounting': year})
seriesQuery.start()
)
signals.connect(accountsQuery, 'update', () ->
renderSettings()
renderApp()
)
signals.connect(seriesQuery, 'update', ->
renderSettings()
renderApp()
)
signals.connect(providerQuery, 'update', ->
renderSettings()
renderApp()
renderAlerts([])
if (providerQuery.result? and providerQuery.result.length < 1)
renderAlerts([{
key: 'missingsettings'
contextcolor: 'info'
dismissable: false
title: 'Welcome!'
message: 'You have not yet configured the Accounts payable module. To do so, click View -> Settings.'
}])
if (providerQuery.result? and providerQuery.result.length > 0)
# Dismiss alert
renderAlerts([], [{
key: 'missingsettings'
}])
)
signals.connect(imageQuery, 'update', ->
renderApp()
)
jsLink.ready.then(->
accountingYearQuery.start()
providerQuery.start()
supplierInvoiceQuery.start()
)
renderApp()
)
| 71586 | /*
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.
*/
define([
'react', 'react-dom',
'gettext', 'signals', 'utils',
'jslink/JsLink', 'jslink/ToiSetWatcher', 'jslink/query', 'jslink/commit',
'widgets/amount', 'widgets/date',
'widgets/accountspayable/main',
'widgets/accountspayable/authorize',
'widgets/accountspayable/fileuploader',
'widgets/accountspayable/settings',
'widgets/accountspayable/alerts',
'classnames',
], ->
[React, ReactDOM,
gettext, signals, utils,
JsLink, ToiSetWatcher, query, commit,
Amount, DatePicker,
Main,
Authorize,
Fileuploader,
Settings,
Alerts,
classnames,
] = arguments
gettext.install('client')
_ = gettext.gettext
orgid = document.location.pathname.split('/')[-1..][0]
# Data link setup
jsLink = new JsLink('/jslink')
# Queries
SIattrList = [
'org',
'accounted',
'invoiceState',
'automated',
'recipient',
'invoiceType',
'amount',
'transferMethod',
'pgnum',
'bgnum',
'bankaccount',
'bankclearing',
#'transferAddress',
'invoiceIdentifierType',
'ocr',
'invoiceNumber',
'message',
#'invoiceIdentifier',
'registrationVerification',
'transferVerification',
'invoiceDate',
'dateInvoiceRegistered',
'transferDate',
'dueDate',
'rejected_log',
'images']
startdate=''
stopdate='a'
setQueryDates = (start, stop) =>
console.log('querydates', start, stop)
startdate = start
stopdate = stop or 'a'
supplierInvoiceQuery.link.deactivate()
supplierInvoiceQuery.result = []
supplierInvoiceQuery.toiData = {}
supplierInvoiceQuery.condGroups = []
if start.length > 0 or stop.length > 0
supplierInvoiceQuery.push({'org': orgid, 'transferDate': new query.Operator.Between(startdate, stopdate)})
else
supplierInvoiceQuery.push({'org': orgid})
supplierInvoiceQuery.start()
supplierInvoiceQuery = new query.SortedQuery(
jsLink, 'accounting.SupplierInvoice', {'org': orgid}
)
supplierInvoiceQuery.attrList = SIattrList
supplierInvoiceQuery.sorting = 'transferDate'
accountingYearQuery = new query.SortedQuery(
jsLink, 'accounting.Org', {'id': orgid}
)
accountingYearQuery.attrList = ['current_accounting']
accountsQuery = new query.SortedQuery(
jsLink, 'accounting.Account'
)
accountsQuery.attrList = ['name', 'number']
accountsQuery.sorting = 'number'
seriesQuery = new query.SortedQuery(
jsLink, 'accounting.VerificationSeries'
)
seriesQuery.attrList = ['name', 'description']
providerQuery = new query.SortedQuery(
jsLink, 'accounting.SupplierInvoiceProvider', {'org': orgid}
)
providerQuery.attrList = ['series', 'account', 'bank_account', 'transferVerification_text', 'plusgiro_sending_bank_account']
imageQuery = new query.SortedQuery(
jsLink, 'accounting.InvoiceImage'
)
imageQuery.attrList = ['filename']
verificationsWatcher = new ToiSetWatcher(
jsLink, 'accounting.Verification', ['transactions', 'version', 'series', 'number']
)
transactionsWatcher = new ToiSetWatcher(
jsLink, 'accounting.Transactions', ['account', 'amount', 'text', 'version']
)
recipients = undefined
# Div functions
#_setQueryArgs = (newargs) =>
# newargs['org'] = orgid
# si_query_args = newargs
# supplierInvoiceQuery.start()
# console.log(si_query_args, newargs)
#_delQueryArgs = (delargs) =>
# console.log(si_query_args)
# for arg in delargs
# if arg != 'org'
# delete si_query_args[arg]
# supplierInvoiceQuery.start()
# BLM functions
createSupplierInvoice = (invoice, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.saveSupplierInvoice',
[[orgid],[invoice]], (result) =>
if result.error?
console.log(result.error)
createStatus = 'failure'
alert = {
key: '<KEY>'
contextcolor: 'danger'
title: 'Failure!'
message: 'Invoice record could not be created. {err}.'
messageattrs: {
err: utils.get_error_message(result.error)
}
}
renderAlerts([alert])
else
createStatus = 'success'
createResult = result.result
renderAlerts([], [{key: 'savefail'}])
callback(createStatus)
renderApp()
)
updateSupplierInvoice = (toid, invoice, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.saveSupplierInvoice',
[[orgid], [invoice], [toid]], (result) =>
if result.error?
console.log(result.error)
updateStatus = 'failure'
alert = {
key: '<KEY>'
contextcolor: 'danger'
title: 'Failure!'
message: 'Failed to save invoice record. {err}.'
messageattrs:
err: utils.get_error_message(result.error)
}
renderAlerts([alert])
else
updateStatus = 'success'
updateResult = result.result
renderAlerts([], [{key: 'savefail'}])
callback(updateStatus)
renderApp()
)
deleteSupplierInvoice = (siToiList) =>
commit.callBlmMethod(
jsLink,
'accounting.deleteSupplierInvoice',
[[orgid], siToiList], (result) =>
if result.error?
deleteStatus = 'failure'
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: 'Delete command failed. {err}'
messageattrs: {err: result.error.args}
}])
else
deleteStatus = 'success'
deleteResult = result.result
if deleteResult.deleted.length > 0
renderAlerts([{
contextcolor: 'success'
title: 'Success!'
message: 'Deleted {del} drafts.'
messageattrs: {
del: deleteResult.deleted.length,
unt: deleteResult.untouched.length
}
}])
renderApp()
)
proposeRecipients = () =>
commit.callBlmMethod(
jsLink,
'accounting.proposeRecipients',
[[orgid]], (result) =>
if result.error?
status = 'failure'
else
status = 'success'
recipients = result.result
renderApp()
)
fetchPredictions = (recipient, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.predictSupplierInvoice',
[[orgid], [recipient]], (result) =>
if result.error?
# Handle failure
predictStatus = 'failure'
else
predictStatus = 'success'
prediction = result.result
callback(prediction)
renderApp()
)
setSIState = (siToiList, newstate, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.setSIState',
[[orgid], siToiList, [newstate]], (result) =>
callback()
if result.error?
updateStatus = 'failure'
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: '{err}.'
messageattrs: {err: utils.get_error_message(result.error)}
}])
else
updateStatus = 'success'
updateResult = result.result
if updateResult['updated'] > 0
renderAlerts([{
contextcolor: 'success'
title: 'Success!'
message: '{mod} of the {sel} selected set to {state}.'
messageattrs: {
mod: updateResult['updated'],
sel: updateResult['selected'],
state: newstate
}
}])
if updateResult['complaints'].length > 0
renderAlerts([{
contextcolor: 'warning'
title: 'Warning!'
message: 'Some states could not be changed due to the following reasons: {reasons}'
messageattrs: {reasons: updateResult['complaints']}
}])
)
enableSIAutomation = (siToiList, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.requestSIAutomation',
[[orgid], siToiList], (result) =>
if result.error?
if result.error.args?
message = result.error.args[0]
else
message = result.error
renderAlerts([
contextcolor: 'danger'
title: 'Failure.'
message: message
])
else
signRef = result.result[0]
renderAuthorization(signRef)
callback()
)
disableSIAutomation = (siToiList, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.disableSIAutomation',
[[orgid], siToiList], (result) =>
callback()
if result.error?
if utils.is_permission_error(result.error)
renderAlerts([
contextcolor: 'danger'
title: 'Permission denied.'
message: 'You do not have permission to schedule automatic payments.'
])
updateStatus = 'failure'
else
updateStatus = 'success'
updateResult = result.result
if updateResult['updated'] > 0
renderAlerts([{
contextcolor: 'success'
title: 'Success!'
message: 'Disabled automated payment for {mod} of the {sel} selected.'
messageattrs: {
mod: updateResult['updated'],
sel: updateResult['selected'],
}
}])
if updateResult['complaints'].length > 0
renderAlerts([{
contextcolor: 'warning'
title: 'Warning!'
message: 'Failed to disable automation for the following reasons: {reasons}'
messageattrs: {reasons: updateResult['complaints']}
}])
)
createTransferVerification = (siToiList, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.createTransferVerification',
[[orgid], siToiList], (result) =>
callback()
if result.error?
updateStatus = 'failure'
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: '{err}.'
messageattrs: {
err: utils.get_error_message(result.error)
}
}])
else
updateStatus = 'success'
updateResult = result.result[0]
renderAlerts([{
contextcolor: 'success'
title: 'Success!'
message: 'Verification number {vers} created, marking {nacc} invoices as accounted.'
messageattrs: {
vers: [ver.number for ver in updateResult['verifications']]
nacc: updateResult['accounted'].length,
}
}])
renderApp()
)
generatePlusgiroFile = (siToiList, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.generatePlusgiroFile',
[[orgid], siToiList], (result) =>
if result.error?
resultStatus = 'failure'
resultData = result.error.args
else
resultStatus = 'success'
resultData = result.result
callback(resultStatus, resultData)
)
generateLBin = (siToiList, callback) =>
# Developer function, disable for production.
# Writes BGC file to /tmp/ on developer machine.
commit.callBlmMethod(
jsLink,
'accounting.writeBankgiroTransferOrder',
[[orgid], siToiList], (result) =>
if result.error?
resultStatus = 'failure'
resultData = {}
else
resultStatus = 'success'
resultData = result.result
callback(resultStatus, resultData)
)
saveSettings = (settings, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.updateSupplierInvoiceProvider',
[[orgid], [settings]], (result) =>
if result.error?
saveProviderStatus = 'failure'
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: 'Unable to save settings.'
}])
else
saveProviderStatus = 'success'
saveProviderResult = result.result
renderAlerts([{
contextcolor: 'success'
title: 'Success!'
key: '<KEY>'
message: 'Settings saved.'
}])
callback()
renderApp()
)
uploadInvoiceImage = (sitoid, file, filedata) =>
images = []
image = {
name: file.name,
type: file.type,
data: btoa(filedata),
}
images.push(image)
commit.callBlmMethod(
jsLink,
'accounting.uploadInvoiceImage',
[[orgid], [sitoid], images], (result) =>
if result.error?
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: 'Unable to upload image.'
}])
)
removeInvoiceImage = (imagetoid) =>
commit.callBlmMethod(
jsLink,
'accounting.removeInvoiceImage',
[[imagetoid]], (result) =>
if result.error?
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: 'Unable to remove image.'
}])
)
renderApp = () ->
ReactDOM.render(
<div className='row'>
<div className='col'>
<Main
org={orgid}
fetchPredictions={fetchPredictions}
createSupplierInvoice={createSupplierInvoice}
updateSupplierInvoice={updateSupplierInvoice}
deleteSupplierInvoice={deleteSupplierInvoice}
createTransferVerification={createTransferVerification}
setSIState={setSIState}
enableSIAutomation={enableSIAutomation}
disableSIAutomation={disableSIAutomation}
generatePlusgiroFile={generatePlusgiroFile}
generateLBin={generateLBin}
uploadInvoiceImage={uploadInvoiceImage}
removeInvoiceImage={removeInvoiceImage}
setQueryDates={setQueryDates}
supplierInvoiceList={supplierInvoiceQuery.result}
supplierInvoiceTData={supplierInvoiceQuery.toiData}
supplierInvoiceQuery={supplierInvoiceQuery}
verificationsWatcher={verificationsWatcher}
transactionsWatcher={transactionsWatcher}
accountsQuery={accountsQuery}
seriesQuery={seriesQuery}
providerQuery={providerQuery}
imageQuery={imageQuery}
recipients={recipients}
renderAlerts={renderAlerts}
/>
</div>
</div>,
document.getElementById('maintarget')
)
renderAlerts = (alerts, dismiss) ->
ReactDOM.render(
<div className='row'>
<div className='col'>
<Alerts
alerts={alerts}
dismiss={dismiss}
/>
</div>
</div>,
document.getElementById('alertstarget')
)
renderSettings = () ->
ReactDOM.render(
<div className='row'>
<div className='col'>
<Settings
providerQuery={providerQuery}
accountsQuery={accountsQuery}
seriesQuery={seriesQuery}
saveSettings={saveSettings}
/>
</div>
</div>,
document.getElementById('settingstarget')
)
renderAuthorization = (signRef) ->
unmountAuthorizationDialog = ->
ReactDOM.render(
<div></div>,
document.getElementById('authorizetarget')
)
ReactDOM.render(
<div className='row'>
<div className='col'>
<Authorize.AuthorizationWidget
signRef=signRef
jsLink=jsLink
unmount=unmountAuthorizationDialog
/>
</div>
</div>,
document.getElementById('authorizetarget')
)
$('#authorizationModal').modal('show')
signals.connect(supplierInvoiceQuery, 'update', () ->
renderApp()
imageQuery.push({supplierInvoice: @result})
imageQuery.start()
proposeRecipients()
)
signals.connect(accountingYearQuery, 'update', () ->
org = @result[0]
year = @toiData[org]['current_accounting'][0]
accountsQuery.push({'accounting': year})
accountsQuery.start()
seriesQuery.push({'accounting': year})
seriesQuery.start()
)
signals.connect(accountsQuery, 'update', () ->
renderSettings()
renderApp()
)
signals.connect(seriesQuery, 'update', ->
renderSettings()
renderApp()
)
signals.connect(providerQuery, 'update', ->
renderSettings()
renderApp()
renderAlerts([])
if (providerQuery.result? and providerQuery.result.length < 1)
renderAlerts([{
key: 'missingsettings'
contextcolor: 'info'
dismissable: false
title: 'Welcome!'
message: 'You have not yet configured the Accounts payable module. To do so, click View -> Settings.'
}])
if (providerQuery.result? and providerQuery.result.length > 0)
# Dismiss alert
renderAlerts([], [{
key: 'missingsettings'
}])
)
signals.connect(imageQuery, 'update', ->
renderApp()
)
jsLink.ready.then(->
accountingYearQuery.start()
providerQuery.start()
supplierInvoiceQuery.start()
)
renderApp()
)
| 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.
*/
define([
'react', 'react-dom',
'gettext', 'signals', 'utils',
'jslink/JsLink', 'jslink/ToiSetWatcher', 'jslink/query', 'jslink/commit',
'widgets/amount', 'widgets/date',
'widgets/accountspayable/main',
'widgets/accountspayable/authorize',
'widgets/accountspayable/fileuploader',
'widgets/accountspayable/settings',
'widgets/accountspayable/alerts',
'classnames',
], ->
[React, ReactDOM,
gettext, signals, utils,
JsLink, ToiSetWatcher, query, commit,
Amount, DatePicker,
Main,
Authorize,
Fileuploader,
Settings,
Alerts,
classnames,
] = arguments
gettext.install('client')
_ = gettext.gettext
orgid = document.location.pathname.split('/')[-1..][0]
# Data link setup
jsLink = new JsLink('/jslink')
# Queries
SIattrList = [
'org',
'accounted',
'invoiceState',
'automated',
'recipient',
'invoiceType',
'amount',
'transferMethod',
'pgnum',
'bgnum',
'bankaccount',
'bankclearing',
#'transferAddress',
'invoiceIdentifierType',
'ocr',
'invoiceNumber',
'message',
#'invoiceIdentifier',
'registrationVerification',
'transferVerification',
'invoiceDate',
'dateInvoiceRegistered',
'transferDate',
'dueDate',
'rejected_log',
'images']
startdate=''
stopdate='a'
setQueryDates = (start, stop) =>
console.log('querydates', start, stop)
startdate = start
stopdate = stop or 'a'
supplierInvoiceQuery.link.deactivate()
supplierInvoiceQuery.result = []
supplierInvoiceQuery.toiData = {}
supplierInvoiceQuery.condGroups = []
if start.length > 0 or stop.length > 0
supplierInvoiceQuery.push({'org': orgid, 'transferDate': new query.Operator.Between(startdate, stopdate)})
else
supplierInvoiceQuery.push({'org': orgid})
supplierInvoiceQuery.start()
supplierInvoiceQuery = new query.SortedQuery(
jsLink, 'accounting.SupplierInvoice', {'org': orgid}
)
supplierInvoiceQuery.attrList = SIattrList
supplierInvoiceQuery.sorting = 'transferDate'
accountingYearQuery = new query.SortedQuery(
jsLink, 'accounting.Org', {'id': orgid}
)
accountingYearQuery.attrList = ['current_accounting']
accountsQuery = new query.SortedQuery(
jsLink, 'accounting.Account'
)
accountsQuery.attrList = ['name', 'number']
accountsQuery.sorting = 'number'
seriesQuery = new query.SortedQuery(
jsLink, 'accounting.VerificationSeries'
)
seriesQuery.attrList = ['name', 'description']
providerQuery = new query.SortedQuery(
jsLink, 'accounting.SupplierInvoiceProvider', {'org': orgid}
)
providerQuery.attrList = ['series', 'account', 'bank_account', 'transferVerification_text', 'plusgiro_sending_bank_account']
imageQuery = new query.SortedQuery(
jsLink, 'accounting.InvoiceImage'
)
imageQuery.attrList = ['filename']
verificationsWatcher = new ToiSetWatcher(
jsLink, 'accounting.Verification', ['transactions', 'version', 'series', 'number']
)
transactionsWatcher = new ToiSetWatcher(
jsLink, 'accounting.Transactions', ['account', 'amount', 'text', 'version']
)
recipients = undefined
# Div functions
#_setQueryArgs = (newargs) =>
# newargs['org'] = orgid
# si_query_args = newargs
# supplierInvoiceQuery.start()
# console.log(si_query_args, newargs)
#_delQueryArgs = (delargs) =>
# console.log(si_query_args)
# for arg in delargs
# if arg != 'org'
# delete si_query_args[arg]
# supplierInvoiceQuery.start()
# BLM functions
createSupplierInvoice = (invoice, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.saveSupplierInvoice',
[[orgid],[invoice]], (result) =>
if result.error?
console.log(result.error)
createStatus = 'failure'
alert = {
key: 'PI:KEY:<KEY>END_PI'
contextcolor: 'danger'
title: 'Failure!'
message: 'Invoice record could not be created. {err}.'
messageattrs: {
err: utils.get_error_message(result.error)
}
}
renderAlerts([alert])
else
createStatus = 'success'
createResult = result.result
renderAlerts([], [{key: 'savefail'}])
callback(createStatus)
renderApp()
)
updateSupplierInvoice = (toid, invoice, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.saveSupplierInvoice',
[[orgid], [invoice], [toid]], (result) =>
if result.error?
console.log(result.error)
updateStatus = 'failure'
alert = {
key: 'PI:KEY:<KEY>END_PI'
contextcolor: 'danger'
title: 'Failure!'
message: 'Failed to save invoice record. {err}.'
messageattrs:
err: utils.get_error_message(result.error)
}
renderAlerts([alert])
else
updateStatus = 'success'
updateResult = result.result
renderAlerts([], [{key: 'savefail'}])
callback(updateStatus)
renderApp()
)
deleteSupplierInvoice = (siToiList) =>
commit.callBlmMethod(
jsLink,
'accounting.deleteSupplierInvoice',
[[orgid], siToiList], (result) =>
if result.error?
deleteStatus = 'failure'
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: 'Delete command failed. {err}'
messageattrs: {err: result.error.args}
}])
else
deleteStatus = 'success'
deleteResult = result.result
if deleteResult.deleted.length > 0
renderAlerts([{
contextcolor: 'success'
title: 'Success!'
message: 'Deleted {del} drafts.'
messageattrs: {
del: deleteResult.deleted.length,
unt: deleteResult.untouched.length
}
}])
renderApp()
)
proposeRecipients = () =>
commit.callBlmMethod(
jsLink,
'accounting.proposeRecipients',
[[orgid]], (result) =>
if result.error?
status = 'failure'
else
status = 'success'
recipients = result.result
renderApp()
)
fetchPredictions = (recipient, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.predictSupplierInvoice',
[[orgid], [recipient]], (result) =>
if result.error?
# Handle failure
predictStatus = 'failure'
else
predictStatus = 'success'
prediction = result.result
callback(prediction)
renderApp()
)
setSIState = (siToiList, newstate, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.setSIState',
[[orgid], siToiList, [newstate]], (result) =>
callback()
if result.error?
updateStatus = 'failure'
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: '{err}.'
messageattrs: {err: utils.get_error_message(result.error)}
}])
else
updateStatus = 'success'
updateResult = result.result
if updateResult['updated'] > 0
renderAlerts([{
contextcolor: 'success'
title: 'Success!'
message: '{mod} of the {sel} selected set to {state}.'
messageattrs: {
mod: updateResult['updated'],
sel: updateResult['selected'],
state: newstate
}
}])
if updateResult['complaints'].length > 0
renderAlerts([{
contextcolor: 'warning'
title: 'Warning!'
message: 'Some states could not be changed due to the following reasons: {reasons}'
messageattrs: {reasons: updateResult['complaints']}
}])
)
enableSIAutomation = (siToiList, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.requestSIAutomation',
[[orgid], siToiList], (result) =>
if result.error?
if result.error.args?
message = result.error.args[0]
else
message = result.error
renderAlerts([
contextcolor: 'danger'
title: 'Failure.'
message: message
])
else
signRef = result.result[0]
renderAuthorization(signRef)
callback()
)
disableSIAutomation = (siToiList, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.disableSIAutomation',
[[orgid], siToiList], (result) =>
callback()
if result.error?
if utils.is_permission_error(result.error)
renderAlerts([
contextcolor: 'danger'
title: 'Permission denied.'
message: 'You do not have permission to schedule automatic payments.'
])
updateStatus = 'failure'
else
updateStatus = 'success'
updateResult = result.result
if updateResult['updated'] > 0
renderAlerts([{
contextcolor: 'success'
title: 'Success!'
message: 'Disabled automated payment for {mod} of the {sel} selected.'
messageattrs: {
mod: updateResult['updated'],
sel: updateResult['selected'],
}
}])
if updateResult['complaints'].length > 0
renderAlerts([{
contextcolor: 'warning'
title: 'Warning!'
message: 'Failed to disable automation for the following reasons: {reasons}'
messageattrs: {reasons: updateResult['complaints']}
}])
)
createTransferVerification = (siToiList, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.createTransferVerification',
[[orgid], siToiList], (result) =>
callback()
if result.error?
updateStatus = 'failure'
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: '{err}.'
messageattrs: {
err: utils.get_error_message(result.error)
}
}])
else
updateStatus = 'success'
updateResult = result.result[0]
renderAlerts([{
contextcolor: 'success'
title: 'Success!'
message: 'Verification number {vers} created, marking {nacc} invoices as accounted.'
messageattrs: {
vers: [ver.number for ver in updateResult['verifications']]
nacc: updateResult['accounted'].length,
}
}])
renderApp()
)
generatePlusgiroFile = (siToiList, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.generatePlusgiroFile',
[[orgid], siToiList], (result) =>
if result.error?
resultStatus = 'failure'
resultData = result.error.args
else
resultStatus = 'success'
resultData = result.result
callback(resultStatus, resultData)
)
generateLBin = (siToiList, callback) =>
# Developer function, disable for production.
# Writes BGC file to /tmp/ on developer machine.
commit.callBlmMethod(
jsLink,
'accounting.writeBankgiroTransferOrder',
[[orgid], siToiList], (result) =>
if result.error?
resultStatus = 'failure'
resultData = {}
else
resultStatus = 'success'
resultData = result.result
callback(resultStatus, resultData)
)
saveSettings = (settings, callback) =>
commit.callBlmMethod(
jsLink,
'accounting.updateSupplierInvoiceProvider',
[[orgid], [settings]], (result) =>
if result.error?
saveProviderStatus = 'failure'
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: 'Unable to save settings.'
}])
else
saveProviderStatus = 'success'
saveProviderResult = result.result
renderAlerts([{
contextcolor: 'success'
title: 'Success!'
key: 'PI:KEY:<KEY>END_PI'
message: 'Settings saved.'
}])
callback()
renderApp()
)
uploadInvoiceImage = (sitoid, file, filedata) =>
images = []
image = {
name: file.name,
type: file.type,
data: btoa(filedata),
}
images.push(image)
commit.callBlmMethod(
jsLink,
'accounting.uploadInvoiceImage',
[[orgid], [sitoid], images], (result) =>
if result.error?
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: 'Unable to upload image.'
}])
)
removeInvoiceImage = (imagetoid) =>
commit.callBlmMethod(
jsLink,
'accounting.removeInvoiceImage',
[[imagetoid]], (result) =>
if result.error?
renderAlerts([{
contextcolor: 'danger'
title: 'Failure!'
message: 'Unable to remove image.'
}])
)
renderApp = () ->
ReactDOM.render(
<div className='row'>
<div className='col'>
<Main
org={orgid}
fetchPredictions={fetchPredictions}
createSupplierInvoice={createSupplierInvoice}
updateSupplierInvoice={updateSupplierInvoice}
deleteSupplierInvoice={deleteSupplierInvoice}
createTransferVerification={createTransferVerification}
setSIState={setSIState}
enableSIAutomation={enableSIAutomation}
disableSIAutomation={disableSIAutomation}
generatePlusgiroFile={generatePlusgiroFile}
generateLBin={generateLBin}
uploadInvoiceImage={uploadInvoiceImage}
removeInvoiceImage={removeInvoiceImage}
setQueryDates={setQueryDates}
supplierInvoiceList={supplierInvoiceQuery.result}
supplierInvoiceTData={supplierInvoiceQuery.toiData}
supplierInvoiceQuery={supplierInvoiceQuery}
verificationsWatcher={verificationsWatcher}
transactionsWatcher={transactionsWatcher}
accountsQuery={accountsQuery}
seriesQuery={seriesQuery}
providerQuery={providerQuery}
imageQuery={imageQuery}
recipients={recipients}
renderAlerts={renderAlerts}
/>
</div>
</div>,
document.getElementById('maintarget')
)
renderAlerts = (alerts, dismiss) ->
ReactDOM.render(
<div className='row'>
<div className='col'>
<Alerts
alerts={alerts}
dismiss={dismiss}
/>
</div>
</div>,
document.getElementById('alertstarget')
)
renderSettings = () ->
ReactDOM.render(
<div className='row'>
<div className='col'>
<Settings
providerQuery={providerQuery}
accountsQuery={accountsQuery}
seriesQuery={seriesQuery}
saveSettings={saveSettings}
/>
</div>
</div>,
document.getElementById('settingstarget')
)
renderAuthorization = (signRef) ->
unmountAuthorizationDialog = ->
ReactDOM.render(
<div></div>,
document.getElementById('authorizetarget')
)
ReactDOM.render(
<div className='row'>
<div className='col'>
<Authorize.AuthorizationWidget
signRef=signRef
jsLink=jsLink
unmount=unmountAuthorizationDialog
/>
</div>
</div>,
document.getElementById('authorizetarget')
)
$('#authorizationModal').modal('show')
signals.connect(supplierInvoiceQuery, 'update', () ->
renderApp()
imageQuery.push({supplierInvoice: @result})
imageQuery.start()
proposeRecipients()
)
signals.connect(accountingYearQuery, 'update', () ->
org = @result[0]
year = @toiData[org]['current_accounting'][0]
accountsQuery.push({'accounting': year})
accountsQuery.start()
seriesQuery.push({'accounting': year})
seriesQuery.start()
)
signals.connect(accountsQuery, 'update', () ->
renderSettings()
renderApp()
)
signals.connect(seriesQuery, 'update', ->
renderSettings()
renderApp()
)
signals.connect(providerQuery, 'update', ->
renderSettings()
renderApp()
renderAlerts([])
if (providerQuery.result? and providerQuery.result.length < 1)
renderAlerts([{
key: 'missingsettings'
contextcolor: 'info'
dismissable: false
title: 'Welcome!'
message: 'You have not yet configured the Accounts payable module. To do so, click View -> Settings.'
}])
if (providerQuery.result? and providerQuery.result.length > 0)
# Dismiss alert
renderAlerts([], [{
key: 'missingsettings'
}])
)
signals.connect(imageQuery, 'update', ->
renderApp()
)
jsLink.ready.then(->
accountingYearQuery.start()
providerQuery.start()
supplierInvoiceQuery.start()
)
renderApp()
)
|
[
{
"context": "rn res.send error: info unless user\n\n token = helpers.createId()\n ttl = (60 * 60 * 24) * 2 # 48 hours\n\n ",
"end": 813,
"score": 0.8262256979942322,
"start": 797,
"tag": "KEY",
"value": "helpers.createId"
}
] | routes/auth.coffee | mattstone/StarterApp-Server | 0 | passport = require('passport');
module.exports = (app) ->
exp = app.exp
helpers = app.helpers
exp.post '/login', (req, res) ->
if !req.body.user? then return res.json { error: "invalid email and password combination", user: null }
if !req.body.user["email"]? then return res.json { error: "invalid email and password combination", user: null }
if !req.body.user["password"]? then return res.json { error: "invalid email and password combination", user: null }
if req.body.user["email"] is '' or req.body.user["password"] is ''
return res.json { error: "invalid email and password combination", user: null }
auth = (err, user, info) ->
return res.send error: err if err
return res.send error: info unless user
token = helpers.createId()
ttl = (60 * 60 * 24) * 2 # 48 hours
app.r.setAccessToken token, user, ttl, (err, response) ->
if err? then return res.send { error: err}
req.logIn user, (err) ->
if err? then return res.send { error: String err }
return res.send { user: user.toJSON(), token: token }
passport.authenticate('local', auth)(req, res)
exp.get '/logout', (req, res) ->
req.logout()
res.send 'Logged Out'
| 107030 | passport = require('passport');
module.exports = (app) ->
exp = app.exp
helpers = app.helpers
exp.post '/login', (req, res) ->
if !req.body.user? then return res.json { error: "invalid email and password combination", user: null }
if !req.body.user["email"]? then return res.json { error: "invalid email and password combination", user: null }
if !req.body.user["password"]? then return res.json { error: "invalid email and password combination", user: null }
if req.body.user["email"] is '' or req.body.user["password"] is ''
return res.json { error: "invalid email and password combination", user: null }
auth = (err, user, info) ->
return res.send error: err if err
return res.send error: info unless user
token = <KEY>()
ttl = (60 * 60 * 24) * 2 # 48 hours
app.r.setAccessToken token, user, ttl, (err, response) ->
if err? then return res.send { error: err}
req.logIn user, (err) ->
if err? then return res.send { error: String err }
return res.send { user: user.toJSON(), token: token }
passport.authenticate('local', auth)(req, res)
exp.get '/logout', (req, res) ->
req.logout()
res.send 'Logged Out'
| true | passport = require('passport');
module.exports = (app) ->
exp = app.exp
helpers = app.helpers
exp.post '/login', (req, res) ->
if !req.body.user? then return res.json { error: "invalid email and password combination", user: null }
if !req.body.user["email"]? then return res.json { error: "invalid email and password combination", user: null }
if !req.body.user["password"]? then return res.json { error: "invalid email and password combination", user: null }
if req.body.user["email"] is '' or req.body.user["password"] is ''
return res.json { error: "invalid email and password combination", user: null }
auth = (err, user, info) ->
return res.send error: err if err
return res.send error: info unless user
token = PI:KEY:<KEY>END_PI()
ttl = (60 * 60 * 24) * 2 # 48 hours
app.r.setAccessToken token, user, ttl, (err, response) ->
if err? then return res.send { error: err}
req.logIn user, (err) ->
if err? then return res.send { error: String err }
return res.send { user: user.toJSON(), token: token }
passport.authenticate('local', auth)(req, res)
exp.get '/logout', (req, res) ->
req.logout()
res.send 'Logged Out'
|
[
{
"context": "## Version - 0.1.0\n######################\n\nDNA = '463d3d0ee1bb024ba9ecb52441e7ae39edb592ccb3bd72490d80703e84d396c06628ba649ec05a140b2605ce865b41d02a266ca61dfb1ac87e6a32d6de56349505e6c039c62fd5d65d6e0e39f2f1650c2c3dd95bd4463f3d0ee1664abb4bacb8ec24e7ae39d8edabb592acbdb10d806b3e9b96ba2829ba0d27c05a140b1f26cee305ce6f865b41ee67266c46593d0ee1a646db024ba9ec442441e7ae1c39edb592ccb3bd72b10d803e84d3966628ba649ec0935a140b26ce61ce865b41672a266ca61df2fb1ac86a3256349505e6c039c62fd50ad65d6e0e39f2f1c20c5d2c49085bd4463f3de166|fbafd1c0253103dad61c3fe45b43a633767fab866d8875ae7",
"end": 578,
"score": 0.7864723205566406,
"start": 114,
"tag": "KEY",
"value": "463d3d0ee1bb024ba9ecb52441e7ae39edb592ccb3bd72490d80703e84d396c06628ba649ec05a140b2605ce865b41d02a266ca61dfb1ac87e6a32d6de56349505e6c039c62fd5d65d6e0e39f2f1650c2c3dd95bd4463f3d0ee1664abb4bacb8ec24e7ae39d8edabb592acbdb10d806b3e9b96ba2829ba0d27c05a140b1f26cee305ce6f865b41ee67266c46593d0ee1a646db024ba9ec442441e7ae1c39edb592ccb3bd72b10d803e84d3966628ba649ec0935a140b26ce61ce865b41672a266ca61df2fb1ac86a3256349505e6c039c62fd50ad65d6e0e39f2f1c20c5d2c49085bd4463f3de166"
},
{
"context": "62fd50ad65d6e0e39f2f1c20c5d2c49085bd4463f3de166|fbafd1c0253103dad61c3fe45b43a633767fab866d8875ae7c0a992a2d9bf8a0b42b69912ed29a8c87ad8f361d08770e3f6b12835209eaa93a25fc5901b5a73638b6371fd4a5f3674119e029fcd597d2681f7ecde3cc7687f2'\npargs = process.argv.slice(2)\nargs = null\n\nproce",
"end": 757,
"score": 0.8131080269813538,
"start": 581,
"tag": "KEY",
"value": "afd1c0253103dad61c3fe45b43a633767fab866d8875ae7c0a992a2d9bf8a0b42b69912ed29a8c87ad8f361d08770e3f6b12835209eaa93a25fc5901b5a73638b6371fd4a5f3674119e029fcd597d2681f7ecde3cc7687f2"
}
] | examples/datasets/house-votes.coffee | wmiller848/GoGP | 2 | #!/usr/local/bin/coffee
######################
## GoGP Program
## Version - 0.1.0
######################
DNA = '463d3d0ee1bb024ba9ecb52441e7ae39edb592ccb3bd72490d80703e84d396c06628ba649ec05a140b2605ce865b41d02a266ca61dfb1ac87e6a32d6de56349505e6c039c62fd5d65d6e0e39f2f1650c2c3dd95bd4463f3d0ee1664abb4bacb8ec24e7ae39d8edabb592acbdb10d806b3e9b96ba2829ba0d27c05a140b1f26cee305ce6f865b41ee67266c46593d0ee1a646db024ba9ec442441e7ae1c39edb592ccb3bd72b10d803e84d3966628ba649ec0935a140b26ce61ce865b41672a266ca61df2fb1ac86a3256349505e6c039c62fd50ad65d6e0e39f2f1c20c5d2c49085bd4463f3de166|fbafd1c0253103dad61c3fe45b43a633767fab866d8875ae7c0a992a2d9bf8a0b42b69912ed29a8c87ad8f361d08770e3f6b12835209eaa93a25fc5901b5a73638b6371fd4a5f3674119e029fcd597d2681f7ecde3cc7687f2'
pargs = process.argv.slice(2)
args = null
process.on('beforeExit', ->
#console.log('Dieing...')
)
process.on('exit', ->
#console.log('Dead...')
)
inputMap =
'noInputStrings': null
assertMap =
'republican': 8
'democrat': 16
##
##
match = (output) ->
diff = Number.MAX_VALUE
ok = ""
ov = 0
for k, v of assertMap
d = Math.abs(v - output)
if d < diff
diff = d
ok = k
ov = v
# "#{ok} (#{ov}) from #{output}"
"#{ok}"
##
##
run = ->
$zz = Number(args[0]);$zy = Number(args[1]);$zx = Number(args[2]);$zw = Number(args[3]);$zv = Number(args[4]);$zu = Number(args[5]);$zt = Number(args[6]);$zs = Number(args[7]);$zr = Number(args[8]);$zq = Number(args[9]);$za = Number(args[10]);$zb = Number(args[11]);$zc = Number(args[12]);$zd = Number(args[13]);$ze = Number(args[14]);$zf = Number(args[15]);
$zz = inputMap[args[0]] if isNaN($zz);$zy = inputMap[args[1]] if isNaN($zy);$zx = inputMap[args[2]] if isNaN($zx);$zw = inputMap[args[3]] if isNaN($zw);$zv = inputMap[args[4]] if isNaN($zv);$zu = inputMap[args[5]] if isNaN($zu);$zt = inputMap[args[6]] if isNaN($zt);$zs = inputMap[args[7]] if isNaN($zs);$zr = inputMap[args[8]] if isNaN($zr);$zq = inputMap[args[9]] if isNaN($zq);$za = inputMap[args[10]] if isNaN($za);$zb = inputMap[args[11]] if isNaN($zb);$zc = inputMap[args[12]] if isNaN($zc);$zd = inputMap[args[13]] if isNaN($zd);$ze = inputMap[args[14]] if isNaN($ze);$zf = inputMap[args[15]] if isNaN($zf);
output = 7+($zq+(8&$zv))
if isNaN(output)
output = ''
ot = match(output)
process.stdout.write(new Buffer.from(ot.toString() + '\n'))
if pargs.length == 0
process.stdin.setEncoding('utf8')
process.stdin.on('readable', ->
chunks = process.stdin.read()
if chunks
chunks = chunks.toString().trim().split('\n')
for chunk in chunks
args = chunk.split(',')
run()
)
process.stdin.on('end', ->
#process.stdout.write(new Buffer.from('\r\n'))
)
else
args = pargs.join(' ').trim().split(' ')
run()
| 132777 | #!/usr/local/bin/coffee
######################
## GoGP Program
## Version - 0.1.0
######################
DNA = '<KEY>|fb<KEY>'
pargs = process.argv.slice(2)
args = null
process.on('beforeExit', ->
#console.log('Dieing...')
)
process.on('exit', ->
#console.log('Dead...')
)
inputMap =
'noInputStrings': null
assertMap =
'republican': 8
'democrat': 16
##
##
match = (output) ->
diff = Number.MAX_VALUE
ok = ""
ov = 0
for k, v of assertMap
d = Math.abs(v - output)
if d < diff
diff = d
ok = k
ov = v
# "#{ok} (#{ov}) from #{output}"
"#{ok}"
##
##
run = ->
$zz = Number(args[0]);$zy = Number(args[1]);$zx = Number(args[2]);$zw = Number(args[3]);$zv = Number(args[4]);$zu = Number(args[5]);$zt = Number(args[6]);$zs = Number(args[7]);$zr = Number(args[8]);$zq = Number(args[9]);$za = Number(args[10]);$zb = Number(args[11]);$zc = Number(args[12]);$zd = Number(args[13]);$ze = Number(args[14]);$zf = Number(args[15]);
$zz = inputMap[args[0]] if isNaN($zz);$zy = inputMap[args[1]] if isNaN($zy);$zx = inputMap[args[2]] if isNaN($zx);$zw = inputMap[args[3]] if isNaN($zw);$zv = inputMap[args[4]] if isNaN($zv);$zu = inputMap[args[5]] if isNaN($zu);$zt = inputMap[args[6]] if isNaN($zt);$zs = inputMap[args[7]] if isNaN($zs);$zr = inputMap[args[8]] if isNaN($zr);$zq = inputMap[args[9]] if isNaN($zq);$za = inputMap[args[10]] if isNaN($za);$zb = inputMap[args[11]] if isNaN($zb);$zc = inputMap[args[12]] if isNaN($zc);$zd = inputMap[args[13]] if isNaN($zd);$ze = inputMap[args[14]] if isNaN($ze);$zf = inputMap[args[15]] if isNaN($zf);
output = 7+($zq+(8&$zv))
if isNaN(output)
output = ''
ot = match(output)
process.stdout.write(new Buffer.from(ot.toString() + '\n'))
if pargs.length == 0
process.stdin.setEncoding('utf8')
process.stdin.on('readable', ->
chunks = process.stdin.read()
if chunks
chunks = chunks.toString().trim().split('\n')
for chunk in chunks
args = chunk.split(',')
run()
)
process.stdin.on('end', ->
#process.stdout.write(new Buffer.from('\r\n'))
)
else
args = pargs.join(' ').trim().split(' ')
run()
| true | #!/usr/local/bin/coffee
######################
## GoGP Program
## Version - 0.1.0
######################
DNA = 'PI:KEY:<KEY>END_PI|fbPI:KEY:<KEY>END_PI'
pargs = process.argv.slice(2)
args = null
process.on('beforeExit', ->
#console.log('Dieing...')
)
process.on('exit', ->
#console.log('Dead...')
)
inputMap =
'noInputStrings': null
assertMap =
'republican': 8
'democrat': 16
##
##
match = (output) ->
diff = Number.MAX_VALUE
ok = ""
ov = 0
for k, v of assertMap
d = Math.abs(v - output)
if d < diff
diff = d
ok = k
ov = v
# "#{ok} (#{ov}) from #{output}"
"#{ok}"
##
##
run = ->
$zz = Number(args[0]);$zy = Number(args[1]);$zx = Number(args[2]);$zw = Number(args[3]);$zv = Number(args[4]);$zu = Number(args[5]);$zt = Number(args[6]);$zs = Number(args[7]);$zr = Number(args[8]);$zq = Number(args[9]);$za = Number(args[10]);$zb = Number(args[11]);$zc = Number(args[12]);$zd = Number(args[13]);$ze = Number(args[14]);$zf = Number(args[15]);
$zz = inputMap[args[0]] if isNaN($zz);$zy = inputMap[args[1]] if isNaN($zy);$zx = inputMap[args[2]] if isNaN($zx);$zw = inputMap[args[3]] if isNaN($zw);$zv = inputMap[args[4]] if isNaN($zv);$zu = inputMap[args[5]] if isNaN($zu);$zt = inputMap[args[6]] if isNaN($zt);$zs = inputMap[args[7]] if isNaN($zs);$zr = inputMap[args[8]] if isNaN($zr);$zq = inputMap[args[9]] if isNaN($zq);$za = inputMap[args[10]] if isNaN($za);$zb = inputMap[args[11]] if isNaN($zb);$zc = inputMap[args[12]] if isNaN($zc);$zd = inputMap[args[13]] if isNaN($zd);$ze = inputMap[args[14]] if isNaN($ze);$zf = inputMap[args[15]] if isNaN($zf);
output = 7+($zq+(8&$zv))
if isNaN(output)
output = ''
ot = match(output)
process.stdout.write(new Buffer.from(ot.toString() + '\n'))
if pargs.length == 0
process.stdin.setEncoding('utf8')
process.stdin.on('readable', ->
chunks = process.stdin.read()
if chunks
chunks = chunks.toString().trim().split('\n')
for chunk in chunks
args = chunk.split(',')
run()
)
process.stdin.on('end', ->
#process.stdout.write(new Buffer.from('\r\n'))
)
else
args = pargs.join(' ').trim().split(' ')
run()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.