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": "me format, format should be in the form of email : user@sample.com'\n\n LANG.errors.confirm_email[VALID.ERR", "end": 1858, "score": 0.9999032020568848, "start": 1843, "tag": "EMAIL", "value": "user@sample.com" }, { "context": "me format, format should be in t...
modules/admin_info_form/admin_info_form.coffee
signonsridhar/sridhar_hbs
0
define([ 'bases/control', '_', 'libs/masked_input_plugin_jquery', 'css!modules/admin_info_form/admin_info_form' ], (BaseControl, _)-> BaseControl.extend({ LANG: (controller)-> LANG = { errors:{ first_name:{} last_name:{} phone:{} email:{} confirm_email:{} } } LANG.errors.first_name[VALID.ERROR.SIZE] = 'first name must be 2 to 40 characters' LANG.errors.first_name[VALID.ERROR.REQUIRED] = 'first name is required' LANG.errors.first_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" LANG.errors.last_name[VALID.ERROR.REQUIRED] = 'last name is required' LANG.errors.last_name[VALID.ERROR.SIZE] = 'last name must be 2 to 40 characters' LANG.errors.last_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" ###LANG.errors.phone[VALID.ERROR.FORMAT] = 'must be 10 digits'### LANG.errors.phone[VALID.ERROR.REQUIRED] = 'phone number is required' LANG.errors.email[VALID.ERROR.REQUIRED] = 'email is required' LANG.errors.email[VALID.ERROR.SIZE] = 'must be a valid email address with 3 to 70 characters' LANG.errors.email[VALID.ERROR.FORMAT] = 'must be alphanumeric, must have @ and period, must be 3 to 70 chars, and may contain following special chars: - . _ +' LANG.errors.email[VALID.ERROR.UNIQUE] = 'this email already exists' LANG.errors.email[VALID.ERROR.INVALID] = 'Invalid user name format, format should be in the form of email : user@sample.com' LANG.errors.confirm_email[VALID.ERROR.REQUIRED] = 'email is required' LANG.errors.confirm_email[VALID.ERROR.SIZE] = 'must be a valid email address with 3 to 70 characters' LANG.errors.confirm_email[VALID.ERROR.FORMAT] = 'must be alphanumeric, must have @ and period, must be 3 to 70 chars, and may contain following special chars: - . _ +' LANG.errors.confirm_email[VALID.ERROR.UNIQUE] = 'this email already exists' LANG.errors.confirm_email[VALID.ERROR.INVALID] = 'Invalid user name format, format should be in the form of email : user@sample.com' LANG.errors.confirm_email[VALID.ERROR.EQUAL] = 'the email address you entered does not match.' LANG }, { #create a valid compute whether the form is valid or not #the validity is changed when viewmodel changed, because viewmodel listens to errors and we can add more #checks too, look at {viewmodel} * change init:(elem, options)-> window.admin_info_form = this #this.bind_model_errors_to_viewmodel('admin', options.admin) this.render('admin_info_form/admin_info_form', {admin:options.admin}) this.element.find('input[name="phone"]').mask("(999) 999-9999") this.bind_view(options.admin) this.set_validity(false) 'input[name=email] paste':($input, e)-> e.preventDefault() return false 'input[name=confirm_email] paste':($input, e)-> e.preventDefault() return false '{admin.valid} change':()-> this.set_validity(this.options.admin.valid()) validate: ()-> this.options.admin.validate() #this.set_validity(validity) ###show_all_errors:()-> this.validate()### }) )
83720
define([ 'bases/control', '_', 'libs/masked_input_plugin_jquery', 'css!modules/admin_info_form/admin_info_form' ], (BaseControl, _)-> BaseControl.extend({ LANG: (controller)-> LANG = { errors:{ first_name:{} last_name:{} phone:{} email:{} confirm_email:{} } } LANG.errors.first_name[VALID.ERROR.SIZE] = 'first name must be 2 to 40 characters' LANG.errors.first_name[VALID.ERROR.REQUIRED] = 'first name is required' LANG.errors.first_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" LANG.errors.last_name[VALID.ERROR.REQUIRED] = 'last name is required' LANG.errors.last_name[VALID.ERROR.SIZE] = 'last name must be 2 to 40 characters' LANG.errors.last_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" ###LANG.errors.phone[VALID.ERROR.FORMAT] = 'must be 10 digits'### LANG.errors.phone[VALID.ERROR.REQUIRED] = 'phone number is required' LANG.errors.email[VALID.ERROR.REQUIRED] = 'email is required' LANG.errors.email[VALID.ERROR.SIZE] = 'must be a valid email address with 3 to 70 characters' LANG.errors.email[VALID.ERROR.FORMAT] = 'must be alphanumeric, must have @ and period, must be 3 to 70 chars, and may contain following special chars: - . _ +' LANG.errors.email[VALID.ERROR.UNIQUE] = 'this email already exists' LANG.errors.email[VALID.ERROR.INVALID] = 'Invalid user name format, format should be in the form of email : <EMAIL>' LANG.errors.confirm_email[VALID.ERROR.REQUIRED] = 'email is required' LANG.errors.confirm_email[VALID.ERROR.SIZE] = 'must be a valid email address with 3 to 70 characters' LANG.errors.confirm_email[VALID.ERROR.FORMAT] = 'must be alphanumeric, must have @ and period, must be 3 to 70 chars, and may contain following special chars: - . _ +' LANG.errors.confirm_email[VALID.ERROR.UNIQUE] = 'this email already exists' LANG.errors.confirm_email[VALID.ERROR.INVALID] = 'Invalid user name format, format should be in the form of email : <EMAIL>' LANG.errors.confirm_email[VALID.ERROR.EQUAL] = 'the email address you entered does not match.' LANG }, { #create a valid compute whether the form is valid or not #the validity is changed when viewmodel changed, because viewmodel listens to errors and we can add more #checks too, look at {viewmodel} * change init:(elem, options)-> window.admin_info_form = this #this.bind_model_errors_to_viewmodel('admin', options.admin) this.render('admin_info_form/admin_info_form', {admin:options.admin}) this.element.find('input[name="phone"]').mask("(999) 999-9999") this.bind_view(options.admin) this.set_validity(false) 'input[name=email] paste':($input, e)-> e.preventDefault() return false 'input[name=confirm_email] paste':($input, e)-> e.preventDefault() return false '{admin.valid} change':()-> this.set_validity(this.options.admin.valid()) validate: ()-> this.options.admin.validate() #this.set_validity(validity) ###show_all_errors:()-> this.validate()### }) )
true
define([ 'bases/control', '_', 'libs/masked_input_plugin_jquery', 'css!modules/admin_info_form/admin_info_form' ], (BaseControl, _)-> BaseControl.extend({ LANG: (controller)-> LANG = { errors:{ first_name:{} last_name:{} phone:{} email:{} confirm_email:{} } } LANG.errors.first_name[VALID.ERROR.SIZE] = 'first name must be 2 to 40 characters' LANG.errors.first_name[VALID.ERROR.REQUIRED] = 'first name is required' LANG.errors.first_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" LANG.errors.last_name[VALID.ERROR.REQUIRED] = 'last name is required' LANG.errors.last_name[VALID.ERROR.SIZE] = 'last name must be 2 to 40 characters' LANG.errors.last_name[VALID.ERROR.FORMAT] = "must be 2 to 40 characters alphanumeric, and may contain the following special chars: . , & ( ) ! ? - @ '" ###LANG.errors.phone[VALID.ERROR.FORMAT] = 'must be 10 digits'### LANG.errors.phone[VALID.ERROR.REQUIRED] = 'phone number is required' LANG.errors.email[VALID.ERROR.REQUIRED] = 'email is required' LANG.errors.email[VALID.ERROR.SIZE] = 'must be a valid email address with 3 to 70 characters' LANG.errors.email[VALID.ERROR.FORMAT] = 'must be alphanumeric, must have @ and period, must be 3 to 70 chars, and may contain following special chars: - . _ +' LANG.errors.email[VALID.ERROR.UNIQUE] = 'this email already exists' LANG.errors.email[VALID.ERROR.INVALID] = 'Invalid user name format, format should be in the form of email : PI:EMAIL:<EMAIL>END_PI' LANG.errors.confirm_email[VALID.ERROR.REQUIRED] = 'email is required' LANG.errors.confirm_email[VALID.ERROR.SIZE] = 'must be a valid email address with 3 to 70 characters' LANG.errors.confirm_email[VALID.ERROR.FORMAT] = 'must be alphanumeric, must have @ and period, must be 3 to 70 chars, and may contain following special chars: - . _ +' LANG.errors.confirm_email[VALID.ERROR.UNIQUE] = 'this email already exists' LANG.errors.confirm_email[VALID.ERROR.INVALID] = 'Invalid user name format, format should be in the form of email : PI:EMAIL:<EMAIL>END_PI' LANG.errors.confirm_email[VALID.ERROR.EQUAL] = 'the email address you entered does not match.' LANG }, { #create a valid compute whether the form is valid or not #the validity is changed when viewmodel changed, because viewmodel listens to errors and we can add more #checks too, look at {viewmodel} * change init:(elem, options)-> window.admin_info_form = this #this.bind_model_errors_to_viewmodel('admin', options.admin) this.render('admin_info_form/admin_info_form', {admin:options.admin}) this.element.find('input[name="phone"]').mask("(999) 999-9999") this.bind_view(options.admin) this.set_validity(false) 'input[name=email] paste':($input, e)-> e.preventDefault() return false 'input[name=confirm_email] paste':($input, e)-> e.preventDefault() return false '{admin.valid} change':()-> this.set_validity(this.options.admin.valid()) validate: ()-> this.options.admin.validate() #this.set_validity(validity) ###show_all_errors:()-> this.validate()### }) )
[ { "context": "###################################\n# MINDAY 0.010 Hanioti\n# sample-start.coffee\n# Стартовый экран\n########", "end": 70, "score": 0.6238375306129456, "start": 64, "tag": "NAME", "value": "Haniot" }, { "context": "R,plain:yes,goto:sample.timer()\n\n\tmd.push add \"(c...
sample-start.coffee
agershun/minday
0
################################################ # MINDAY 0.010 Hanioti # sample-start.coffee # Стартовый экран ################################################ library = null sample.start = -> m = createNewModel("start") m.readonly = yes selectModel("start") md = adf "Minday: Методики и инструменты анализа" background: 1 canvas: CANVASJS intype:TABLE tableclass:1 md1 = md.add null,rowspan:3,tableclass:1,valign:TOP md2 = md.adr "Методы",valign:TOP, md3 = md.add "Инструменты анализа",valign:TOP md4 = md.add "Как пользоваться программой?" md11 = md1.add "Новая модель" forma: BUTTON place: BAG scheme: BLUE # valign:TOP plain:yes run: -> updateModel("start") createNewModel("minday") selectModel("minday") m=adf "Новая модель" m.fhtml() md12 = md1.add "Открыть модель..." forma: BUTTON place: BAG scheme: WHITE plain:yes run: -> updateModel("start") createNewModel("mymodels") selectModel("mymodels") mm=adf "Мои модели" for k,v of models xa = add v.name xa.run = "selectModel('"+v.name+"',true);" mm.add xa mm.fhtml() updateModel("mymodels") library = md1.add "Библиотека моделей" forma: BUTTON place: BAG scheme: GREEN plain:yes frame:yes md14 = md1.add "Показать меню" forma: BUTTON place: BAG scheme: RED plain:yes run: -> viewFullScreen() md21 = md2.add intype:TABLE,tableclass:1,forma:BUTTON,scheme:WHITE,place:BAG md21.add kind:IMAGE, url:"icon-swot-64-64.png",w:64,h:64# md211 = md21.adr "SWOT-анализ",goto:sample.swot() md211.add "Анализ сильных<br>и слабых сторон",plain:yes md22 = md2.adr intype:TABLE,tableclass:1,forma:BUTTON,scheme:WHITE,place:BAG md22.add kind:IMAGE, url:"icon-businessmodel-64-64.png",w:64,h:64# md221 = md22.adr "Бизнес-модель" md221.add "Описание стратегии<br>предприятия",plain:yes # md22.add "",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-businessmodel-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.businessmodel() md ### md2.push md22=add "Списки<br>дел",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-check-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.checklist() md2.push md23=add "Пирамида<br>Маслоу",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-pyramid-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.maslow() md2.push md23=add "Голубые<br>океаны",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-blueocean-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.blueocean() md2.push md23=add "Матрица<br>БКГ",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-bcg-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.bcg() md3.push md31=add "Интеллектуальные<br>карты",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-mindmap-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.mmap() md3.push md32=add "Деревья<br>&nbsp;",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-tree-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.tree() md3.push md33=add "Матрицы<br>и таблицы",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-table-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.matrix() md3.push md33=add "Анкеты и<br>опросники",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-check-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.anketa() md3.push md34=add "Стратегические<br>карты",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-map-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,newline:yes,align:CENTER,goto:sample.maps() md3.push md35=add "Диаграмма<br>Ишикава",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-ishikawa-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.ishikawa() md3.push md36=add "Текст<br>&nbsp;",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-text-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.text() md3.push md36=add "Холст<br>и графика",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-canvas-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.canvas() md4.push md41=add "Клавиши<br>управления",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-key-64-64.png"),imageplace:TOP,list:TD,tableclass:1,align:CENTER,plain:yes,goto:sample.hotkey() md4.push md42=add "Таймер<br>&nbsp;",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-timer-64-64.png"),imageplace:TOP,list:TD,align:CENTER,plain:yes,goto:sample.timer() md.push add "(c) Андрей Гершун, 1993-2012",plain:yes showFullScreen() md ### ### st = adf "Добро пожаловать" background: 1 align: CENTER st.push st0=add "" st0.push st1=add "С чего начать работу?" align: CENTER childrenalign: CENTER st1.push add "Разработка<br>стратегии" image: add "strategy.jpg" imageplace: TOP list:SPAN button: BLUE st1.push add "Инструменты<br>лидера" image: add "leadership.jpg" imageplace: TOP list:SPAN button: LIGHTBLUE # st1.push add "Командная<br>работа" # image: add "team.jpg" # imageplace: TOP # list:SPAN # button: WHITE st1.push add "Управление<br>проектами" image: add "project.jpg" imageplace: TOP list:SPAN button: GREEN st0.push st2=add "" align: CENTER childrenalign: CENTER st2.push add "Принятие<br>решений" image: add "decision.jpg" imageplace: TOP list:SPAN button: RED st2.push add "Решение<br>задач" image: add "solving.jpg" imageplace: TOP list:SPAN button: BLACK st2.push add "Техники<br>креативности" image: add "creativity.jpg" imageplace: TOP list:SPAN button: LIGHTBLUE st.push st5=add "" st5.push st6=add "Популярные инструменты" st6.push sw=add "SWOT-анализ" image: add "swot.jpg" button: WHITE st6.push bo=add "Голубые океаны" image: add "blueocean.jpg" button: WHITE st
200231
################################################ # MINDAY 0.010 <NAME>i # sample-start.coffee # Стартовый экран ################################################ library = null sample.start = -> m = createNewModel("start") m.readonly = yes selectModel("start") md = adf "Minday: Методики и инструменты анализа" background: 1 canvas: CANVASJS intype:TABLE tableclass:1 md1 = md.add null,rowspan:3,tableclass:1,valign:TOP md2 = md.adr "Методы",valign:TOP, md3 = md.add "Инструменты анализа",valign:TOP md4 = md.add "Как пользоваться программой?" md11 = md1.add "Новая модель" forma: BUTTON place: BAG scheme: BLUE # valign:TOP plain:yes run: -> updateModel("start") createNewModel("minday") selectModel("minday") m=adf "Новая модель" m.fhtml() md12 = md1.add "Открыть модель..." forma: BUTTON place: BAG scheme: WHITE plain:yes run: -> updateModel("start") createNewModel("mymodels") selectModel("mymodels") mm=adf "Мои модели" for k,v of models xa = add v.name xa.run = "selectModel('"+v.name+"',true);" mm.add xa mm.fhtml() updateModel("mymodels") library = md1.add "Библиотека моделей" forma: BUTTON place: BAG scheme: GREEN plain:yes frame:yes md14 = md1.add "Показать меню" forma: BUTTON place: BAG scheme: RED plain:yes run: -> viewFullScreen() md21 = md2.add intype:TABLE,tableclass:1,forma:BUTTON,scheme:WHITE,place:BAG md21.add kind:IMAGE, url:"icon-swot-64-64.png",w:64,h:64# md211 = md21.adr "SWOT-анализ",goto:sample.swot() md211.add "Анализ сильных<br>и слабых сторон",plain:yes md22 = md2.adr intype:TABLE,tableclass:1,forma:BUTTON,scheme:WHITE,place:BAG md22.add kind:IMAGE, url:"icon-businessmodel-64-64.png",w:64,h:64# md221 = md22.adr "Бизнес-модель" md221.add "Описание стратегии<br>предприятия",plain:yes # md22.add "",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-businessmodel-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.businessmodel() md ### md2.push md22=add "Списки<br>дел",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-check-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.checklist() md2.push md23=add "Пирамида<br>Маслоу",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-pyramid-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.maslow() md2.push md23=add "Голубые<br>океаны",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-blueocean-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.blueocean() md2.push md23=add "Матрица<br>БКГ",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-bcg-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.bcg() md3.push md31=add "Интеллектуальные<br>карты",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-mindmap-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.mmap() md3.push md32=add "Деревья<br>&nbsp;",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-tree-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.tree() md3.push md33=add "Матрицы<br>и таблицы",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-table-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.matrix() md3.push md33=add "Анкеты и<br>опросники",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-check-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.anketa() md3.push md34=add "Стратегические<br>карты",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-map-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,newline:yes,align:CENTER,goto:sample.maps() md3.push md35=add "Диаграмма<br>Ишикава",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-ishikawa-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.ishikawa() md3.push md36=add "Текст<br>&nbsp;",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-text-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.text() md3.push md36=add "Холст<br>и графика",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-canvas-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.canvas() md4.push md41=add "Клавиши<br>управления",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-key-64-64.png"),imageplace:TOP,list:TD,tableclass:1,align:CENTER,plain:yes,goto:sample.hotkey() md4.push md42=add "Таймер<br>&nbsp;",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-timer-64-64.png"),imageplace:TOP,list:TD,align:CENTER,plain:yes,goto:sample.timer() md.push add "(c) <NAME>, 1993-2012",plain:yes showFullScreen() md ### ### st = adf "Добро пожаловать" background: 1 align: CENTER st.push st0=add "" st0.push st1=add "С чего начать работу?" align: CENTER childrenalign: CENTER st1.push add "Разработка<br>стратегии" image: add "strategy.jpg" imageplace: TOP list:SPAN button: BLUE st1.push add "Инструменты<br>лидера" image: add "leadership.jpg" imageplace: TOP list:SPAN button: LIGHTBLUE # st1.push add "Командная<br>работа" # image: add "team.jpg" # imageplace: TOP # list:SPAN # button: WHITE st1.push add "Управление<br>проектами" image: add "project.jpg" imageplace: TOP list:SPAN button: GREEN st0.push st2=add "" align: CENTER childrenalign: CENTER st2.push add "Принятие<br>решений" image: add "decision.jpg" imageplace: TOP list:SPAN button: RED st2.push add "Решение<br>задач" image: add "solving.jpg" imageplace: TOP list:SPAN button: BLACK st2.push add "Техники<br>креативности" image: add "creativity.jpg" imageplace: TOP list:SPAN button: LIGHTBLUE st.push st5=add "" st5.push st6=add "Популярные инструменты" st6.push sw=add "SWOT-анализ" image: add "swot.jpg" button: WHITE st6.push bo=add "Голубые океаны" image: add "blueocean.jpg" button: WHITE st
true
################################################ # MINDAY 0.010 PI:NAME:<NAME>END_PIi # sample-start.coffee # Стартовый экран ################################################ library = null sample.start = -> m = createNewModel("start") m.readonly = yes selectModel("start") md = adf "Minday: Методики и инструменты анализа" background: 1 canvas: CANVASJS intype:TABLE tableclass:1 md1 = md.add null,rowspan:3,tableclass:1,valign:TOP md2 = md.adr "Методы",valign:TOP, md3 = md.add "Инструменты анализа",valign:TOP md4 = md.add "Как пользоваться программой?" md11 = md1.add "Новая модель" forma: BUTTON place: BAG scheme: BLUE # valign:TOP plain:yes run: -> updateModel("start") createNewModel("minday") selectModel("minday") m=adf "Новая модель" m.fhtml() md12 = md1.add "Открыть модель..." forma: BUTTON place: BAG scheme: WHITE plain:yes run: -> updateModel("start") createNewModel("mymodels") selectModel("mymodels") mm=adf "Мои модели" for k,v of models xa = add v.name xa.run = "selectModel('"+v.name+"',true);" mm.add xa mm.fhtml() updateModel("mymodels") library = md1.add "Библиотека моделей" forma: BUTTON place: BAG scheme: GREEN plain:yes frame:yes md14 = md1.add "Показать меню" forma: BUTTON place: BAG scheme: RED plain:yes run: -> viewFullScreen() md21 = md2.add intype:TABLE,tableclass:1,forma:BUTTON,scheme:WHITE,place:BAG md21.add kind:IMAGE, url:"icon-swot-64-64.png",w:64,h:64# md211 = md21.adr "SWOT-анализ",goto:sample.swot() md211.add "Анализ сильных<br>и слабых сторон",plain:yes md22 = md2.adr intype:TABLE,tableclass:1,forma:BUTTON,scheme:WHITE,place:BAG md22.add kind:IMAGE, url:"icon-businessmodel-64-64.png",w:64,h:64# md221 = md22.adr "Бизнес-модель" md221.add "Описание стратегии<br>предприятия",plain:yes # md22.add "",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-businessmodel-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.businessmodel() md ### md2.push md22=add "Списки<br>дел",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-check-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.checklist() md2.push md23=add "Пирамида<br>Маслоу",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-pyramid-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.maslow() md2.push md23=add "Голубые<br>океаны",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-blueocean-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.blueocean() md2.push md23=add "Матрица<br>БКГ",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-bcg-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.bcg() md3.push md31=add "Интеллектуальные<br>карты",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-mindmap-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.mmap() md3.push md32=add "Деревья<br>&nbsp;",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-tree-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.tree() md3.push md33=add "Матрицы<br>и таблицы",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-table-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.matrix() md3.push md33=add "Анкеты и<br>опросники",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-check-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.anketa() md3.push md34=add "Стратегические<br>карты",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-map-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,newline:yes,align:CENTER,goto:sample.maps() md3.push md35=add "Диаграмма<br>Ишикава",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-ishikawa-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.ishikawa() md3.push md36=add "Текст<br>&nbsp;",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-text-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.text() md3.push md36=add "Холст<br>и графика",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-canvas-64-64.png"),imageplace:TOP,list:TD,tableclass:1,plain:yes,align:CENTER,goto:sample.canvas() md4.push md41=add "Клавиши<br>управления",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-key-64-64.png"),imageplace:TOP,list:TD,tableclass:1,align:CENTER,plain:yes,goto:sample.hotkey() md4.push md42=add "Таймер<br>&nbsp;",forma:BUTTON,place:BAG,scheme:BLUE,image:(add "icon-timer-64-64.png"),imageplace:TOP,list:TD,align:CENTER,plain:yes,goto:sample.timer() md.push add "(c) PI:NAME:<NAME>END_PI, 1993-2012",plain:yes showFullScreen() md ### ### st = adf "Добро пожаловать" background: 1 align: CENTER st.push st0=add "" st0.push st1=add "С чего начать работу?" align: CENTER childrenalign: CENTER st1.push add "Разработка<br>стратегии" image: add "strategy.jpg" imageplace: TOP list:SPAN button: BLUE st1.push add "Инструменты<br>лидера" image: add "leadership.jpg" imageplace: TOP list:SPAN button: LIGHTBLUE # st1.push add "Командная<br>работа" # image: add "team.jpg" # imageplace: TOP # list:SPAN # button: WHITE st1.push add "Управление<br>проектами" image: add "project.jpg" imageplace: TOP list:SPAN button: GREEN st0.push st2=add "" align: CENTER childrenalign: CENTER st2.push add "Принятие<br>решений" image: add "decision.jpg" imageplace: TOP list:SPAN button: RED st2.push add "Решение<br>задач" image: add "solving.jpg" imageplace: TOP list:SPAN button: BLACK st2.push add "Техники<br>креативности" image: add "creativity.jpg" imageplace: TOP list:SPAN button: LIGHTBLUE st.push st5=add "" st5.push st6=add "Популярные инструменты" st6.push sw=add "SWOT-анализ" image: add "swot.jpg" button: WHITE st6.push bo=add "Голубые океаны" image: add "blueocean.jpg" button: WHITE st
[ { "context": "->\n res.json([{type: 'bulldozer', name: 'willy'}])\n\n args = ['./test/fixtures/single-get.", "end": 688, "score": 0.7254014015197754, "start": 683, "tag": "NAME", "value": "willy" }, { "context": "rgs = ['./test/fixtures/single-get.apib', \"http://127....
test/integration/cli/cli-test.coffee
hitsumabushi/dredd
0
{assert} = require('chai') net = require('net') {exec} = require('child_process') {isProcessRunning, killAll, createServer, runDreddCommandWithServer, runDreddCommand, DEFAULT_SERVER_PORT} = require('../helpers') COFFEE_BIN = 'node_modules/.bin/coffee' DEFAULT_HOOK_HANDLER_PORT = 61321 describe 'CLI', -> describe "Arguments with existing API description document and responding server", -> describe "when executing the command and the server is responding as specified in the API description", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = ['./test/fixtures/single-get.apib', "http://127.0.0.1:#{DEFAULT_SERVER_PORT}"] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'exit status should be 0', -> assert.equal runtimeInfo.dredd.exitStatus, 0 describe "when executing the command and the server is responding as specified in the API description, endpoint with path", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/v2/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = ['./test/fixtures/single-get.apib', "http://127.0.0.1:#{DEFAULT_SERVER_PORT}/v2/"] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'exit status should be 0', -> assert.equal runtimeInfo.dredd.exitStatus, 0 describe "when executing the command and the server is sending different response", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.status(201).json([{kind: 'bulldozer', imatriculation: 'willy'}]) args = ['./test/fixtures/single-get.apib', "http://127.0.0.1:#{DEFAULT_SERVER_PORT}"] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'exit status should be 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 describe "when called with arguments", -> describe 'when using language hook handler and spawning the server', -> describe "and handler file doesn't exist", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--server-wait=0' '--language=foo/bar/hook-handler' '--hookfiles=./test/fixtures/scripts/emptyfile' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) after (done) -> killAll('test/fixtures/scripts/', done) it 'should return with status 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 it 'should not return message containing exited or killed', -> assert.notInclude runtimeInfo.dredd.stderr, 'exited' assert.notInclude runtimeInfo.dredd.stderr, 'killed' it 'should not return message announcing the fact', -> assert.include runtimeInfo.dredd.stderr, 'not found' it 'should term or kill the server', (done) -> isProcessRunning('endless-ignore-term', (err, isRunning) -> assert.isFalse isRunning unless err done(err) ) it 'should not execute any transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {} describe 'and handler crashes before execution', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--server-wait=0' "--language=#{COFFEE_BIN} ./test/fixtures/scripts/exit-3.coffee" '--hookfiles=./test/fixtures/scripts/emptyfile' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) after (done) -> killAll('test/fixtures/scripts/', done) it 'should return with status 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 it 'should return message announcing the fact', -> assert.include runtimeInfo.dredd.stderr, 'exited' it 'should term or kill the server', (done) -> isProcessRunning('endless-ignore-term', (err, isRunning) -> assert.isFalse isRunning unless err done(err) ) it 'should not execute any transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {} describe "and handler is killed before execution", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" "--server=#{COFFEE_BIN} ./test/fixtures/scripts/endless-ignore-term.coffee" '--server-wait=0' "--language=#{COFFEE_BIN} ./test/fixtures/scripts/kill-self.coffee" '--hookfiles=./test/fixtures/scripts/emptyfile' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) after (done) -> killAll('test/fixtures/scripts/', done) it 'should return with status 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 it 'should return message announcing the fact', -> if process.platform is 'win32' # On Windows there's no way to detect a process was killed assert.include runtimeInfo.dredd.stderr, 'exited' else assert.include runtimeInfo.dredd.stderr, 'killed' it 'should term or kill the server', (done) -> isProcessRunning('endless-ignore-term', (err, isRunning) -> assert.isFalse isRunning unless err done(err) ) it 'should not execute any transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {} describe "and handler is killed during execution", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> killAll('endless-ignore-term.+[^=]foo/bar/hooks', (err) -> done err if err res.json([{type: 'bulldozer', name: 'willy'}]) ) # TCP server echoing transactions back hookHandler = net.createServer (socket) -> socket.on 'data', (data) -> socket.write data socket.on 'error', (err) -> console.error err args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" "--server=#{COFFEE_BIN} ./test/fixtures/scripts/endless-ignore-term.coffee" '--server-wait=0' "--language=#{COFFEE_BIN} ./test/fixtures/scripts/endless-ignore-term.coffee" '--hookfiles=foo/bar/hooks' ] hookHandler.listen DEFAULT_HOOK_HANDLER_PORT, -> runDreddCommandWithServer(args, app, (err, info) -> hookHandler.close() runtimeInfo = info done(err) ) after (done) -> killAll('test/fixtures/scripts/', done) it 'should return with status 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 it 'should return message announcing the fact', -> if process.platform is 'win32' # On Windows there's no way to detect a process was killed assert.include runtimeInfo.dredd.stderr, 'exited' else assert.include runtimeInfo.dredd.stderr, 'killed' it 'should term or kill the server', (done) -> isProcessRunning('endless-ignore-term', (err, isRunning) -> assert.isFalse isRunning unless err done(err) ) it 'should execute the transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {'/machines': 1} describe "and handler didn't quit but all Dredd tests were OK", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) # TCP server echoing transactions back hookHandler = net.createServer (socket) -> socket.on 'data', (data) -> socket.write data socket.on 'error', (err) -> console.error err args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" "--server=#{COFFEE_BIN} ./test/fixtures/scripts/endless-ignore-term.coffee" '--server-wait=0' "--language=#{COFFEE_BIN} ./test/fixtures/scripts/endless-ignore-term.coffee" '--hookfiles=./test/fixtures/scripts/emptyfile' ] hookHandler.listen DEFAULT_HOOK_HANDLER_PORT, -> runDreddCommandWithServer(args, app, (err, info) -> hookHandler.close() runtimeInfo = info done(err) ) after (done) -> killAll('test/fixtures/scripts/', done) it 'should return with status 0', -> assert.equal runtimeInfo.dredd.exitStatus, 0 it 'should not return any killed or exited message', -> assert.notInclude runtimeInfo.dredd.stderr, 'killed' assert.notInclude runtimeInfo.dredd.stderr, 'exited' it 'should kill both the handler and the server', (done) -> isProcessRunning('endless-ignore-term', (err, isRunning) -> assert.isFalse isRunning unless err done(err) ) it 'should execute some transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {'/machines': 1} describe "when adding additional headers with -h", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-h' 'Accept:application/json' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should have an additional header in the request', -> assert.deepPropertyVal runtimeInfo.server.requests['/machines'][0], 'headers.accept', 'application/json' describe "when adding basic auth credentials with -u", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-u' 'username:password' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should have an authorization header in the request', -> assert.isOk runtimeInfo.server.requests['/machines'][0].headers.authorization it 'should contain a base64 encoded string of the username and password', -> assert.isOk runtimeInfo.server.requests['/machines'][0].headers.authorization is 'Basic ' + new Buffer('username:password').toString('base64') describe "when sorting requests with -s", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/apiary.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-s' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should perform the POST, GET, PUT, DELETE in order', -> assert.isOk runtimeInfo.dredd.stdout.indexOf('POST') < runtimeInfo.dredd.stdout.indexOf('GET') < runtimeInfo.dredd.stdout.indexOf('PUT') < runtimeInfo.dredd.stdout.indexOf('DELETE') describe 'when displaying errors inline with -e', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.status(201).json([{kind: 'bulldozer', imatriculation: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-e' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should display errors inline', -> # when displayed inline, a single fail request only creates two "fail:" messages, # as opposed to the usual three count = runtimeInfo.dredd.stdout.split("fail").length - 2 #says fail in the epilogue assert.equal count, 2 describe 'when showing details for all requests with -d', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-d' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should display details on passing tests', -> # the request: block is not shown for passing tests normally assert.isOk runtimeInfo.dredd.stdout.indexOf('request') > -1 describe "when filtering request methods with -m", -> describe 'when blocking a request', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-m', 'POST' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should not send the request request', -> assert.deepEqual runtimeInfo.server.requestCounts, {} describe 'when not blocking a request', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-m', 'GET' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should allow the request to go through', -> assert.deepEqual runtimeInfo.server.requestCounts, {'/machines': 1} describe "when filtering transaction to particular name with -x or --only", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) app.get '/message', (req, res) -> res.type('text/plain').send "Hello World!\n" args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--path=./test/fixtures/multifile/*.apib' '--only=Message API > /message > GET' '--no-color' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should notify skipping to the stdout', -> assert.include runtimeInfo.dredd.stdout, 'skip: GET /machines' it 'should hit the only transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {'/message': 1} it 'exit status should be 0', -> assert.equal runtimeInfo.dredd.exitStatus, 0 describe 'when suppressing color with --no-color', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--no-color' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should print without colors', -> # if colors are not on, there is no closing color code between # the "pass" and the ":" assert.include runtimeInfo.dredd.stdout, 'pass:' describe 'when suppressing color with --color=false', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--color=false' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should print without colors', -> # if colors are not on, there is no closing color code between # the "pass" and the ":" assert.include runtimeInfo.dredd.stdout, 'pass:' describe 'when setting the log output level with -l', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-l=error' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should not display anything', -> # at the "error" level, complete should not be shown assert.isOk runtimeInfo.dredd.stdout.indexOf('complete') is -1 describe 'when showing timestamps with -t', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-t' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should display timestamps', -> # look for the prefix for cli output with timestamps assert.notEqual runtimeInfo.dredd.stdout.indexOf('Z -'), -1 describe 'when loading hooks with --hookfiles', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--hookfiles=./test/fixtures/*_hooks.*' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should modify the transaction with hooks', -> assert.equal runtimeInfo.server.requests['/machines'][0].headers['header'], '123232323' describe 'when describing events in hookfiles', -> runtimeInfo = undefined containsLine = (str, expected) -> lines = str.split('\n') for line in lines if line.indexOf(expected) > -1 return true return false before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--hookfiles=./test/fixtures/*_events.*' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should execute the before and after events', -> assert.isOk containsLine(runtimeInfo.dredd.stdout, 'hooks.beforeAll'), (runtimeInfo.dredd.stdout) assert.isOk containsLine(runtimeInfo.dredd.stdout, 'hooks.afterAll'), (runtimeInfo.dredd.stdout) describe 'when describing both hooks and events in hookfiles', -> runtimeInfo = undefined getResults = (str) -> ret = [] lines = str.split('\n') for line in lines if line.indexOf('*** ') > -1 ret.push(line.substr(line.indexOf('*** ') + 4)) return ret.join(',') before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--hookfiles=./test/fixtures/*_all.*' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should execute hooks and events in order', -> events = getResults(runtimeInfo.dredd.stdout) assert.isOk events is 'beforeAll,before,after,afterAll' describe "tests an API description containing an endpoint with schema", -> describe "and server is responding in accordance with the schema", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/', (req, res) -> res.json( data: expires: 1234, token: 'this should pass since it is a string' ) args = [ './test/fixtures/schema.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'exit status should be 0 (success)', -> assert.equal runtimeInfo.dredd.exitStatus, 0 describe "and server is NOT responding in accordance with the schema", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/', (req, res) -> res.json( data: expires: 'this should fail since it is a string', token: 'this should pass since it is a string' ) args = [ './test/fixtures/schema.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'exit status should be 1 (failure)', -> assert.equal runtimeInfo.dredd.exitStatus, 1 describe "when API description document path is a glob", -> describe "and called with --names options", -> dreddCommandInfo = undefined before (done) -> args = [ './test/fixtures/multifile/*.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--names' ] runDreddCommand(args, (err, info) -> dreddCommandInfo = info done(err) ) it 'it should include all paths from all API description documents matching the glob', -> assert.include dreddCommandInfo.stdout, '> /greeting > GET' assert.include dreddCommandInfo.stdout, '> /message > GET' assert.include dreddCommandInfo.stdout, '> /name > GET' it 'should exit with status 0', -> assert.equal dreddCommandInfo.exitStatus, 0 describe 'and called with hooks', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/name', (req, res) -> res.type('text/plain').send "Adam\n" app.get '/greeting', (req, res) -> res.type('text/plain').send "Howdy!\n" app.get '/message', (req, res) -> res.type('text/plain').send "Hello World!\n" args = [ './test/fixtures/multifile/*.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--hookfiles=./test/fixtures/multifile/multifile_hooks.coffee' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should eval the hook for each transaction', -> assert.include runtimeInfo.dredd.stdout, 'after name' assert.include runtimeInfo.dredd.stdout, 'after greeting' assert.include runtimeInfo.dredd.stdout, 'after message' it 'should exit with status 0', -> assert.equal runtimeInfo.dredd.exitStatus, 0, (runtimeInfo.dredd.output) it 'server should receive 3 requests', -> assert.deepEqual runtimeInfo.server.requestCounts, '/name': 1 '/greeting': 1 '/message': 1 describe "when called with additional --path argument which is a glob", -> describe "and called with --names options", -> dreddCommandInfo = undefined before (done) -> args = [ './test/fixtures/multiple-examples.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--path=./test/fixtures/multifile/*.apib' '--names' ] runDreddCommand(args, (err, info) -> dreddCommandInfo = info done(err) ) it 'it should include all paths from all API description documents matching all paths and globs', -> assert.include dreddCommandInfo.stdout, 'Greeting API > /greeting > GET' assert.include dreddCommandInfo.stdout, 'Message API > /message > GET' assert.include dreddCommandInfo.stdout, 'Name API > /name > GET' assert.include dreddCommandInfo.stdout, 'Machines API > Machines > Machines collection > Get Machines > Example 1' assert.include dreddCommandInfo.stdout, 'Machines API > Machines > Machines collection > Get Machines > Example 2' it 'should exit with status 0', -> assert.equal dreddCommandInfo.exitStatus, 0 describe "Using sandboxed hooks", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--sandbox' '--hookfiles=./test/fixtures/sandboxed-hook.js' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should hit the resource', -> assert.deepEqual runtimeInfo.server.requestCounts, {'/machines': 1} it 'exit status should be 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 it 'stdout shoud contain fail message', -> assert.include runtimeInfo.dredd.stdout, 'failed in sandboxed hook' it 'stdout shoud contain sandbox messagae', -> assert.include runtimeInfo.dredd.stdout, 'Loading hook files in sandboxed context'
143658
{assert} = require('chai') net = require('net') {exec} = require('child_process') {isProcessRunning, killAll, createServer, runDreddCommandWithServer, runDreddCommand, DEFAULT_SERVER_PORT} = require('../helpers') COFFEE_BIN = 'node_modules/.bin/coffee' DEFAULT_HOOK_HANDLER_PORT = 61321 describe 'CLI', -> describe "Arguments with existing API description document and responding server", -> describe "when executing the command and the server is responding as specified in the API description", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) args = ['./test/fixtures/single-get.apib', "http://127.0.0.1:#{DEFAULT_SERVER_PORT}"] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'exit status should be 0', -> assert.equal runtimeInfo.dredd.exitStatus, 0 describe "when executing the command and the server is responding as specified in the API description, endpoint with path", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/v2/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>ly'}]) args = ['./test/fixtures/single-get.apib', "http://127.0.0.1:#{DEFAULT_SERVER_PORT}/v2/"] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'exit status should be 0', -> assert.equal runtimeInfo.dredd.exitStatus, 0 describe "when executing the command and the server is sending different response", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.status(201).json([{kind: 'bulldozer', imatriculation: 'willy'}]) args = ['./test/fixtures/single-get.apib', "http://127.0.0.1:#{DEFAULT_SERVER_PORT}"] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'exit status should be 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 describe "when called with arguments", -> describe 'when using language hook handler and spawning the server', -> describe "and handler file doesn't exist", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--server-wait=0' '--language=foo/bar/hook-handler' '--hookfiles=./test/fixtures/scripts/emptyfile' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) after (done) -> killAll('test/fixtures/scripts/', done) it 'should return with status 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 it 'should not return message containing exited or killed', -> assert.notInclude runtimeInfo.dredd.stderr, 'exited' assert.notInclude runtimeInfo.dredd.stderr, 'killed' it 'should not return message announcing the fact', -> assert.include runtimeInfo.dredd.stderr, 'not found' it 'should term or kill the server', (done) -> isProcessRunning('endless-ignore-term', (err, isRunning) -> assert.isFalse isRunning unless err done(err) ) it 'should not execute any transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {} describe 'and handler crashes before execution', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--server-wait=0' "--language=#{COFFEE_BIN} ./test/fixtures/scripts/exit-3.coffee" '--hookfiles=./test/fixtures/scripts/emptyfile' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) after (done) -> killAll('test/fixtures/scripts/', done) it 'should return with status 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 it 'should return message announcing the fact', -> assert.include runtimeInfo.dredd.stderr, 'exited' it 'should term or kill the server', (done) -> isProcessRunning('endless-ignore-term', (err, isRunning) -> assert.isFalse isRunning unless err done(err) ) it 'should not execute any transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {} describe "and handler is killed before execution", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" "--server=#{COFFEE_BIN} ./test/fixtures/scripts/endless-ignore-term.coffee" '--server-wait=0' "--language=#{COFFEE_BIN} ./test/fixtures/scripts/kill-self.coffee" '--hookfiles=./test/fixtures/scripts/emptyfile' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) after (done) -> killAll('test/fixtures/scripts/', done) it 'should return with status 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 it 'should return message announcing the fact', -> if process.platform is 'win32' # On Windows there's no way to detect a process was killed assert.include runtimeInfo.dredd.stderr, 'exited' else assert.include runtimeInfo.dredd.stderr, 'killed' it 'should term or kill the server', (done) -> isProcessRunning('endless-ignore-term', (err, isRunning) -> assert.isFalse isRunning unless err done(err) ) it 'should not execute any transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {} describe "and handler is killed during execution", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> killAll('endless-ignore-term.+[^=]foo/bar/hooks', (err) -> done err if err res.json([{type: 'bulldozer', name: '<NAME>'}]) ) # TCP server echoing transactions back hookHandler = net.createServer (socket) -> socket.on 'data', (data) -> socket.write data socket.on 'error', (err) -> console.error err args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" "--server=#{COFFEE_BIN} ./test/fixtures/scripts/endless-ignore-term.coffee" '--server-wait=0' "--language=#{COFFEE_BIN} ./test/fixtures/scripts/endless-ignore-term.coffee" '--hookfiles=foo/bar/hooks' ] hookHandler.listen DEFAULT_HOOK_HANDLER_PORT, -> runDreddCommandWithServer(args, app, (err, info) -> hookHandler.close() runtimeInfo = info done(err) ) after (done) -> killAll('test/fixtures/scripts/', done) it 'should return with status 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 it 'should return message announcing the fact', -> if process.platform is 'win32' # On Windows there's no way to detect a process was killed assert.include runtimeInfo.dredd.stderr, 'exited' else assert.include runtimeInfo.dredd.stderr, 'killed' it 'should term or kill the server', (done) -> isProcessRunning('endless-ignore-term', (err, isRunning) -> assert.isFalse isRunning unless err done(err) ) it 'should execute the transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {'/machines': 1} describe "and handler didn't quit but all Dredd tests were OK", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) # TCP server echoing transactions back hookHandler = net.createServer (socket) -> socket.on 'data', (data) -> socket.write data socket.on 'error', (err) -> console.error err args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" "--server=#{COFFEE_BIN} ./test/fixtures/scripts/endless-ignore-term.coffee" '--server-wait=0' "--language=#{COFFEE_BIN} ./test/fixtures/scripts/endless-ignore-term.coffee" '--hookfiles=./test/fixtures/scripts/emptyfile' ] hookHandler.listen DEFAULT_HOOK_HANDLER_PORT, -> runDreddCommandWithServer(args, app, (err, info) -> hookHandler.close() runtimeInfo = info done(err) ) after (done) -> killAll('test/fixtures/scripts/', done) it 'should return with status 0', -> assert.equal runtimeInfo.dredd.exitStatus, 0 it 'should not return any killed or exited message', -> assert.notInclude runtimeInfo.dredd.stderr, 'killed' assert.notInclude runtimeInfo.dredd.stderr, 'exited' it 'should kill both the handler and the server', (done) -> isProcessRunning('endless-ignore-term', (err, isRunning) -> assert.isFalse isRunning unless err done(err) ) it 'should execute some transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {'/machines': 1} describe "when adding additional headers with -h", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-h' 'Accept:application/json' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should have an additional header in the request', -> assert.deepPropertyVal runtimeInfo.server.requests['/machines'][0], 'headers.accept', 'application/json' describe "when adding basic auth credentials with -u", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-u' 'username:password' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should have an authorization header in the request', -> assert.isOk runtimeInfo.server.requests['/machines'][0].headers.authorization it 'should contain a base64 encoded string of the username and password', -> assert.isOk runtimeInfo.server.requests['/machines'][0].headers.authorization is 'Basic ' + new Buffer('username:password').toString('base64') describe "when sorting requests with -s", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) args = [ './test/fixtures/apiary.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-s' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should perform the POST, GET, PUT, DELETE in order', -> assert.isOk runtimeInfo.dredd.stdout.indexOf('POST') < runtimeInfo.dredd.stdout.indexOf('GET') < runtimeInfo.dredd.stdout.indexOf('PUT') < runtimeInfo.dredd.stdout.indexOf('DELETE') describe 'when displaying errors inline with -e', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.status(201).json([{kind: 'bulldozer', imatriculation: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-e' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should display errors inline', -> # when displayed inline, a single fail request only creates two "fail:" messages, # as opposed to the usual three count = runtimeInfo.dredd.stdout.split("fail").length - 2 #says fail in the epilogue assert.equal count, 2 describe 'when showing details for all requests with -d', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-d' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should display details on passing tests', -> # the request: block is not shown for passing tests normally assert.isOk runtimeInfo.dredd.stdout.indexOf('request') > -1 describe "when filtering request methods with -m", -> describe 'when blocking a request', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-m', 'POST' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should not send the request request', -> assert.deepEqual runtimeInfo.server.requestCounts, {} describe 'when not blocking a request', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-m', 'GET' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should allow the request to go through', -> assert.deepEqual runtimeInfo.server.requestCounts, {'/machines': 1} describe "when filtering transaction to particular name with -x or --only", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) app.get '/message', (req, res) -> res.type('text/plain').send "Hello World!\n" args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--path=./test/fixtures/multifile/*.apib' '--only=Message API > /message > GET' '--no-color' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should notify skipping to the stdout', -> assert.include runtimeInfo.dredd.stdout, 'skip: GET /machines' it 'should hit the only transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {'/message': 1} it 'exit status should be 0', -> assert.equal runtimeInfo.dredd.exitStatus, 0 describe 'when suppressing color with --no-color', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--no-color' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should print without colors', -> # if colors are not on, there is no closing color code between # the "pass" and the ":" assert.include runtimeInfo.dredd.stdout, 'pass:' describe 'when suppressing color with --color=false', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--color=false' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should print without colors', -> # if colors are not on, there is no closing color code between # the "pass" and the ":" assert.include runtimeInfo.dredd.stdout, 'pass:' describe 'when setting the log output level with -l', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-l=error' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should not display anything', -> # at the "error" level, complete should not be shown assert.isOk runtimeInfo.dredd.stdout.indexOf('complete') is -1 describe 'when showing timestamps with -t', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-t' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should display timestamps', -> # look for the prefix for cli output with timestamps assert.notEqual runtimeInfo.dredd.stdout.indexOf('Z -'), -1 describe 'when loading hooks with --hookfiles', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--hookfiles=./test/fixtures/*_hooks.*' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should modify the transaction with hooks', -> assert.equal runtimeInfo.server.requests['/machines'][0].headers['header'], '123232323' describe 'when describing events in hookfiles', -> runtimeInfo = undefined containsLine = (str, expected) -> lines = str.split('\n') for line in lines if line.indexOf(expected) > -1 return true return false before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--hookfiles=./test/fixtures/*_events.*' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should execute the before and after events', -> assert.isOk containsLine(runtimeInfo.dredd.stdout, 'hooks.beforeAll'), (runtimeInfo.dredd.stdout) assert.isOk containsLine(runtimeInfo.dredd.stdout, 'hooks.afterAll'), (runtimeInfo.dredd.stdout) describe 'when describing both hooks and events in hookfiles', -> runtimeInfo = undefined getResults = (str) -> ret = [] lines = str.split('\n') for line in lines if line.indexOf('*** ') > -1 ret.push(line.substr(line.indexOf('*** ') + 4)) return ret.join(',') before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--hookfiles=./test/fixtures/*_all.*' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should execute hooks and events in order', -> events = getResults(runtimeInfo.dredd.stdout) assert.isOk events is 'beforeAll,before,after,afterAll' describe "tests an API description containing an endpoint with schema", -> describe "and server is responding in accordance with the schema", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/', (req, res) -> res.json( data: expires: 1234, token: '<PASSWORD>' ) args = [ './test/fixtures/schema.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'exit status should be 0 (success)', -> assert.equal runtimeInfo.dredd.exitStatus, 0 describe "and server is NOT responding in accordance with the schema", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/', (req, res) -> res.json( data: expires: 'this should fail since it is a string', token: '<PASSWORD>' ) args = [ './test/fixtures/schema.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'exit status should be 1 (failure)', -> assert.equal runtimeInfo.dredd.exitStatus, 1 describe "when API description document path is a glob", -> describe "and called with --names options", -> dreddCommandInfo = undefined before (done) -> args = [ './test/fixtures/multifile/*.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--names' ] runDreddCommand(args, (err, info) -> dreddCommandInfo = info done(err) ) it 'it should include all paths from all API description documents matching the glob', -> assert.include dreddCommandInfo.stdout, '> /greeting > GET' assert.include dreddCommandInfo.stdout, '> /message > GET' assert.include dreddCommandInfo.stdout, '> /name > GET' it 'should exit with status 0', -> assert.equal dreddCommandInfo.exitStatus, 0 describe 'and called with hooks', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/name', (req, res) -> res.type('text/plain').send "<NAME>\n" app.get '/greeting', (req, res) -> res.type('text/plain').send "Howdy!\n" app.get '/message', (req, res) -> res.type('text/plain').send "Hello World!\n" args = [ './test/fixtures/multifile/*.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--hookfiles=./test/fixtures/multifile/multifile_hooks.coffee' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should eval the hook for each transaction', -> assert.include runtimeInfo.dredd.stdout, 'after name' assert.include runtimeInfo.dredd.stdout, 'after greeting' assert.include runtimeInfo.dredd.stdout, 'after message' it 'should exit with status 0', -> assert.equal runtimeInfo.dredd.exitStatus, 0, (runtimeInfo.dredd.output) it 'server should receive 3 requests', -> assert.deepEqual runtimeInfo.server.requestCounts, '/name': 1 '/greeting': 1 '/message': 1 describe "when called with additional --path argument which is a glob", -> describe "and called with --names options", -> dreddCommandInfo = undefined before (done) -> args = [ './test/fixtures/multiple-examples.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--path=./test/fixtures/multifile/*.apib' '--names' ] runDreddCommand(args, (err, info) -> dreddCommandInfo = info done(err) ) it 'it should include all paths from all API description documents matching all paths and globs', -> assert.include dreddCommandInfo.stdout, 'Greeting API > /greeting > GET' assert.include dreddCommandInfo.stdout, 'Message API > /message > GET' assert.include dreddCommandInfo.stdout, 'Name API > /name > GET' assert.include dreddCommandInfo.stdout, 'Machines API > Machines > Machines collection > Get Machines > Example 1' assert.include dreddCommandInfo.stdout, 'Machines API > Machines > Machines collection > Get Machines > Example 2' it 'should exit with status 0', -> assert.equal dreddCommandInfo.exitStatus, 0 describe "Using sandboxed hooks", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: '<NAME>'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--sandbox' '--hookfiles=./test/fixtures/sandboxed-hook.js' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should hit the resource', -> assert.deepEqual runtimeInfo.server.requestCounts, {'/machines': 1} it 'exit status should be 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 it 'stdout shoud contain fail message', -> assert.include runtimeInfo.dredd.stdout, 'failed in sandboxed hook' it 'stdout shoud contain sandbox messagae', -> assert.include runtimeInfo.dredd.stdout, 'Loading hook files in sandboxed context'
true
{assert} = require('chai') net = require('net') {exec} = require('child_process') {isProcessRunning, killAll, createServer, runDreddCommandWithServer, runDreddCommand, DEFAULT_SERVER_PORT} = require('../helpers') COFFEE_BIN = 'node_modules/.bin/coffee' DEFAULT_HOOK_HANDLER_PORT = 61321 describe 'CLI', -> describe "Arguments with existing API description document and responding server", -> describe "when executing the command and the server is responding as specified in the API description", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) args = ['./test/fixtures/single-get.apib', "http://127.0.0.1:#{DEFAULT_SERVER_PORT}"] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'exit status should be 0', -> assert.equal runtimeInfo.dredd.exitStatus, 0 describe "when executing the command and the server is responding as specified in the API description, endpoint with path", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/v2/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PIly'}]) args = ['./test/fixtures/single-get.apib', "http://127.0.0.1:#{DEFAULT_SERVER_PORT}/v2/"] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'exit status should be 0', -> assert.equal runtimeInfo.dredd.exitStatus, 0 describe "when executing the command and the server is sending different response", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.status(201).json([{kind: 'bulldozer', imatriculation: 'willy'}]) args = ['./test/fixtures/single-get.apib', "http://127.0.0.1:#{DEFAULT_SERVER_PORT}"] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'exit status should be 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 describe "when called with arguments", -> describe 'when using language hook handler and spawning the server', -> describe "and handler file doesn't exist", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--server-wait=0' '--language=foo/bar/hook-handler' '--hookfiles=./test/fixtures/scripts/emptyfile' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) after (done) -> killAll('test/fixtures/scripts/', done) it 'should return with status 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 it 'should not return message containing exited or killed', -> assert.notInclude runtimeInfo.dredd.stderr, 'exited' assert.notInclude runtimeInfo.dredd.stderr, 'killed' it 'should not return message announcing the fact', -> assert.include runtimeInfo.dredd.stderr, 'not found' it 'should term or kill the server', (done) -> isProcessRunning('endless-ignore-term', (err, isRunning) -> assert.isFalse isRunning unless err done(err) ) it 'should not execute any transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {} describe 'and handler crashes before execution', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--server-wait=0' "--language=#{COFFEE_BIN} ./test/fixtures/scripts/exit-3.coffee" '--hookfiles=./test/fixtures/scripts/emptyfile' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) after (done) -> killAll('test/fixtures/scripts/', done) it 'should return with status 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 it 'should return message announcing the fact', -> assert.include runtimeInfo.dredd.stderr, 'exited' it 'should term or kill the server', (done) -> isProcessRunning('endless-ignore-term', (err, isRunning) -> assert.isFalse isRunning unless err done(err) ) it 'should not execute any transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {} describe "and handler is killed before execution", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" "--server=#{COFFEE_BIN} ./test/fixtures/scripts/endless-ignore-term.coffee" '--server-wait=0' "--language=#{COFFEE_BIN} ./test/fixtures/scripts/kill-self.coffee" '--hookfiles=./test/fixtures/scripts/emptyfile' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) after (done) -> killAll('test/fixtures/scripts/', done) it 'should return with status 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 it 'should return message announcing the fact', -> if process.platform is 'win32' # On Windows there's no way to detect a process was killed assert.include runtimeInfo.dredd.stderr, 'exited' else assert.include runtimeInfo.dredd.stderr, 'killed' it 'should term or kill the server', (done) -> isProcessRunning('endless-ignore-term', (err, isRunning) -> assert.isFalse isRunning unless err done(err) ) it 'should not execute any transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {} describe "and handler is killed during execution", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> killAll('endless-ignore-term.+[^=]foo/bar/hooks', (err) -> done err if err res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) ) # TCP server echoing transactions back hookHandler = net.createServer (socket) -> socket.on 'data', (data) -> socket.write data socket.on 'error', (err) -> console.error err args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" "--server=#{COFFEE_BIN} ./test/fixtures/scripts/endless-ignore-term.coffee" '--server-wait=0' "--language=#{COFFEE_BIN} ./test/fixtures/scripts/endless-ignore-term.coffee" '--hookfiles=foo/bar/hooks' ] hookHandler.listen DEFAULT_HOOK_HANDLER_PORT, -> runDreddCommandWithServer(args, app, (err, info) -> hookHandler.close() runtimeInfo = info done(err) ) after (done) -> killAll('test/fixtures/scripts/', done) it 'should return with status 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 it 'should return message announcing the fact', -> if process.platform is 'win32' # On Windows there's no way to detect a process was killed assert.include runtimeInfo.dredd.stderr, 'exited' else assert.include runtimeInfo.dredd.stderr, 'killed' it 'should term or kill the server', (done) -> isProcessRunning('endless-ignore-term', (err, isRunning) -> assert.isFalse isRunning unless err done(err) ) it 'should execute the transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {'/machines': 1} describe "and handler didn't quit but all Dredd tests were OK", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) # TCP server echoing transactions back hookHandler = net.createServer (socket) -> socket.on 'data', (data) -> socket.write data socket.on 'error', (err) -> console.error err args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" "--server=#{COFFEE_BIN} ./test/fixtures/scripts/endless-ignore-term.coffee" '--server-wait=0' "--language=#{COFFEE_BIN} ./test/fixtures/scripts/endless-ignore-term.coffee" '--hookfiles=./test/fixtures/scripts/emptyfile' ] hookHandler.listen DEFAULT_HOOK_HANDLER_PORT, -> runDreddCommandWithServer(args, app, (err, info) -> hookHandler.close() runtimeInfo = info done(err) ) after (done) -> killAll('test/fixtures/scripts/', done) it 'should return with status 0', -> assert.equal runtimeInfo.dredd.exitStatus, 0 it 'should not return any killed or exited message', -> assert.notInclude runtimeInfo.dredd.stderr, 'killed' assert.notInclude runtimeInfo.dredd.stderr, 'exited' it 'should kill both the handler and the server', (done) -> isProcessRunning('endless-ignore-term', (err, isRunning) -> assert.isFalse isRunning unless err done(err) ) it 'should execute some transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {'/machines': 1} describe "when adding additional headers with -h", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-h' 'Accept:application/json' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should have an additional header in the request', -> assert.deepPropertyVal runtimeInfo.server.requests['/machines'][0], 'headers.accept', 'application/json' describe "when adding basic auth credentials with -u", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-u' 'username:password' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should have an authorization header in the request', -> assert.isOk runtimeInfo.server.requests['/machines'][0].headers.authorization it 'should contain a base64 encoded string of the username and password', -> assert.isOk runtimeInfo.server.requests['/machines'][0].headers.authorization is 'Basic ' + new Buffer('username:password').toString('base64') describe "when sorting requests with -s", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) args = [ './test/fixtures/apiary.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-s' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should perform the POST, GET, PUT, DELETE in order', -> assert.isOk runtimeInfo.dredd.stdout.indexOf('POST') < runtimeInfo.dredd.stdout.indexOf('GET') < runtimeInfo.dredd.stdout.indexOf('PUT') < runtimeInfo.dredd.stdout.indexOf('DELETE') describe 'when displaying errors inline with -e', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.status(201).json([{kind: 'bulldozer', imatriculation: 'willy'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-e' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should display errors inline', -> # when displayed inline, a single fail request only creates two "fail:" messages, # as opposed to the usual three count = runtimeInfo.dredd.stdout.split("fail").length - 2 #says fail in the epilogue assert.equal count, 2 describe 'when showing details for all requests with -d', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-d' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should display details on passing tests', -> # the request: block is not shown for passing tests normally assert.isOk runtimeInfo.dredd.stdout.indexOf('request') > -1 describe "when filtering request methods with -m", -> describe 'when blocking a request', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-m', 'POST' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should not send the request request', -> assert.deepEqual runtimeInfo.server.requestCounts, {} describe 'when not blocking a request', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-m', 'GET' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should allow the request to go through', -> assert.deepEqual runtimeInfo.server.requestCounts, {'/machines': 1} describe "when filtering transaction to particular name with -x or --only", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) app.get '/message', (req, res) -> res.type('text/plain').send "Hello World!\n" args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--path=./test/fixtures/multifile/*.apib' '--only=Message API > /message > GET' '--no-color' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should notify skipping to the stdout', -> assert.include runtimeInfo.dredd.stdout, 'skip: GET /machines' it 'should hit the only transaction', -> assert.deepEqual runtimeInfo.server.requestCounts, {'/message': 1} it 'exit status should be 0', -> assert.equal runtimeInfo.dredd.exitStatus, 0 describe 'when suppressing color with --no-color', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--no-color' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should print without colors', -> # if colors are not on, there is no closing color code between # the "pass" and the ":" assert.include runtimeInfo.dredd.stdout, 'pass:' describe 'when suppressing color with --color=false', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--color=false' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should print without colors', -> # if colors are not on, there is no closing color code between # the "pass" and the ":" assert.include runtimeInfo.dredd.stdout, 'pass:' describe 'when setting the log output level with -l', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-l=error' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should not display anything', -> # at the "error" level, complete should not be shown assert.isOk runtimeInfo.dredd.stdout.indexOf('complete') is -1 describe 'when showing timestamps with -t', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '-t' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should display timestamps', -> # look for the prefix for cli output with timestamps assert.notEqual runtimeInfo.dredd.stdout.indexOf('Z -'), -1 describe 'when loading hooks with --hookfiles', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--hookfiles=./test/fixtures/*_hooks.*' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should modify the transaction with hooks', -> assert.equal runtimeInfo.server.requests['/machines'][0].headers['header'], '123232323' describe 'when describing events in hookfiles', -> runtimeInfo = undefined containsLine = (str, expected) -> lines = str.split('\n') for line in lines if line.indexOf(expected) > -1 return true return false before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--hookfiles=./test/fixtures/*_events.*' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should execute the before and after events', -> assert.isOk containsLine(runtimeInfo.dredd.stdout, 'hooks.beforeAll'), (runtimeInfo.dredd.stdout) assert.isOk containsLine(runtimeInfo.dredd.stdout, 'hooks.afterAll'), (runtimeInfo.dredd.stdout) describe 'when describing both hooks and events in hookfiles', -> runtimeInfo = undefined getResults = (str) -> ret = [] lines = str.split('\n') for line in lines if line.indexOf('*** ') > -1 ret.push(line.substr(line.indexOf('*** ') + 4)) return ret.join(',') before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--hookfiles=./test/fixtures/*_all.*' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should execute hooks and events in order', -> events = getResults(runtimeInfo.dredd.stdout) assert.isOk events is 'beforeAll,before,after,afterAll' describe "tests an API description containing an endpoint with schema", -> describe "and server is responding in accordance with the schema", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/', (req, res) -> res.json( data: expires: 1234, token: 'PI:PASSWORD:<PASSWORD>END_PI' ) args = [ './test/fixtures/schema.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'exit status should be 0 (success)', -> assert.equal runtimeInfo.dredd.exitStatus, 0 describe "and server is NOT responding in accordance with the schema", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/', (req, res) -> res.json( data: expires: 'this should fail since it is a string', token: 'PI:PASSWORD:<PASSWORD>END_PI' ) args = [ './test/fixtures/schema.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'exit status should be 1 (failure)', -> assert.equal runtimeInfo.dredd.exitStatus, 1 describe "when API description document path is a glob", -> describe "and called with --names options", -> dreddCommandInfo = undefined before (done) -> args = [ './test/fixtures/multifile/*.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--names' ] runDreddCommand(args, (err, info) -> dreddCommandInfo = info done(err) ) it 'it should include all paths from all API description documents matching the glob', -> assert.include dreddCommandInfo.stdout, '> /greeting > GET' assert.include dreddCommandInfo.stdout, '> /message > GET' assert.include dreddCommandInfo.stdout, '> /name > GET' it 'should exit with status 0', -> assert.equal dreddCommandInfo.exitStatus, 0 describe 'and called with hooks', -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/name', (req, res) -> res.type('text/plain').send "PI:NAME:<NAME>END_PI\n" app.get '/greeting', (req, res) -> res.type('text/plain').send "Howdy!\n" app.get '/message', (req, res) -> res.type('text/plain').send "Hello World!\n" args = [ './test/fixtures/multifile/*.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--hookfiles=./test/fixtures/multifile/multifile_hooks.coffee' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should eval the hook for each transaction', -> assert.include runtimeInfo.dredd.stdout, 'after name' assert.include runtimeInfo.dredd.stdout, 'after greeting' assert.include runtimeInfo.dredd.stdout, 'after message' it 'should exit with status 0', -> assert.equal runtimeInfo.dredd.exitStatus, 0, (runtimeInfo.dredd.output) it 'server should receive 3 requests', -> assert.deepEqual runtimeInfo.server.requestCounts, '/name': 1 '/greeting': 1 '/message': 1 describe "when called with additional --path argument which is a glob", -> describe "and called with --names options", -> dreddCommandInfo = undefined before (done) -> args = [ './test/fixtures/multiple-examples.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--path=./test/fixtures/multifile/*.apib' '--names' ] runDreddCommand(args, (err, info) -> dreddCommandInfo = info done(err) ) it 'it should include all paths from all API description documents matching all paths and globs', -> assert.include dreddCommandInfo.stdout, 'Greeting API > /greeting > GET' assert.include dreddCommandInfo.stdout, 'Message API > /message > GET' assert.include dreddCommandInfo.stdout, 'Name API > /name > GET' assert.include dreddCommandInfo.stdout, 'Machines API > Machines > Machines collection > Get Machines > Example 1' assert.include dreddCommandInfo.stdout, 'Machines API > Machines > Machines collection > Get Machines > Example 2' it 'should exit with status 0', -> assert.equal dreddCommandInfo.exitStatus, 0 describe "Using sandboxed hooks", -> runtimeInfo = undefined before (done) -> app = createServer() app.get '/machines', (req, res) -> res.json([{type: 'bulldozer', name: 'PI:NAME:<NAME>END_PI'}]) args = [ './test/fixtures/single-get.apib' "http://127.0.0.1:#{DEFAULT_SERVER_PORT}" '--sandbox' '--hookfiles=./test/fixtures/sandboxed-hook.js' ] runDreddCommandWithServer(args, app, (err, info) -> runtimeInfo = info done(err) ) it 'should hit the resource', -> assert.deepEqual runtimeInfo.server.requestCounts, {'/machines': 1} it 'exit status should be 1', -> assert.equal runtimeInfo.dredd.exitStatus, 1 it 'stdout shoud contain fail message', -> assert.include runtimeInfo.dredd.stdout, 'failed in sandboxed hook' it 'stdout shoud contain sandbox messagae', -> assert.include runtimeInfo.dredd.stdout, 'Loading hook files in sandboxed context'
[ { "context": "n: (len = 100) ->\n key = ''\n str = '1234567890abcdefghijlmnopqrstuyxzw'.split ''\n\n while key.length < len\n ", "end": 164, "score": 0.9745668768882751, "start": 130, "tag": "KEY", "value": "1234567890abcdefghijlmnopqrstuyxzw" } ]
lib/uniqid.coffee
cranic/node-flatdb
2
crypto = require 'crypto' class uniqid constructor: (@salt = '') -> gen: (len = 100) -> key = '' str = '1234567890abcdefghijlmnopqrstuyxzw'.split '' while key.length < len rnd = Math.floor Math.random() * str.length key = key + str[rnd] crypto.createHash('sha1').update(@salt + key + new Date().getTime()).digest 'hex' module.exports = uniqid
145966
crypto = require 'crypto' class uniqid constructor: (@salt = '') -> gen: (len = 100) -> key = '' str = '<KEY>'.split '' while key.length < len rnd = Math.floor Math.random() * str.length key = key + str[rnd] crypto.createHash('sha1').update(@salt + key + new Date().getTime()).digest 'hex' module.exports = uniqid
true
crypto = require 'crypto' class uniqid constructor: (@salt = '') -> gen: (len = 100) -> key = '' str = 'PI:KEY:<KEY>END_PI'.split '' while key.length < len rnd = Math.floor Math.random() * str.length key = key + str[rnd] crypto.createHash('sha1').update(@salt + key + new Date().getTime()).digest 'hex' module.exports = uniqid
[ { "context": " [@_account().me()]\n to: [new Contact(name: \"Nylas Team\", email: \"n1-support@nylas.com\")]\n date: (ne", "end": 3462, "score": 0.9995529055595398, "start": 3452, "tag": "NAME", "value": "Nylas Team" }, { "context": " to: [new Contact(name: \"Nylas Team...
app/internal_packages/message-list/lib/message-controls.cjsx
immershy/nodemail
0
React = require 'react' # {remote} = require 'electron' {Actions, NylasAPI, AccountStore} = require 'nylas-exports' {RetinaImg, ButtonDropdown, Menu} = require 'nylas-component-kit' class MessageControls extends React.Component @displayName: "MessageControls" @propTypes: thread: React.PropTypes.object.isRequired message: React.PropTypes.object.isRequired constructor: (@props) -> render: => items = @_items() <div className="message-actions-wrap"> <ButtonDropdown primaryItem={<RetinaImg name={items[0].image} mode={RetinaImg.Mode.ContentIsMask}/>} primaryTitle={items[0].name} primaryClick={items[0].select} closeOnMenuClick={true} menu={@_dropdownMenu(items[1..-1])}/> <div className="message-actions-ellipsis" onClick={@_onShowActionsMenu}> <RetinaImg name={"message-actions-ellipsis.png"} mode={RetinaImg.Mode.ContentIsMask}/> </div> </div> _items: -> reply = name: 'Reply', image: 'ic-dropdown-reply.png' select: @_onReply replyAll = name: 'Reply All', image: 'ic-dropdown-replyall.png' select: @_onReplyAll forward = name: 'Forward', image: 'ic-dropdown-forward.png' select: @_onForward if @props.message.canReplyAll() defaultReplyType = NylasEnv.config.get('core.sending.defaultReplyType') if defaultReplyType is 'reply-all' return [replyAll, reply, forward] else return [reply, replyAll, forward] else return [reply, forward] _account: => AccountStore.accountForId(@props.message.accountId) _dropdownMenu: (items) -> itemContent = (item) -> <span> <RetinaImg name={item.image} mode={RetinaImg.Mode.ContentIsMask}/> &nbsp;&nbsp;{item.name} </span> <Menu items={items} itemKey={ (item) -> item.name } itemContent={itemContent} onSelect={ (item) => item.select() } /> _onReply: => {thread, message} = @props Actions.composeReply({thread, message, type: 'reply', behavior: 'prefer-existing-if-pristine'}) _onReplyAll: => {thread, message} = @props Actions.composeReply({thread, message, type: 'reply-all', behavior: 'prefer-existing-if-pristine'}) _onForward: => Actions.composeForward(thread: @props.thread, message: @props.message) _onShowActionsMenu: => #SystemMenu = remote.require('menu') #SystemMenuItem = remote.require('menu-item') # Todo: refactor this so that message actions are provided # dynamically. Waiting to see if this will be used often. #menu = new SystemMenu() #menu.append(new SystemMenuItem({ label: 'Log Data', click: => @_onLogData()})) #menu.append(new SystemMenuItem({ label: 'Show Original', click: => @_onShowOriginal()})) #menu.append(new SystemMenuItem({ label: 'Copy Debug Info to Clipboard', click: => @_onCopyToClipboard()})) ##menu.append(new SystemMenuItem({ type: 'separator'})) #menu.append(new SystemMenuItem({ label: 'Report Issue: Quoted Text', click: => @_onReport('Quoted Text')})) #menu.append(new SystemMenuItem({ label: 'Report Issue: Rendering', click: => @_onReport('Rendering')})) #menu.popup(remote.getCurrentWindow()) _onReport: (issueType) => {Contact, Message, DatabaseStore, AccountStore} = require 'nylas-exports' draft = new Message from: [@_account().me()] to: [new Contact(name: "Nylas Team", email: "n1-support@nylas.com")] date: (new Date) draft: true subject: "Feedback - Message Display Issue (#{issueType})" accountId: @_account().id body: @props.message.body DatabaseStore.inTransaction (t) => t.persistModel(draft) .then => Actions.sendDraft(draft.clientId) dialog = remote.require('dialog') dialog.showMessageBox remote.getCurrentWindow(), { type: 'warning' buttons: ['OK'], message: "Thank you." detail: "The contents of this message have been sent to the N1 team and will be added to a test suite." } _onShowOriginal: => fs = require 'fs' path = require 'path' BrowserWindow = remote.require('browser-window') app = remote.require('app') tmpfile = path.join(app.getPath('temp'), @props.message.id) NylasAPI.makeRequest headers: Accept: 'message/rfc822' path: "/messages/#{@props.message.id}" accountId: @props.message.accountId json:false success: (body) => fs.writeFile tmpfile, body, => window = new BrowserWindow(width: 800, height: 600, title: "#{@props.message.subject} - RFC822") window.loadURL('file://'+tmpfile) _onLogData: => console.log @props.message window.__message = @props.message window.__thread = @props.thread console.log "Also now available in window.__message and window.__thread" _onCopyToClipboard: => clipboard = require('electron').clipboard data = "AccountID: #{@props.message.accountId}\n"+ "Message ID: #{@props.message.serverId}\n"+ "Message Metadata: #{JSON.stringify(@props.message.pluginMetadata, null, ' ')}\n"+ "Thread ID: #{@props.thread.serverId}\n"+ "Thread Metadata: #{JSON.stringify(@props.thread.pluginMetadata, null, ' ')}\n" clipboard.writeText(data) module.exports = MessageControls
973
React = require 'react' # {remote} = require 'electron' {Actions, NylasAPI, AccountStore} = require 'nylas-exports' {RetinaImg, ButtonDropdown, Menu} = require 'nylas-component-kit' class MessageControls extends React.Component @displayName: "MessageControls" @propTypes: thread: React.PropTypes.object.isRequired message: React.PropTypes.object.isRequired constructor: (@props) -> render: => items = @_items() <div className="message-actions-wrap"> <ButtonDropdown primaryItem={<RetinaImg name={items[0].image} mode={RetinaImg.Mode.ContentIsMask}/>} primaryTitle={items[0].name} primaryClick={items[0].select} closeOnMenuClick={true} menu={@_dropdownMenu(items[1..-1])}/> <div className="message-actions-ellipsis" onClick={@_onShowActionsMenu}> <RetinaImg name={"message-actions-ellipsis.png"} mode={RetinaImg.Mode.ContentIsMask}/> </div> </div> _items: -> reply = name: 'Reply', image: 'ic-dropdown-reply.png' select: @_onReply replyAll = name: 'Reply All', image: 'ic-dropdown-replyall.png' select: @_onReplyAll forward = name: 'Forward', image: 'ic-dropdown-forward.png' select: @_onForward if @props.message.canReplyAll() defaultReplyType = NylasEnv.config.get('core.sending.defaultReplyType') if defaultReplyType is 'reply-all' return [replyAll, reply, forward] else return [reply, replyAll, forward] else return [reply, forward] _account: => AccountStore.accountForId(@props.message.accountId) _dropdownMenu: (items) -> itemContent = (item) -> <span> <RetinaImg name={item.image} mode={RetinaImg.Mode.ContentIsMask}/> &nbsp;&nbsp;{item.name} </span> <Menu items={items} itemKey={ (item) -> item.name } itemContent={itemContent} onSelect={ (item) => item.select() } /> _onReply: => {thread, message} = @props Actions.composeReply({thread, message, type: 'reply', behavior: 'prefer-existing-if-pristine'}) _onReplyAll: => {thread, message} = @props Actions.composeReply({thread, message, type: 'reply-all', behavior: 'prefer-existing-if-pristine'}) _onForward: => Actions.composeForward(thread: @props.thread, message: @props.message) _onShowActionsMenu: => #SystemMenu = remote.require('menu') #SystemMenuItem = remote.require('menu-item') # Todo: refactor this so that message actions are provided # dynamically. Waiting to see if this will be used often. #menu = new SystemMenu() #menu.append(new SystemMenuItem({ label: 'Log Data', click: => @_onLogData()})) #menu.append(new SystemMenuItem({ label: 'Show Original', click: => @_onShowOriginal()})) #menu.append(new SystemMenuItem({ label: 'Copy Debug Info to Clipboard', click: => @_onCopyToClipboard()})) ##menu.append(new SystemMenuItem({ type: 'separator'})) #menu.append(new SystemMenuItem({ label: 'Report Issue: Quoted Text', click: => @_onReport('Quoted Text')})) #menu.append(new SystemMenuItem({ label: 'Report Issue: Rendering', click: => @_onReport('Rendering')})) #menu.popup(remote.getCurrentWindow()) _onReport: (issueType) => {Contact, Message, DatabaseStore, AccountStore} = require 'nylas-exports' draft = new Message from: [@_account().me()] to: [new Contact(name: "<NAME>", email: "<EMAIL>")] date: (new Date) draft: true subject: "Feedback - Message Display Issue (#{issueType})" accountId: @_account().id body: @props.message.body DatabaseStore.inTransaction (t) => t.persistModel(draft) .then => Actions.sendDraft(draft.clientId) dialog = remote.require('dialog') dialog.showMessageBox remote.getCurrentWindow(), { type: 'warning' buttons: ['OK'], message: "Thank you." detail: "The contents of this message have been sent to the N1 team and will be added to a test suite." } _onShowOriginal: => fs = require 'fs' path = require 'path' BrowserWindow = remote.require('browser-window') app = remote.require('app') tmpfile = path.join(app.getPath('temp'), @props.message.id) NylasAPI.makeRequest headers: Accept: 'message/rfc822' path: "/messages/#{@props.message.id}" accountId: @props.message.accountId json:false success: (body) => fs.writeFile tmpfile, body, => window = new BrowserWindow(width: 800, height: 600, title: "#{@props.message.subject} - RFC822") window.loadURL('file://'+tmpfile) _onLogData: => console.log @props.message window.__message = @props.message window.__thread = @props.thread console.log "Also now available in window.__message and window.__thread" _onCopyToClipboard: => clipboard = require('electron').clipboard data = "AccountID: #{@props.message.accountId}\n"+ "Message ID: #{@props.message.serverId}\n"+ "Message Metadata: #{JSON.stringify(@props.message.pluginMetadata, null, ' ')}\n"+ "Thread ID: #{@props.thread.serverId}\n"+ "Thread Metadata: #{JSON.stringify(@props.thread.pluginMetadata, null, ' ')}\n" clipboard.writeText(data) module.exports = MessageControls
true
React = require 'react' # {remote} = require 'electron' {Actions, NylasAPI, AccountStore} = require 'nylas-exports' {RetinaImg, ButtonDropdown, Menu} = require 'nylas-component-kit' class MessageControls extends React.Component @displayName: "MessageControls" @propTypes: thread: React.PropTypes.object.isRequired message: React.PropTypes.object.isRequired constructor: (@props) -> render: => items = @_items() <div className="message-actions-wrap"> <ButtonDropdown primaryItem={<RetinaImg name={items[0].image} mode={RetinaImg.Mode.ContentIsMask}/>} primaryTitle={items[0].name} primaryClick={items[0].select} closeOnMenuClick={true} menu={@_dropdownMenu(items[1..-1])}/> <div className="message-actions-ellipsis" onClick={@_onShowActionsMenu}> <RetinaImg name={"message-actions-ellipsis.png"} mode={RetinaImg.Mode.ContentIsMask}/> </div> </div> _items: -> reply = name: 'Reply', image: 'ic-dropdown-reply.png' select: @_onReply replyAll = name: 'Reply All', image: 'ic-dropdown-replyall.png' select: @_onReplyAll forward = name: 'Forward', image: 'ic-dropdown-forward.png' select: @_onForward if @props.message.canReplyAll() defaultReplyType = NylasEnv.config.get('core.sending.defaultReplyType') if defaultReplyType is 'reply-all' return [replyAll, reply, forward] else return [reply, replyAll, forward] else return [reply, forward] _account: => AccountStore.accountForId(@props.message.accountId) _dropdownMenu: (items) -> itemContent = (item) -> <span> <RetinaImg name={item.image} mode={RetinaImg.Mode.ContentIsMask}/> &nbsp;&nbsp;{item.name} </span> <Menu items={items} itemKey={ (item) -> item.name } itemContent={itemContent} onSelect={ (item) => item.select() } /> _onReply: => {thread, message} = @props Actions.composeReply({thread, message, type: 'reply', behavior: 'prefer-existing-if-pristine'}) _onReplyAll: => {thread, message} = @props Actions.composeReply({thread, message, type: 'reply-all', behavior: 'prefer-existing-if-pristine'}) _onForward: => Actions.composeForward(thread: @props.thread, message: @props.message) _onShowActionsMenu: => #SystemMenu = remote.require('menu') #SystemMenuItem = remote.require('menu-item') # Todo: refactor this so that message actions are provided # dynamically. Waiting to see if this will be used often. #menu = new SystemMenu() #menu.append(new SystemMenuItem({ label: 'Log Data', click: => @_onLogData()})) #menu.append(new SystemMenuItem({ label: 'Show Original', click: => @_onShowOriginal()})) #menu.append(new SystemMenuItem({ label: 'Copy Debug Info to Clipboard', click: => @_onCopyToClipboard()})) ##menu.append(new SystemMenuItem({ type: 'separator'})) #menu.append(new SystemMenuItem({ label: 'Report Issue: Quoted Text', click: => @_onReport('Quoted Text')})) #menu.append(new SystemMenuItem({ label: 'Report Issue: Rendering', click: => @_onReport('Rendering')})) #menu.popup(remote.getCurrentWindow()) _onReport: (issueType) => {Contact, Message, DatabaseStore, AccountStore} = require 'nylas-exports' draft = new Message from: [@_account().me()] to: [new Contact(name: "PI:NAME:<NAME>END_PI", email: "PI:EMAIL:<EMAIL>END_PI")] date: (new Date) draft: true subject: "Feedback - Message Display Issue (#{issueType})" accountId: @_account().id body: @props.message.body DatabaseStore.inTransaction (t) => t.persistModel(draft) .then => Actions.sendDraft(draft.clientId) dialog = remote.require('dialog') dialog.showMessageBox remote.getCurrentWindow(), { type: 'warning' buttons: ['OK'], message: "Thank you." detail: "The contents of this message have been sent to the N1 team and will be added to a test suite." } _onShowOriginal: => fs = require 'fs' path = require 'path' BrowserWindow = remote.require('browser-window') app = remote.require('app') tmpfile = path.join(app.getPath('temp'), @props.message.id) NylasAPI.makeRequest headers: Accept: 'message/rfc822' path: "/messages/#{@props.message.id}" accountId: @props.message.accountId json:false success: (body) => fs.writeFile tmpfile, body, => window = new BrowserWindow(width: 800, height: 600, title: "#{@props.message.subject} - RFC822") window.loadURL('file://'+tmpfile) _onLogData: => console.log @props.message window.__message = @props.message window.__thread = @props.thread console.log "Also now available in window.__message and window.__thread" _onCopyToClipboard: => clipboard = require('electron').clipboard data = "AccountID: #{@props.message.accountId}\n"+ "Message ID: #{@props.message.serverId}\n"+ "Message Metadata: #{JSON.stringify(@props.message.pluginMetadata, null, ' ')}\n"+ "Thread ID: #{@props.thread.serverId}\n"+ "Thread Metadata: #{JSON.stringify(@props.thread.pluginMetadata, null, ' ')}\n" clipboard.writeText(data) module.exports = MessageControls
[ { "context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje", "end": 22, "score": 0.9584249258041382, "start": 16, "tag": "NAME", "value": "Konode" } ]
src/term.coffee
LogicalOutcomes/KoNote
1
# Copyright (c) Konode. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # Post-processes terms identified Config.terminology # Require into pages as Terms = require('./terms') # Refrain from using this module in internal error/crashHandler messages Config = require './config' Pluralize = require 'pluralize' _ = require 'underscore' # Utility functions capitalize = (word) -> word.replace /(?:^|\s)\S/g, (a) -> a.toUpperCase() pluralizeLastWord = (string) -> # Split string into words, pluralize last word, join back together stringWords = string.split " " lastWordIndex = stringWords.length - 1 stringWords[lastWordIndex] = Pluralize stringWords[lastWordIndex] return stringWords.join " " # Generate variations of capitalized and pluralized terms generatedTerms = {} _.each Config.terminology, (value, key) -> capKey = capitalize key.toString() capValue = capitalize value generatedTerms[key] = value generatedTerms[capKey] = capValue generatedTerms[pluralizeLastWord(key)] = pluralizeLastWord(value) generatedTerms[pluralizeLastWord(capKey)] = pluralizeLastWord(capValue) module.exports = (term) -> # TODO: Logic to switch out "a", "an", etc if generatedTerms[term] return generatedTerms[term] else throw new Error "'#{term}'' does not exist in Terms(), or is not a valid plural of the root word."
155588
# Copyright (c) <NAME>. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # Post-processes terms identified Config.terminology # Require into pages as Terms = require('./terms') # Refrain from using this module in internal error/crashHandler messages Config = require './config' Pluralize = require 'pluralize' _ = require 'underscore' # Utility functions capitalize = (word) -> word.replace /(?:^|\s)\S/g, (a) -> a.toUpperCase() pluralizeLastWord = (string) -> # Split string into words, pluralize last word, join back together stringWords = string.split " " lastWordIndex = stringWords.length - 1 stringWords[lastWordIndex] = Pluralize stringWords[lastWordIndex] return stringWords.join " " # Generate variations of capitalized and pluralized terms generatedTerms = {} _.each Config.terminology, (value, key) -> capKey = capitalize key.toString() capValue = capitalize value generatedTerms[key] = value generatedTerms[capKey] = capValue generatedTerms[pluralizeLastWord(key)] = pluralizeLastWord(value) generatedTerms[pluralizeLastWord(capKey)] = pluralizeLastWord(capValue) module.exports = (term) -> # TODO: Logic to switch out "a", "an", etc if generatedTerms[term] return generatedTerms[term] else throw new Error "'#{term}'' does not exist in Terms(), or is not a valid plural of the root word."
true
# Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # Post-processes terms identified Config.terminology # Require into pages as Terms = require('./terms') # Refrain from using this module in internal error/crashHandler messages Config = require './config' Pluralize = require 'pluralize' _ = require 'underscore' # Utility functions capitalize = (word) -> word.replace /(?:^|\s)\S/g, (a) -> a.toUpperCase() pluralizeLastWord = (string) -> # Split string into words, pluralize last word, join back together stringWords = string.split " " lastWordIndex = stringWords.length - 1 stringWords[lastWordIndex] = Pluralize stringWords[lastWordIndex] return stringWords.join " " # Generate variations of capitalized and pluralized terms generatedTerms = {} _.each Config.terminology, (value, key) -> capKey = capitalize key.toString() capValue = capitalize value generatedTerms[key] = value generatedTerms[capKey] = capValue generatedTerms[pluralizeLastWord(key)] = pluralizeLastWord(value) generatedTerms[pluralizeLastWord(capKey)] = pluralizeLastWord(capValue) module.exports = (term) -> # TODO: Logic to switch out "a", "an", etc if generatedTerms[term] return generatedTerms[term] else throw new Error "'#{term}'' does not exist in Terms(), or is not a valid plural of the root word."
[ { "context": "l\": \"Test Account\",\n \"mailbox-login\": \"test@cozytest.org\",\n \"mailbox-name\": \"Test\",\n ", "end": 2270, "score": 0.9999229311943054, "start": 2253, "tag": "EMAIL", "value": "test@cozytest.org" }, { "context": "x-name\": \"Test\...
client/tests/casper/full/accounts.coffee
gelnior/cozy-emails
58
if global? require = patchRequire global.require else require = patchRequire this.require require.globals.casper = casper init = require(fs.workingDirectory + "/client/tests/casper/common").init utils = require "utils.js" deleteTestAccounts = -> casper.evaluate -> AccountStore = require 'stores/account_store' account = AccountStore.getByLabel 'Test Account' if account? AccountActionCreator = require 'actions/account_action_creator' console.log "Deleting test account #{account.get 'id'}" AccountActionCreator.remove(account.get 'id') else console.log "No test account to delete" casper.test.begin 'Test accounts', (test) -> init casper casper.start casper.cozy.startUrl, -> casper.waitForSelector "aside[role=menubar][aria-expanded=true]" casper.then -> accountSel = ".mainmenu .account" accounts = casper.getElementsInfo accountSel casper.eachThen accounts, (response) -> account = response.data id = account.attributes['data-reactid'] if not casper.exists ".active[data-reactid='#{id}']" casper.click "[data-reactid='#{id}']" casper.waitForSelector ".active[data-reactid='#{id}']", -> label = casper.getElementInfo "[data-reactid='#{id}'] .item-label" test.pass "Account #{label.text} selected" if casper.exists ".messages-list .message" casper.click ".messages-list .message a .subject" casper.waitUntilVisible ".conversation" , -> test.fail "Unable to select account #{account.text} #{id}" casper.run -> test.done() casper.test.begin 'Create account', (test) -> init casper casper.start casper.cozy.startUrl, -> casper.waitForSelector "aside[role=menubar][aria-expanded=true]" casper.then -> values = "mailbox-accountType": "IMAP", "mailbox-imapPort": "993", "mailbox-imapSSL": true, "mailbox-imapServer": "toto", "mailbox-imapTLS": false, "mailbox-label": "Test Account", "mailbox-login": "test@cozytest.org", "mailbox-name": "Test", "mailbox-password": "toto", "mailbox-smtpPort": "465", "mailbox-smtpSSL": true, "mailbox-smtpServer": "toto", "mailbox-smtpTLS": false deleteTestAccounts() account = casper.evaluate -> AccountStore = require 'stores/account_store' account = AccountStore.getByLabel 'Test Account' return account? test.assertFalsy account, "Test account doesnt exists" casper.click '.new-account-action' casper.waitForSelector '#mailbox-config', -> test.assertSelectorHasText "#mailbox-config h3", "New account" test.assertDoesntExist "#mailbox-config .nav-tabs", "No tabs" test.assertSelectorHasText "#mailbox-config button.action-save", "Add", "Add button" test.assertDoesntExist ".toast-error", "No error message" casper.click "#mailbox-config button.action-save" casper.waitForSelector ".toast-error", -> test.pass "Error message displayed" test.assertElementCount ".form-group.has-error", 9, "Errors are underlined" casper.fillSelectors 'form', '#mailbox-label': values['mailbox-label'] casper.click "#mailbox-config button.action-save" casper.wait 100, -> test.assertElementCount ".form-group.has-error", 8, "Errors are underlined" casper.fillSelectors 'form', '#mailbox-name': values['mailbox-name'] '#mailbox-login': values['mailbox-login'] '#mailbox-password': values['mailbox-password'] '#mailbox-smtpServer': values['mailbox-smtpServer'] '#mailbox-imapServer': values['mailbox-imapServer'] '#maibox-accountType': values['account-type'] casper.click "#mailbox-config button.action-save" casper.waitForSelector '.form-account.waiting', -> casper.waitWhileSelector '.form-account.waiting', -> test.assertSelectorHasText "#mailbox-config button.action-save", "Add", "Wrong SMTP Server" test.assertEquals casper.getFormValues('form'), values, "Form not changed" test.assertDoesntExist ".has-error #mailbox-label", "No error on label" test.assertExist ".has-error #mailbox-smtpServer", "Error on SMTP" casper.fillSelectors 'form', '#mailbox-accountType': 'TEST' '#mailbox-smtpServer': 'ssl0.ovh.net' '#mailbox-imapServer': values['mailbox-imapServer'] casper.wait 500, -> casper.click "#mailbox-config button.action-save" casper.waitForSelector "#mailbox-config .nav-tabs", -> test.pass 'No more errors ☺' casper.then -> test.comment "Creating mailbox" name = "Box 1" test.assertSelectorHasText "#mailbox-config .nav-tabs .active", "Folders", "Folders tab is active" test.assertDoesntExist ".form-group.draftMailbox .dropdown", "No draft folder" test.assertDoesntExist ".form-group.sentMailbox .dropdown", "No sent folder" test.assertDoesntExist ".form-group.trashMailbox .dropdown", "No trash folder" test.assertElementCount "ul.boxes > li.box-item", 0, "No boxes" casper.fillSelectors 'form', '#newmailbox': name casper.click '.box-action.add i' casper.waitForSelector '.box-item', -> test.assertSelectorHasText ".box .box-label", name, "Box created" test.assertExist ".form-group.draftMailbox .dropdown", "Draft folder", "Draft dropdown" test.assertSelectorHasText ".form-group.draftMailbox .dropdown-menu", name, "Box in draft dropdown" test.assertExist ".form-group.sentMailbox .dropdown", "Sent folder", "Sent dropdown" test.assertSelectorHasText ".form-group.sentMailbox .dropdown-menu", name, "Box in sent dropdown" test.assertExist ".form-group.trashMailbox .dropdown", "Trash folder", "Trash dropdown" test.assertSelectorHasText ".form-group.trashMailbox .dropdown-menu", name, "Box in trash dropdown" casper.then -> test.comment "Rename mailbox" name = "Box 2" casper.click ".box .box-action.edit i" casper.waitForSelector ".box .box-action.save", -> casper.fillSelectors 'form', '.box .box-label': name casper.click ".box .box-action.save i" casper.waitForSelector ".box span.box-label", -> test.assertSelectorDoesntHaveText ".box .box-label", "Box 1", "Box renamed" test.assertSelectorHasText ".box .box-label", name, "Box renamed" test.assertExist ".form-group.draftMailbox .dropdown", "Draft folder", "Draft dropdown" test.assertSelectorHasText ".form-group.draftMailbox .dropdown-menu", name, "Box in draft dropdown" test.assertExist ".form-group.sentMailbox .dropdown", "Sent folder", "Sent dropdown" test.assertSelectorHasText ".form-group.sentMailbox .dropdown-menu", name, "Box in sent dropdown" test.assertExist ".form-group.trashMailbox .dropdown", "Trash folder", "Trash dropdown" test.assertSelectorHasText ".form-group.trashMailbox .dropdown-menu", name, "Box in trash dropdown" casper.then -> test.comment "Delete mailbox" casper.click ".box .box-action.delete i" casper.waitUntilVisible '.modal-dialog', -> confirm = casper.fetchText('.modal-body').trim() test.assertEquals confirm, "Do you really want to delete all messages in this box?", "Confirmation dialog" casper.click ".modal-dialog .btn:not(.btn-cozy-non-default)" casper.waitWhileSelector "ul.boxes .box span.box-label", -> test.assertDoesntExist ".form-group.draftMailbox .dropdown", "No draft folder" test.assertDoesntExist ".form-group.sentMailbox .dropdown", "No sent folder" test.assertDoesntExist ".form-group.trashMailbox .dropdown", "No trash folder" test.assertElementCount "ul.boxes > li.box-item", 0, "No boxes" casper.then -> test.pass "ok" casper.run -> test.done() casper.test.begin 'Test accounts', (test) -> init casper casper.start casper.cozy.startUrl, -> casper.waitForSelector "aside[role=menubar][aria-expanded=true]" casper.then -> accountSel = ".mainmenu .account" accounts = casper.getElementsInfo accountSel id = accounts[0].attributes['data-reactid'] if not casper.exists ".active[data-reactid='#{id}']" casper.click "[data-reactid='#{id}']" casper.waitForSelector ".active[data-reactid='#{id}']", -> casper.click '.mainmenu .active .mailbox-config' casper.waitForSelector '#mailbox-config', -> test.assertSelectorHasText "#mailbox-config h3", "Edit account" test.assertSelectorHasText "#mailbox-config .nav-tabs .active", "Account", "Account tab is active" test.assertSelectorHasText "#mailbox-config .nav-tabs", "Folders", "Folder tab visible" casper.run -> deleteTestAccounts() test.done()
57306
if global? require = patchRequire global.require else require = patchRequire this.require require.globals.casper = casper init = require(fs.workingDirectory + "/client/tests/casper/common").init utils = require "utils.js" deleteTestAccounts = -> casper.evaluate -> AccountStore = require 'stores/account_store' account = AccountStore.getByLabel 'Test Account' if account? AccountActionCreator = require 'actions/account_action_creator' console.log "Deleting test account #{account.get 'id'}" AccountActionCreator.remove(account.get 'id') else console.log "No test account to delete" casper.test.begin 'Test accounts', (test) -> init casper casper.start casper.cozy.startUrl, -> casper.waitForSelector "aside[role=menubar][aria-expanded=true]" casper.then -> accountSel = ".mainmenu .account" accounts = casper.getElementsInfo accountSel casper.eachThen accounts, (response) -> account = response.data id = account.attributes['data-reactid'] if not casper.exists ".active[data-reactid='#{id}']" casper.click "[data-reactid='#{id}']" casper.waitForSelector ".active[data-reactid='#{id}']", -> label = casper.getElementInfo "[data-reactid='#{id}'] .item-label" test.pass "Account #{label.text} selected" if casper.exists ".messages-list .message" casper.click ".messages-list .message a .subject" casper.waitUntilVisible ".conversation" , -> test.fail "Unable to select account #{account.text} #{id}" casper.run -> test.done() casper.test.begin 'Create account', (test) -> init casper casper.start casper.cozy.startUrl, -> casper.waitForSelector "aside[role=menubar][aria-expanded=true]" casper.then -> values = "mailbox-accountType": "IMAP", "mailbox-imapPort": "993", "mailbox-imapSSL": true, "mailbox-imapServer": "toto", "mailbox-imapTLS": false, "mailbox-label": "Test Account", "mailbox-login": "<EMAIL>", "mailbox-name": "Test", "mailbox-password": "<PASSWORD>", "mailbox-smtpPort": "465", "mailbox-smtpSSL": true, "mailbox-smtpServer": "toto", "mailbox-smtpTLS": false deleteTestAccounts() account = casper.evaluate -> AccountStore = require 'stores/account_store' account = AccountStore.getByLabel 'Test Account' return account? test.assertFalsy account, "Test account doesnt exists" casper.click '.new-account-action' casper.waitForSelector '#mailbox-config', -> test.assertSelectorHasText "#mailbox-config h3", "New account" test.assertDoesntExist "#mailbox-config .nav-tabs", "No tabs" test.assertSelectorHasText "#mailbox-config button.action-save", "Add", "Add button" test.assertDoesntExist ".toast-error", "No error message" casper.click "#mailbox-config button.action-save" casper.waitForSelector ".toast-error", -> test.pass "Error message displayed" test.assertElementCount ".form-group.has-error", 9, "Errors are underlined" casper.fillSelectors 'form', '#mailbox-label': values['mailbox-label'] casper.click "#mailbox-config button.action-save" casper.wait 100, -> test.assertElementCount ".form-group.has-error", 8, "Errors are underlined" casper.fillSelectors 'form', '#mailbox-name': values['mailbox-name'] '#mailbox-login': values['mailbox-login'] '#mailbox-password': values['<PASSWORD>'] '#mailbox-smtpServer': values['mailbox-smtpServer'] '#mailbox-imapServer': values['mailbox-imapServer'] '#maibox-accountType': values['account-type'] casper.click "#mailbox-config button.action-save" casper.waitForSelector '.form-account.waiting', -> casper.waitWhileSelector '.form-account.waiting', -> test.assertSelectorHasText "#mailbox-config button.action-save", "Add", "Wrong SMTP Server" test.assertEquals casper.getFormValues('form'), values, "Form not changed" test.assertDoesntExist ".has-error #mailbox-label", "No error on label" test.assertExist ".has-error #mailbox-smtpServer", "Error on SMTP" casper.fillSelectors 'form', '#mailbox-accountType': 'TEST' '#mailbox-smtpServer': 'ssl0.ovh.net' '#mailbox-imapServer': values['mailbox-imapServer'] casper.wait 500, -> casper.click "#mailbox-config button.action-save" casper.waitForSelector "#mailbox-config .nav-tabs", -> test.pass 'No more errors ☺' casper.then -> test.comment "Creating mailbox" name = "Box 1" test.assertSelectorHasText "#mailbox-config .nav-tabs .active", "Folders", "Folders tab is active" test.assertDoesntExist ".form-group.draftMailbox .dropdown", "No draft folder" test.assertDoesntExist ".form-group.sentMailbox .dropdown", "No sent folder" test.assertDoesntExist ".form-group.trashMailbox .dropdown", "No trash folder" test.assertElementCount "ul.boxes > li.box-item", 0, "No boxes" casper.fillSelectors 'form', '#newmailbox': name casper.click '.box-action.add i' casper.waitForSelector '.box-item', -> test.assertSelectorHasText ".box .box-label", name, "Box created" test.assertExist ".form-group.draftMailbox .dropdown", "Draft folder", "Draft dropdown" test.assertSelectorHasText ".form-group.draftMailbox .dropdown-menu", name, "Box in draft dropdown" test.assertExist ".form-group.sentMailbox .dropdown", "Sent folder", "Sent dropdown" test.assertSelectorHasText ".form-group.sentMailbox .dropdown-menu", name, "Box in sent dropdown" test.assertExist ".form-group.trashMailbox .dropdown", "Trash folder", "Trash dropdown" test.assertSelectorHasText ".form-group.trashMailbox .dropdown-menu", name, "Box in trash dropdown" casper.then -> test.comment "Rename mailbox" name = "Box 2" casper.click ".box .box-action.edit i" casper.waitForSelector ".box .box-action.save", -> casper.fillSelectors 'form', '.box .box-label': name casper.click ".box .box-action.save i" casper.waitForSelector ".box span.box-label", -> test.assertSelectorDoesntHaveText ".box .box-label", "Box 1", "Box renamed" test.assertSelectorHasText ".box .box-label", name, "Box renamed" test.assertExist ".form-group.draftMailbox .dropdown", "Draft folder", "Draft dropdown" test.assertSelectorHasText ".form-group.draftMailbox .dropdown-menu", name, "Box in draft dropdown" test.assertExist ".form-group.sentMailbox .dropdown", "Sent folder", "Sent dropdown" test.assertSelectorHasText ".form-group.sentMailbox .dropdown-menu", name, "Box in sent dropdown" test.assertExist ".form-group.trashMailbox .dropdown", "Trash folder", "Trash dropdown" test.assertSelectorHasText ".form-group.trashMailbox .dropdown-menu", name, "Box in trash dropdown" casper.then -> test.comment "Delete mailbox" casper.click ".box .box-action.delete i" casper.waitUntilVisible '.modal-dialog', -> confirm = casper.fetchText('.modal-body').trim() test.assertEquals confirm, "Do you really want to delete all messages in this box?", "Confirmation dialog" casper.click ".modal-dialog .btn:not(.btn-cozy-non-default)" casper.waitWhileSelector "ul.boxes .box span.box-label", -> test.assertDoesntExist ".form-group.draftMailbox .dropdown", "No draft folder" test.assertDoesntExist ".form-group.sentMailbox .dropdown", "No sent folder" test.assertDoesntExist ".form-group.trashMailbox .dropdown", "No trash folder" test.assertElementCount "ul.boxes > li.box-item", 0, "No boxes" casper.then -> test.pass "ok" casper.run -> test.done() casper.test.begin 'Test accounts', (test) -> init casper casper.start casper.cozy.startUrl, -> casper.waitForSelector "aside[role=menubar][aria-expanded=true]" casper.then -> accountSel = ".mainmenu .account" accounts = casper.getElementsInfo accountSel id = accounts[0].attributes['data-reactid'] if not casper.exists ".active[data-reactid='#{id}']" casper.click "[data-reactid='#{id}']" casper.waitForSelector ".active[data-reactid='#{id}']", -> casper.click '.mainmenu .active .mailbox-config' casper.waitForSelector '#mailbox-config', -> test.assertSelectorHasText "#mailbox-config h3", "Edit account" test.assertSelectorHasText "#mailbox-config .nav-tabs .active", "Account", "Account tab is active" test.assertSelectorHasText "#mailbox-config .nav-tabs", "Folders", "Folder tab visible" casper.run -> deleteTestAccounts() test.done()
true
if global? require = patchRequire global.require else require = patchRequire this.require require.globals.casper = casper init = require(fs.workingDirectory + "/client/tests/casper/common").init utils = require "utils.js" deleteTestAccounts = -> casper.evaluate -> AccountStore = require 'stores/account_store' account = AccountStore.getByLabel 'Test Account' if account? AccountActionCreator = require 'actions/account_action_creator' console.log "Deleting test account #{account.get 'id'}" AccountActionCreator.remove(account.get 'id') else console.log "No test account to delete" casper.test.begin 'Test accounts', (test) -> init casper casper.start casper.cozy.startUrl, -> casper.waitForSelector "aside[role=menubar][aria-expanded=true]" casper.then -> accountSel = ".mainmenu .account" accounts = casper.getElementsInfo accountSel casper.eachThen accounts, (response) -> account = response.data id = account.attributes['data-reactid'] if not casper.exists ".active[data-reactid='#{id}']" casper.click "[data-reactid='#{id}']" casper.waitForSelector ".active[data-reactid='#{id}']", -> label = casper.getElementInfo "[data-reactid='#{id}'] .item-label" test.pass "Account #{label.text} selected" if casper.exists ".messages-list .message" casper.click ".messages-list .message a .subject" casper.waitUntilVisible ".conversation" , -> test.fail "Unable to select account #{account.text} #{id}" casper.run -> test.done() casper.test.begin 'Create account', (test) -> init casper casper.start casper.cozy.startUrl, -> casper.waitForSelector "aside[role=menubar][aria-expanded=true]" casper.then -> values = "mailbox-accountType": "IMAP", "mailbox-imapPort": "993", "mailbox-imapSSL": true, "mailbox-imapServer": "toto", "mailbox-imapTLS": false, "mailbox-label": "Test Account", "mailbox-login": "PI:EMAIL:<EMAIL>END_PI", "mailbox-name": "Test", "mailbox-password": "PI:PASSWORD:<PASSWORD>END_PI", "mailbox-smtpPort": "465", "mailbox-smtpSSL": true, "mailbox-smtpServer": "toto", "mailbox-smtpTLS": false deleteTestAccounts() account = casper.evaluate -> AccountStore = require 'stores/account_store' account = AccountStore.getByLabel 'Test Account' return account? test.assertFalsy account, "Test account doesnt exists" casper.click '.new-account-action' casper.waitForSelector '#mailbox-config', -> test.assertSelectorHasText "#mailbox-config h3", "New account" test.assertDoesntExist "#mailbox-config .nav-tabs", "No tabs" test.assertSelectorHasText "#mailbox-config button.action-save", "Add", "Add button" test.assertDoesntExist ".toast-error", "No error message" casper.click "#mailbox-config button.action-save" casper.waitForSelector ".toast-error", -> test.pass "Error message displayed" test.assertElementCount ".form-group.has-error", 9, "Errors are underlined" casper.fillSelectors 'form', '#mailbox-label': values['mailbox-label'] casper.click "#mailbox-config button.action-save" casper.wait 100, -> test.assertElementCount ".form-group.has-error", 8, "Errors are underlined" casper.fillSelectors 'form', '#mailbox-name': values['mailbox-name'] '#mailbox-login': values['mailbox-login'] '#mailbox-password': values['PI:PASSWORD:<PASSWORD>END_PI'] '#mailbox-smtpServer': values['mailbox-smtpServer'] '#mailbox-imapServer': values['mailbox-imapServer'] '#maibox-accountType': values['account-type'] casper.click "#mailbox-config button.action-save" casper.waitForSelector '.form-account.waiting', -> casper.waitWhileSelector '.form-account.waiting', -> test.assertSelectorHasText "#mailbox-config button.action-save", "Add", "Wrong SMTP Server" test.assertEquals casper.getFormValues('form'), values, "Form not changed" test.assertDoesntExist ".has-error #mailbox-label", "No error on label" test.assertExist ".has-error #mailbox-smtpServer", "Error on SMTP" casper.fillSelectors 'form', '#mailbox-accountType': 'TEST' '#mailbox-smtpServer': 'ssl0.ovh.net' '#mailbox-imapServer': values['mailbox-imapServer'] casper.wait 500, -> casper.click "#mailbox-config button.action-save" casper.waitForSelector "#mailbox-config .nav-tabs", -> test.pass 'No more errors ☺' casper.then -> test.comment "Creating mailbox" name = "Box 1" test.assertSelectorHasText "#mailbox-config .nav-tabs .active", "Folders", "Folders tab is active" test.assertDoesntExist ".form-group.draftMailbox .dropdown", "No draft folder" test.assertDoesntExist ".form-group.sentMailbox .dropdown", "No sent folder" test.assertDoesntExist ".form-group.trashMailbox .dropdown", "No trash folder" test.assertElementCount "ul.boxes > li.box-item", 0, "No boxes" casper.fillSelectors 'form', '#newmailbox': name casper.click '.box-action.add i' casper.waitForSelector '.box-item', -> test.assertSelectorHasText ".box .box-label", name, "Box created" test.assertExist ".form-group.draftMailbox .dropdown", "Draft folder", "Draft dropdown" test.assertSelectorHasText ".form-group.draftMailbox .dropdown-menu", name, "Box in draft dropdown" test.assertExist ".form-group.sentMailbox .dropdown", "Sent folder", "Sent dropdown" test.assertSelectorHasText ".form-group.sentMailbox .dropdown-menu", name, "Box in sent dropdown" test.assertExist ".form-group.trashMailbox .dropdown", "Trash folder", "Trash dropdown" test.assertSelectorHasText ".form-group.trashMailbox .dropdown-menu", name, "Box in trash dropdown" casper.then -> test.comment "Rename mailbox" name = "Box 2" casper.click ".box .box-action.edit i" casper.waitForSelector ".box .box-action.save", -> casper.fillSelectors 'form', '.box .box-label': name casper.click ".box .box-action.save i" casper.waitForSelector ".box span.box-label", -> test.assertSelectorDoesntHaveText ".box .box-label", "Box 1", "Box renamed" test.assertSelectorHasText ".box .box-label", name, "Box renamed" test.assertExist ".form-group.draftMailbox .dropdown", "Draft folder", "Draft dropdown" test.assertSelectorHasText ".form-group.draftMailbox .dropdown-menu", name, "Box in draft dropdown" test.assertExist ".form-group.sentMailbox .dropdown", "Sent folder", "Sent dropdown" test.assertSelectorHasText ".form-group.sentMailbox .dropdown-menu", name, "Box in sent dropdown" test.assertExist ".form-group.trashMailbox .dropdown", "Trash folder", "Trash dropdown" test.assertSelectorHasText ".form-group.trashMailbox .dropdown-menu", name, "Box in trash dropdown" casper.then -> test.comment "Delete mailbox" casper.click ".box .box-action.delete i" casper.waitUntilVisible '.modal-dialog', -> confirm = casper.fetchText('.modal-body').trim() test.assertEquals confirm, "Do you really want to delete all messages in this box?", "Confirmation dialog" casper.click ".modal-dialog .btn:not(.btn-cozy-non-default)" casper.waitWhileSelector "ul.boxes .box span.box-label", -> test.assertDoesntExist ".form-group.draftMailbox .dropdown", "No draft folder" test.assertDoesntExist ".form-group.sentMailbox .dropdown", "No sent folder" test.assertDoesntExist ".form-group.trashMailbox .dropdown", "No trash folder" test.assertElementCount "ul.boxes > li.box-item", 0, "No boxes" casper.then -> test.pass "ok" casper.run -> test.done() casper.test.begin 'Test accounts', (test) -> init casper casper.start casper.cozy.startUrl, -> casper.waitForSelector "aside[role=menubar][aria-expanded=true]" casper.then -> accountSel = ".mainmenu .account" accounts = casper.getElementsInfo accountSel id = accounts[0].attributes['data-reactid'] if not casper.exists ".active[data-reactid='#{id}']" casper.click "[data-reactid='#{id}']" casper.waitForSelector ".active[data-reactid='#{id}']", -> casper.click '.mainmenu .active .mailbox-config' casper.waitForSelector '#mailbox-config', -> test.assertSelectorHasText "#mailbox-config h3", "Edit account" test.assertSelectorHasText "#mailbox-config .nav-tabs .active", "Account", "Account tab is active" test.assertSelectorHasText "#mailbox-config .nav-tabs", "Folders", "Folder tab visible" casper.run -> deleteTestAccounts() test.done()
[ { "context": "\n# Project's main unit\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\nclass Colorifier extends Element\n include: cor", "end": 69, "score": 0.9998878240585327, "start": 52, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
src/colorifier.coffee
MadRabbit/colorifier
1
# # Project's main unit # # Copyright (C) 2011-2012 Nikolay Nemshilov # class Colorifier extends Element include: core.Options extend: # Default options Options: tag: 'pre' # tag name of the elements to process attr: 'data-lang' # attribute that keeps the language name theme: 'light' # color theme name gutter: true # show or not the gutter trim: true # automatically trim trailing spaces # mass-initializer initialize: ()-> $("#{Colorifier.Options.tag}[#{Colorifier.Options.attr}]").forEach (element)-> if lang = element.attr(Colorifier.Options.attr) color = Colorifier[lang] || Colorifier.unsupported color = element.colorifier or (element.colorifier = new color(element, lang)) return # # fallback markers comments: "" strings: "',\"" keywords: "" objects: "" booleans: "" regexps: [/([^\*\\\/;])(\/[^\*\/][^\n]*?[^\*\n\\](?!\\\/)\/[a-z]*)/g] # default POSIX style regexps styles2copy: "font-family,font-size,font-weight,line-height," + ",margin-top,margin-left,margin-right,margin-bottom" # # Default constructor # # @param {dom.Element} # @return {Colorifier} new # constructor: (element, lang)-> return @ unless element @setOptions(element.data('colorifier')) super 'div', class: 'colorifier' text = element.html() text = text.replace(/</g, '&lt;') text = text.replace(/>/g, '&gt;') text = text.replace(/(^\s*\n)|(\s+$)/g, '') if @options.trim @ref = element.html(this.paint(text)) @style(element.style(@styles2copy)) @insertTo(element.hide(), 'before') if @options.gutter nums = (i for line, i in text.split("\n")) @insert(new Element('div', class: 'gutter', html: nums.join('<br/>'))) @insert(new Element('div', class: 'code').html(element.html())) @addClass(@options.theme).data(lang: lang) # # Paints the code according to the rules # # @param {String} original # @param {Function} additional callback # @return {String} painted # paint: (text, callback)-> text = @_strings(text) text = @_regexps(text) text = @_comments(text) text = @_numbers(text) text = @_keywords(text) text = @_methods(text) text = callback.call(@, text) if callback @_rollback(text) # protected # painting the comments _comments: (text, callback)-> return text if !@comments replacements = [] # replacing the comments with dummies for token in @comments.split(',') chunks = token.split(' ') if chunks[1] regex = new RegExp("(.?)(#{escape(chunks[0])}[\\s\\S]*?#{escape(chunks[1])})(.*)", "mg") else regex = new RegExp("(.?)(#{escape(chunks[0])}.*?)(\n|$)", "g") replacements.push([regex, "comment", "$1 $3"]) @_prepare(text, replacements) # painting the strings _strings: (text, callback)-> return text if !@strings replacements = [] for token in @strings.split(',') regexs = [ new RegExp("([^\\\\])((#{escape(token)})(\\3))", 'mg') new RegExp("([^\\\\])((#{escape(token)})(.|\n)*?[^\\\\](\\3))", "mg") ] for re in regexs replacements.push([re, "string", "$1 "]) @_prepare(text, replacements) # painting the regexps _regexps: (text, callback)-> return text if !@regexps replacements = [] for re in @regexps replacements.push([re, "regexp", "$1 "]) @_prepare(text, replacements) # painting integers and floats _numbers: (text)-> @_prepare(text, [ [/([^'"\d\w\.])([\d]+)(?!['"\d\w\.])/g, "integer", "$1 "] [/([^'"\d\w\.])(\d*\.\d+)(?!['"\d\w\.])/g, "float", "$1 "] ]) # painting the keywords _keywords: (text)-> reps = [] for name in ['keyword', 'object', 'boolean'] if regexp = @[name + "s"].replace(/,/g, '|') regexp = new RegExp("([^a-zA-Z0-9_]|^)(#{regexp})(?![a-zA-Z0-9_])", "g") reps.push([regexp, name, "$1 "]) @_prepare(text, reps) # painting attributes and methods _methods: (text)-> @_prepare(text, [ [/([^a-zA-Z0-9_]|^)([A-Z][a-zA-Z_0-9]+)(?![a-zA-Z0-9_])/g, "unit", '$1 '] [/(\.)([a-z_$][a-z0-9_]*)(?![a-z0-9_\(])/ig, "attribute", '$1 '] [/(\.)([a-z_$][a-z0-9_]*)(\()/ig, "method", '$1 $3'] ]) # pre-replaces the text-entries with mocks so they didn't mess with the rest _prepare: (text, list)-> @___ or= [] tokens = @___ for [re, css, dummy] in list text = text.replace re, (m, _1, _2, _3, _4, _5)-> tokens.push("<span class=\"#{css}\">#{_2}</span>") dummy.replace(' ', "___dummy_#{tokens.length}___") .replace('$1', _1).replace('$3', _3).replace('$4', _4) text # rollbacks the comments, strings and regexps prereplacements _rollback: (text)-> for i in [@___.length - 1..0] text = text.replace("___dummy_#{i+1}___", @___[i]) text
131947
# # Project's main unit # # Copyright (C) 2011-2012 <NAME> # class Colorifier extends Element include: core.Options extend: # Default options Options: tag: 'pre' # tag name of the elements to process attr: 'data-lang' # attribute that keeps the language name theme: 'light' # color theme name gutter: true # show or not the gutter trim: true # automatically trim trailing spaces # mass-initializer initialize: ()-> $("#{Colorifier.Options.tag}[#{Colorifier.Options.attr}]").forEach (element)-> if lang = element.attr(Colorifier.Options.attr) color = Colorifier[lang] || Colorifier.unsupported color = element.colorifier or (element.colorifier = new color(element, lang)) return # # fallback markers comments: "" strings: "',\"" keywords: "" objects: "" booleans: "" regexps: [/([^\*\\\/;])(\/[^\*\/][^\n]*?[^\*\n\\](?!\\\/)\/[a-z]*)/g] # default POSIX style regexps styles2copy: "font-family,font-size,font-weight,line-height," + ",margin-top,margin-left,margin-right,margin-bottom" # # Default constructor # # @param {dom.Element} # @return {Colorifier} new # constructor: (element, lang)-> return @ unless element @setOptions(element.data('colorifier')) super 'div', class: 'colorifier' text = element.html() text = text.replace(/</g, '&lt;') text = text.replace(/>/g, '&gt;') text = text.replace(/(^\s*\n)|(\s+$)/g, '') if @options.trim @ref = element.html(this.paint(text)) @style(element.style(@styles2copy)) @insertTo(element.hide(), 'before') if @options.gutter nums = (i for line, i in text.split("\n")) @insert(new Element('div', class: 'gutter', html: nums.join('<br/>'))) @insert(new Element('div', class: 'code').html(element.html())) @addClass(@options.theme).data(lang: lang) # # Paints the code according to the rules # # @param {String} original # @param {Function} additional callback # @return {String} painted # paint: (text, callback)-> text = @_strings(text) text = @_regexps(text) text = @_comments(text) text = @_numbers(text) text = @_keywords(text) text = @_methods(text) text = callback.call(@, text) if callback @_rollback(text) # protected # painting the comments _comments: (text, callback)-> return text if !@comments replacements = [] # replacing the comments with dummies for token in @comments.split(',') chunks = token.split(' ') if chunks[1] regex = new RegExp("(.?)(#{escape(chunks[0])}[\\s\\S]*?#{escape(chunks[1])})(.*)", "mg") else regex = new RegExp("(.?)(#{escape(chunks[0])}.*?)(\n|$)", "g") replacements.push([regex, "comment", "$1 $3"]) @_prepare(text, replacements) # painting the strings _strings: (text, callback)-> return text if !@strings replacements = [] for token in @strings.split(',') regexs = [ new RegExp("([^\\\\])((#{escape(token)})(\\3))", 'mg') new RegExp("([^\\\\])((#{escape(token)})(.|\n)*?[^\\\\](\\3))", "mg") ] for re in regexs replacements.push([re, "string", "$1 "]) @_prepare(text, replacements) # painting the regexps _regexps: (text, callback)-> return text if !@regexps replacements = [] for re in @regexps replacements.push([re, "regexp", "$1 "]) @_prepare(text, replacements) # painting integers and floats _numbers: (text)-> @_prepare(text, [ [/([^'"\d\w\.])([\d]+)(?!['"\d\w\.])/g, "integer", "$1 "] [/([^'"\d\w\.])(\d*\.\d+)(?!['"\d\w\.])/g, "float", "$1 "] ]) # painting the keywords _keywords: (text)-> reps = [] for name in ['keyword', 'object', 'boolean'] if regexp = @[name + "s"].replace(/,/g, '|') regexp = new RegExp("([^a-zA-Z0-9_]|^)(#{regexp})(?![a-zA-Z0-9_])", "g") reps.push([regexp, name, "$1 "]) @_prepare(text, reps) # painting attributes and methods _methods: (text)-> @_prepare(text, [ [/([^a-zA-Z0-9_]|^)([A-Z][a-zA-Z_0-9]+)(?![a-zA-Z0-9_])/g, "unit", '$1 '] [/(\.)([a-z_$][a-z0-9_]*)(?![a-z0-9_\(])/ig, "attribute", '$1 '] [/(\.)([a-z_$][a-z0-9_]*)(\()/ig, "method", '$1 $3'] ]) # pre-replaces the text-entries with mocks so they didn't mess with the rest _prepare: (text, list)-> @___ or= [] tokens = @___ for [re, css, dummy] in list text = text.replace re, (m, _1, _2, _3, _4, _5)-> tokens.push("<span class=\"#{css}\">#{_2}</span>") dummy.replace(' ', "___dummy_#{tokens.length}___") .replace('$1', _1).replace('$3', _3).replace('$4', _4) text # rollbacks the comments, strings and regexps prereplacements _rollback: (text)-> for i in [@___.length - 1..0] text = text.replace("___dummy_#{i+1}___", @___[i]) text
true
# # Project's main unit # # Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI # class Colorifier extends Element include: core.Options extend: # Default options Options: tag: 'pre' # tag name of the elements to process attr: 'data-lang' # attribute that keeps the language name theme: 'light' # color theme name gutter: true # show or not the gutter trim: true # automatically trim trailing spaces # mass-initializer initialize: ()-> $("#{Colorifier.Options.tag}[#{Colorifier.Options.attr}]").forEach (element)-> if lang = element.attr(Colorifier.Options.attr) color = Colorifier[lang] || Colorifier.unsupported color = element.colorifier or (element.colorifier = new color(element, lang)) return # # fallback markers comments: "" strings: "',\"" keywords: "" objects: "" booleans: "" regexps: [/([^\*\\\/;])(\/[^\*\/][^\n]*?[^\*\n\\](?!\\\/)\/[a-z]*)/g] # default POSIX style regexps styles2copy: "font-family,font-size,font-weight,line-height," + ",margin-top,margin-left,margin-right,margin-bottom" # # Default constructor # # @param {dom.Element} # @return {Colorifier} new # constructor: (element, lang)-> return @ unless element @setOptions(element.data('colorifier')) super 'div', class: 'colorifier' text = element.html() text = text.replace(/</g, '&lt;') text = text.replace(/>/g, '&gt;') text = text.replace(/(^\s*\n)|(\s+$)/g, '') if @options.trim @ref = element.html(this.paint(text)) @style(element.style(@styles2copy)) @insertTo(element.hide(), 'before') if @options.gutter nums = (i for line, i in text.split("\n")) @insert(new Element('div', class: 'gutter', html: nums.join('<br/>'))) @insert(new Element('div', class: 'code').html(element.html())) @addClass(@options.theme).data(lang: lang) # # Paints the code according to the rules # # @param {String} original # @param {Function} additional callback # @return {String} painted # paint: (text, callback)-> text = @_strings(text) text = @_regexps(text) text = @_comments(text) text = @_numbers(text) text = @_keywords(text) text = @_methods(text) text = callback.call(@, text) if callback @_rollback(text) # protected # painting the comments _comments: (text, callback)-> return text if !@comments replacements = [] # replacing the comments with dummies for token in @comments.split(',') chunks = token.split(' ') if chunks[1] regex = new RegExp("(.?)(#{escape(chunks[0])}[\\s\\S]*?#{escape(chunks[1])})(.*)", "mg") else regex = new RegExp("(.?)(#{escape(chunks[0])}.*?)(\n|$)", "g") replacements.push([regex, "comment", "$1 $3"]) @_prepare(text, replacements) # painting the strings _strings: (text, callback)-> return text if !@strings replacements = [] for token in @strings.split(',') regexs = [ new RegExp("([^\\\\])((#{escape(token)})(\\3))", 'mg') new RegExp("([^\\\\])((#{escape(token)})(.|\n)*?[^\\\\](\\3))", "mg") ] for re in regexs replacements.push([re, "string", "$1 "]) @_prepare(text, replacements) # painting the regexps _regexps: (text, callback)-> return text if !@regexps replacements = [] for re in @regexps replacements.push([re, "regexp", "$1 "]) @_prepare(text, replacements) # painting integers and floats _numbers: (text)-> @_prepare(text, [ [/([^'"\d\w\.])([\d]+)(?!['"\d\w\.])/g, "integer", "$1 "] [/([^'"\d\w\.])(\d*\.\d+)(?!['"\d\w\.])/g, "float", "$1 "] ]) # painting the keywords _keywords: (text)-> reps = [] for name in ['keyword', 'object', 'boolean'] if regexp = @[name + "s"].replace(/,/g, '|') regexp = new RegExp("([^a-zA-Z0-9_]|^)(#{regexp})(?![a-zA-Z0-9_])", "g") reps.push([regexp, name, "$1 "]) @_prepare(text, reps) # painting attributes and methods _methods: (text)-> @_prepare(text, [ [/([^a-zA-Z0-9_]|^)([A-Z][a-zA-Z_0-9]+)(?![a-zA-Z0-9_])/g, "unit", '$1 '] [/(\.)([a-z_$][a-z0-9_]*)(?![a-z0-9_\(])/ig, "attribute", '$1 '] [/(\.)([a-z_$][a-z0-9_]*)(\()/ig, "method", '$1 $3'] ]) # pre-replaces the text-entries with mocks so they didn't mess with the rest _prepare: (text, list)-> @___ or= [] tokens = @___ for [re, css, dummy] in list text = text.replace re, (m, _1, _2, _3, _4, _5)-> tokens.push("<span class=\"#{css}\">#{_2}</span>") dummy.replace(' ', "___dummy_#{tokens.length}___") .replace('$1', _1).replace('$3', _3).replace('$4', _4) text # rollbacks the comments, strings and regexps prereplacements _rollback: (text)-> for i in [@___.length - 1..0] text = text.replace("___dummy_#{i+1}___", @___[i]) text
[ { "context": "/neocotic.com/UndoWikipediaBlackout) \r\n# (c) 2012 Alasdair Mercer \r\n# Freely distributable under the MIT license. ", "end": 100, "score": 0.999879002571106, "start": 85, "tag": "NAME", "value": "Alasdair Mercer" } ]
src/lib/utils.coffee
neocotic/UndoWikipediaBlackout
1
# [Undo Wikipedia Blackout](http://neocotic.com/UndoWikipediaBlackout) # (c) 2012 Alasdair Mercer # Freely distributable under the MIT license. # For all details and documentation: # <http://neocotic.com/UndoWikipediaBlackout> # Private classes # --------------- # `Class` makes for more readable logs etc. as it overrides `toString` to # output the name of the implementing class. class Class # Override the default `toString` implementation to provide a cleaner output. toString: -> @constructor.name # Private variables # ----------------- # Mapping of all timers currently being managed. timings = {} # Utilities setup # --------------- utils = window.utils = new class Utils extends Class # Public functions # ---------------- # Call a function asynchronously with the arguments provided and then pass # the returned value to `callback` if it was specified. async: (fn, args..., callback) -> if callback? and typeof callback isnt 'function' args.push callback callback = null setTimeout -> result = fn args... callback? result , 0 # Generate a unique key based on the current time and using a randomly # generated hexadecimal number of the specified length. keyGen: (separator = '.', length = 5, prefix = '', upperCase = yes) -> parts = [] # Populate the segment(s) to attempt uniquity. parts.push new Date().getTime() if length > 0 min = @repeat '1', '0', if length is 1 then 1 else length - 1 max = @repeat 'f', 'f', if length is 1 then 1 else length - 1 min = parseInt min, 16 max = parseInt max, 16 parts.push @random min, max # Convert segments to their hexadecimal (base 16) forms. parts[i] = part.toString 16 for part, i in parts # Join all segments using `separator` and append to the `prefix` before # potentially transforming it to upper case. key = prefix + parts.join separator if upperCase then key.toUpperCase() else key.toLowerCase() # Retrieve the first entity/all entities that pass the specified `filter`. query: (entities, singular, filter) -> if singular return entity for entity in entities when filter entity else entity for entity in entities when filter entity # Generate a random number between the `min` and `max` values provided. random: (min, max) -> Math.floor(Math.random() * (max - min + 1)) + min # Bind `handler` to event indicating that the DOM is ready. ready: (context, handler) -> unless handler? handler = context context = window if context.jQuery? context.jQuery handler else context.document.addEventListener 'DOMContentLoaded', handler # Repeat the string provided the specified number of times. repeat: (str = '', repeatStr = str, count = 1) -> if count isnt 0 # Repeat to the right if `count` is positive. str += repeatStr for i in [1..count] if count > 0 # Repeat to the left if `count` is negative. str = repeatStr + str for i in [1..count*-1] if count < 0 str # Start a new timer for the specified `key`. # If a timer already exists for `key`, return the time difference in # milliseconds. time: (key) -> if timings.hasOwnProperty key new Date().getTime() - timings[key] else timings[key] = new Date().getTime() # End the timer for the specified `key` and return the time difference in # milliseconds and remove the timer. # If no timer exists for `key`, simply return `0'. timeEnd: (key) -> if timings.hasOwnProperty key start = timings[key] delete timings[key] new Date().getTime() - start else 0 # Convenient shorthand for `chrome.extension.getURL`. url: -> chrome.extension.getURL arguments... # Public classes # -------------- # Objects within the extension should extend this class wherever possible. utils.Class = Class # `Runner` allows asynchronous code to be executed dependently in an # organized manner. class utils.Runner extends utils.Class # Create a new instance of `Runner`. constructor: -> @queue = [] # Finalize the process by resetting this `Runner` an then calling `onfinish`, # if it was specified when `run` was called. # Any arguments passed in should also be passed to the registered `onfinish` # handler. finish: (args...) -> @queue = [] @started = no @onfinish? args... # Remove the next task from the queue and call it. # Finish up if there are no more tasks in the queue, ensuring any `args` are # passed along to `onfinish`. next: (args...) -> if @started if @queue.length ctx = fn = null task = @queue.shift() # Determine what context the function should be executed in. switch typeof task.reference when 'function' then fn = task.reference when 'string' ctx = task.context fn = ctx[task.reference] # Unpack the arguments where required. if typeof task.args is 'function' task.args = task.args.apply null fn?.apply ctx, task.args return yes else @finish args... no # Add a new task to the queue using the values provided. # `reference` can either be the name of the property on the `context` object # which references the target function or the function itself. When the # latter, `context` is ignored and should be `null` (not omitted). All of the # remaining `args` are passed to the function when it is called during the # process. push: (context, reference, args...) -> @queue.push args: args context: context reference: reference # Add a new task to the queue using the *packed* values provided. # This method varies from `push` since the arguments are provided in the form # of a function which is called immediately before the function, which allows # any dependent arguments to be correctly referenced. pushPacked: (context, reference, packedArgs) -> @queue.push args: packedArgs context: context reference: reference # Start the process by calling the first task in the queue and register the # `onfinish` function provided. run: (@onfinish) -> @started = yes @next() # Remove the specified number of tasks from the front of the queue. skip: (count = 1) -> @queue.splice 0, count
38692
# [Undo Wikipedia Blackout](http://neocotic.com/UndoWikipediaBlackout) # (c) 2012 <NAME> # Freely distributable under the MIT license. # For all details and documentation: # <http://neocotic.com/UndoWikipediaBlackout> # Private classes # --------------- # `Class` makes for more readable logs etc. as it overrides `toString` to # output the name of the implementing class. class Class # Override the default `toString` implementation to provide a cleaner output. toString: -> @constructor.name # Private variables # ----------------- # Mapping of all timers currently being managed. timings = {} # Utilities setup # --------------- utils = window.utils = new class Utils extends Class # Public functions # ---------------- # Call a function asynchronously with the arguments provided and then pass # the returned value to `callback` if it was specified. async: (fn, args..., callback) -> if callback? and typeof callback isnt 'function' args.push callback callback = null setTimeout -> result = fn args... callback? result , 0 # Generate a unique key based on the current time and using a randomly # generated hexadecimal number of the specified length. keyGen: (separator = '.', length = 5, prefix = '', upperCase = yes) -> parts = [] # Populate the segment(s) to attempt uniquity. parts.push new Date().getTime() if length > 0 min = @repeat '1', '0', if length is 1 then 1 else length - 1 max = @repeat 'f', 'f', if length is 1 then 1 else length - 1 min = parseInt min, 16 max = parseInt max, 16 parts.push @random min, max # Convert segments to their hexadecimal (base 16) forms. parts[i] = part.toString 16 for part, i in parts # Join all segments using `separator` and append to the `prefix` before # potentially transforming it to upper case. key = prefix + parts.join separator if upperCase then key.toUpperCase() else key.toLowerCase() # Retrieve the first entity/all entities that pass the specified `filter`. query: (entities, singular, filter) -> if singular return entity for entity in entities when filter entity else entity for entity in entities when filter entity # Generate a random number between the `min` and `max` values provided. random: (min, max) -> Math.floor(Math.random() * (max - min + 1)) + min # Bind `handler` to event indicating that the DOM is ready. ready: (context, handler) -> unless handler? handler = context context = window if context.jQuery? context.jQuery handler else context.document.addEventListener 'DOMContentLoaded', handler # Repeat the string provided the specified number of times. repeat: (str = '', repeatStr = str, count = 1) -> if count isnt 0 # Repeat to the right if `count` is positive. str += repeatStr for i in [1..count] if count > 0 # Repeat to the left if `count` is negative. str = repeatStr + str for i in [1..count*-1] if count < 0 str # Start a new timer for the specified `key`. # If a timer already exists for `key`, return the time difference in # milliseconds. time: (key) -> if timings.hasOwnProperty key new Date().getTime() - timings[key] else timings[key] = new Date().getTime() # End the timer for the specified `key` and return the time difference in # milliseconds and remove the timer. # If no timer exists for `key`, simply return `0'. timeEnd: (key) -> if timings.hasOwnProperty key start = timings[key] delete timings[key] new Date().getTime() - start else 0 # Convenient shorthand for `chrome.extension.getURL`. url: -> chrome.extension.getURL arguments... # Public classes # -------------- # Objects within the extension should extend this class wherever possible. utils.Class = Class # `Runner` allows asynchronous code to be executed dependently in an # organized manner. class utils.Runner extends utils.Class # Create a new instance of `Runner`. constructor: -> @queue = [] # Finalize the process by resetting this `Runner` an then calling `onfinish`, # if it was specified when `run` was called. # Any arguments passed in should also be passed to the registered `onfinish` # handler. finish: (args...) -> @queue = [] @started = no @onfinish? args... # Remove the next task from the queue and call it. # Finish up if there are no more tasks in the queue, ensuring any `args` are # passed along to `onfinish`. next: (args...) -> if @started if @queue.length ctx = fn = null task = @queue.shift() # Determine what context the function should be executed in. switch typeof task.reference when 'function' then fn = task.reference when 'string' ctx = task.context fn = ctx[task.reference] # Unpack the arguments where required. if typeof task.args is 'function' task.args = task.args.apply null fn?.apply ctx, task.args return yes else @finish args... no # Add a new task to the queue using the values provided. # `reference` can either be the name of the property on the `context` object # which references the target function or the function itself. When the # latter, `context` is ignored and should be `null` (not omitted). All of the # remaining `args` are passed to the function when it is called during the # process. push: (context, reference, args...) -> @queue.push args: args context: context reference: reference # Add a new task to the queue using the *packed* values provided. # This method varies from `push` since the arguments are provided in the form # of a function which is called immediately before the function, which allows # any dependent arguments to be correctly referenced. pushPacked: (context, reference, packedArgs) -> @queue.push args: packedArgs context: context reference: reference # Start the process by calling the first task in the queue and register the # `onfinish` function provided. run: (@onfinish) -> @started = yes @next() # Remove the specified number of tasks from the front of the queue. skip: (count = 1) -> @queue.splice 0, count
true
# [Undo Wikipedia Blackout](http://neocotic.com/UndoWikipediaBlackout) # (c) 2012 PI:NAME:<NAME>END_PI # Freely distributable under the MIT license. # For all details and documentation: # <http://neocotic.com/UndoWikipediaBlackout> # Private classes # --------------- # `Class` makes for more readable logs etc. as it overrides `toString` to # output the name of the implementing class. class Class # Override the default `toString` implementation to provide a cleaner output. toString: -> @constructor.name # Private variables # ----------------- # Mapping of all timers currently being managed. timings = {} # Utilities setup # --------------- utils = window.utils = new class Utils extends Class # Public functions # ---------------- # Call a function asynchronously with the arguments provided and then pass # the returned value to `callback` if it was specified. async: (fn, args..., callback) -> if callback? and typeof callback isnt 'function' args.push callback callback = null setTimeout -> result = fn args... callback? result , 0 # Generate a unique key based on the current time and using a randomly # generated hexadecimal number of the specified length. keyGen: (separator = '.', length = 5, prefix = '', upperCase = yes) -> parts = [] # Populate the segment(s) to attempt uniquity. parts.push new Date().getTime() if length > 0 min = @repeat '1', '0', if length is 1 then 1 else length - 1 max = @repeat 'f', 'f', if length is 1 then 1 else length - 1 min = parseInt min, 16 max = parseInt max, 16 parts.push @random min, max # Convert segments to their hexadecimal (base 16) forms. parts[i] = part.toString 16 for part, i in parts # Join all segments using `separator` and append to the `prefix` before # potentially transforming it to upper case. key = prefix + parts.join separator if upperCase then key.toUpperCase() else key.toLowerCase() # Retrieve the first entity/all entities that pass the specified `filter`. query: (entities, singular, filter) -> if singular return entity for entity in entities when filter entity else entity for entity in entities when filter entity # Generate a random number between the `min` and `max` values provided. random: (min, max) -> Math.floor(Math.random() * (max - min + 1)) + min # Bind `handler` to event indicating that the DOM is ready. ready: (context, handler) -> unless handler? handler = context context = window if context.jQuery? context.jQuery handler else context.document.addEventListener 'DOMContentLoaded', handler # Repeat the string provided the specified number of times. repeat: (str = '', repeatStr = str, count = 1) -> if count isnt 0 # Repeat to the right if `count` is positive. str += repeatStr for i in [1..count] if count > 0 # Repeat to the left if `count` is negative. str = repeatStr + str for i in [1..count*-1] if count < 0 str # Start a new timer for the specified `key`. # If a timer already exists for `key`, return the time difference in # milliseconds. time: (key) -> if timings.hasOwnProperty key new Date().getTime() - timings[key] else timings[key] = new Date().getTime() # End the timer for the specified `key` and return the time difference in # milliseconds and remove the timer. # If no timer exists for `key`, simply return `0'. timeEnd: (key) -> if timings.hasOwnProperty key start = timings[key] delete timings[key] new Date().getTime() - start else 0 # Convenient shorthand for `chrome.extension.getURL`. url: -> chrome.extension.getURL arguments... # Public classes # -------------- # Objects within the extension should extend this class wherever possible. utils.Class = Class # `Runner` allows asynchronous code to be executed dependently in an # organized manner. class utils.Runner extends utils.Class # Create a new instance of `Runner`. constructor: -> @queue = [] # Finalize the process by resetting this `Runner` an then calling `onfinish`, # if it was specified when `run` was called. # Any arguments passed in should also be passed to the registered `onfinish` # handler. finish: (args...) -> @queue = [] @started = no @onfinish? args... # Remove the next task from the queue and call it. # Finish up if there are no more tasks in the queue, ensuring any `args` are # passed along to `onfinish`. next: (args...) -> if @started if @queue.length ctx = fn = null task = @queue.shift() # Determine what context the function should be executed in. switch typeof task.reference when 'function' then fn = task.reference when 'string' ctx = task.context fn = ctx[task.reference] # Unpack the arguments where required. if typeof task.args is 'function' task.args = task.args.apply null fn?.apply ctx, task.args return yes else @finish args... no # Add a new task to the queue using the values provided. # `reference` can either be the name of the property on the `context` object # which references the target function or the function itself. When the # latter, `context` is ignored and should be `null` (not omitted). All of the # remaining `args` are passed to the function when it is called during the # process. push: (context, reference, args...) -> @queue.push args: args context: context reference: reference # Add a new task to the queue using the *packed* values provided. # This method varies from `push` since the arguments are provided in the form # of a function which is called immediately before the function, which allows # any dependent arguments to be correctly referenced. pushPacked: (context, reference, packedArgs) -> @queue.push args: packedArgs context: context reference: reference # Start the process by calling the first task in the queue and register the # `onfinish` function provided. run: (@onfinish) -> @started = yes @next() # Remove the specified number of tasks from the front of the queue. skip: (count = 1) -> @queue.splice 0, count
[ { "context": " key_value_pairs = for key, value of keys\n \"#{key}='#{value.replace(/'/g, \"''\")}'\"\n\n keys_string = ", "end": 1121, "score": 0.7489868402481079, "start": 1112, "tag": "KEY", "value": "\"#{key}='" }, { "context": "e_pairs = for key, value of keys\n ...
src/client.coffee
sap-archive/sapjam-hubot-adapter
0
# # SAP Jam OData client # pluralize = require('pluralize') request = require ('request') ODATA_PREFIX = "/api/v1/OData" class Client constructor: (options) -> @options = options get_entity: (entity, callback) -> @get_odata(@entity_uri_string(entity.type, entity.navigation, entity.keys), callback) post_service: (service, params, callback) -> @post_odata(@service_uri_string(service, params), null, callback) post_entity: (entity, payload) -> @post_odata(@entity_uri_string(entity.type, entity.navigation, entity.keys), payload) # ----------- Helper methods ------------- # Assemble service operation URI string service_uri_string: (service, params) -> key_value_pairs = for key, value of params "#{key}='#{value}'" params_string = key_value_pairs.join("&") uri = "/#{service}?#{params_string}" # Assemble OData URI string entity_uri_string: (type, navigation, keys) -> type_pattern = /(.*)([A-Z][a-z]+)/ matches = type.match type_pattern type = matches[1] + pluralize(matches[2]) key_value_pairs = for key, value of keys "#{key}='#{value.replace(/'/g, "''")}'" keys_string = key_value_pairs.join(",%20") navigation_string = if navigation then "/#{navigation}" else "" uri = "/#{type}(#{keys_string})#{navigation_string}" # GET call to Jam get_odata: (path, callback) -> console.log("GET: #{@options.server}#{ODATA_PREFIX}#{path}") request { method: 'GET' uri: "#{@options.server}#{ODATA_PREFIX}#{path}" headers: { "Authorization": "Bearer #{@options.oauth_token}", "Accept": "application/json" } }, (err, res, body) -> if err? console.error("Error from SAP Jam Adapter: #{err}") typeof callback is "function" and callback(true, null) else if res.statusCode isnt 200 console.error("Unexpected #{res.statusCode} response from SAP Jam API: #{body}") typeof callback is "function" and callback(true, null) else typeof callback is "function" and callback(null, body) # POST call to Jam post_odata: (path, payload, callback) -> console.log("POST: #{@options.server}#{ODATA_PREFIX}#{path}") request { method: 'POST' uri: "#{@options.server}#{ODATA_PREFIX}#{path}" headers: { "Authorization": "Bearer #{@options.oauth_token}", "Accept": "application/json", "Content-Type": "application/json" } body: if payload then JSON.stringify(payload) else null }, (err, res, body) -> if err? console.error("Error from SAP Jam Adapter: #{err}") typeof callback is "function" and callback(true, null) else if res.statusCode not in [201, 204] console.error("Unexpected #{res.statusCode} response from SAP Jam API: #{body}") typeof callback is "function" and callback(true, null) else typeof callback is "function" and callback(null, body) module.exports = Client
116278
# # SAP Jam OData client # pluralize = require('pluralize') request = require ('request') ODATA_PREFIX = "/api/v1/OData" class Client constructor: (options) -> @options = options get_entity: (entity, callback) -> @get_odata(@entity_uri_string(entity.type, entity.navigation, entity.keys), callback) post_service: (service, params, callback) -> @post_odata(@service_uri_string(service, params), null, callback) post_entity: (entity, payload) -> @post_odata(@entity_uri_string(entity.type, entity.navigation, entity.keys), payload) # ----------- Helper methods ------------- # Assemble service operation URI string service_uri_string: (service, params) -> key_value_pairs = for key, value of params "#{key}='#{value}'" params_string = key_value_pairs.join("&") uri = "/#{service}?#{params_string}" # Assemble OData URI string entity_uri_string: (type, navigation, keys) -> type_pattern = /(.*)([A-Z][a-z]+)/ matches = type.match type_pattern type = matches[1] + pluralize(matches[2]) key_value_pairs = for key, value of keys <KEY>#{<KEY>.replace(/'/g, "''<KEY>")}'" keys_string = key_value_pairs.<KEY> navigation_string = if navigation then "/#{navigation}" else "" uri = "/#{type}(#{keys_string})#{navigation_string}" # GET call to Jam get_odata: (path, callback) -> console.log("GET: #{@options.server}#{ODATA_PREFIX}#{path}") request { method: 'GET' uri: "#{@options.server}#{ODATA_PREFIX}#{path}" headers: { "Authorization": "Bearer #{@options.oauth_token}", "Accept": "application/json" } }, (err, res, body) -> if err? console.error("Error from SAP Jam Adapter: #{err}") typeof callback is "function" and callback(true, null) else if res.statusCode isnt 200 console.error("Unexpected #{res.statusCode} response from SAP Jam API: #{body}") typeof callback is "function" and callback(true, null) else typeof callback is "function" and callback(null, body) # POST call to Jam post_odata: (path, payload, callback) -> console.log("POST: #{@options.server}#{ODATA_PREFIX}#{path}") request { method: 'POST' uri: "#{@options.server}#{ODATA_PREFIX}#{path}" headers: { "Authorization": "Bearer #{@options.oauth_token}", "Accept": "application/json", "Content-Type": "application/json" } body: if payload then JSON.stringify(payload) else null }, (err, res, body) -> if err? console.error("Error from SAP Jam Adapter: #{err}") typeof callback is "function" and callback(true, null) else if res.statusCode not in [201, 204] console.error("Unexpected #{res.statusCode} response from SAP Jam API: #{body}") typeof callback is "function" and callback(true, null) else typeof callback is "function" and callback(null, body) module.exports = Client
true
# # SAP Jam OData client # pluralize = require('pluralize') request = require ('request') ODATA_PREFIX = "/api/v1/OData" class Client constructor: (options) -> @options = options get_entity: (entity, callback) -> @get_odata(@entity_uri_string(entity.type, entity.navigation, entity.keys), callback) post_service: (service, params, callback) -> @post_odata(@service_uri_string(service, params), null, callback) post_entity: (entity, payload) -> @post_odata(@entity_uri_string(entity.type, entity.navigation, entity.keys), payload) # ----------- Helper methods ------------- # Assemble service operation URI string service_uri_string: (service, params) -> key_value_pairs = for key, value of params "#{key}='#{value}'" params_string = key_value_pairs.join("&") uri = "/#{service}?#{params_string}" # Assemble OData URI string entity_uri_string: (type, navigation, keys) -> type_pattern = /(.*)([A-Z][a-z]+)/ matches = type.match type_pattern type = matches[1] + pluralize(matches[2]) key_value_pairs = for key, value of keys PI:KEY:<KEY>END_PI#{PI:KEY:<KEY>END_PI.replace(/'/g, "''PI:KEY:<KEY>END_PI")}'" keys_string = key_value_pairs.PI:KEY:<KEY>END_PI navigation_string = if navigation then "/#{navigation}" else "" uri = "/#{type}(#{keys_string})#{navigation_string}" # GET call to Jam get_odata: (path, callback) -> console.log("GET: #{@options.server}#{ODATA_PREFIX}#{path}") request { method: 'GET' uri: "#{@options.server}#{ODATA_PREFIX}#{path}" headers: { "Authorization": "Bearer #{@options.oauth_token}", "Accept": "application/json" } }, (err, res, body) -> if err? console.error("Error from SAP Jam Adapter: #{err}") typeof callback is "function" and callback(true, null) else if res.statusCode isnt 200 console.error("Unexpected #{res.statusCode} response from SAP Jam API: #{body}") typeof callback is "function" and callback(true, null) else typeof callback is "function" and callback(null, body) # POST call to Jam post_odata: (path, payload, callback) -> console.log("POST: #{@options.server}#{ODATA_PREFIX}#{path}") request { method: 'POST' uri: "#{@options.server}#{ODATA_PREFIX}#{path}" headers: { "Authorization": "Bearer #{@options.oauth_token}", "Accept": "application/json", "Content-Type": "application/json" } body: if payload then JSON.stringify(payload) else null }, (err, res, body) -> if err? console.error("Error from SAP Jam Adapter: #{err}") typeof callback is "function" and callback(true, null) else if res.statusCode not in [201, 204] console.error("Unexpected #{res.statusCode} response from SAP Jam API: #{body}") typeof callback is "function" and callback(true, null) else typeof callback is "function" and callback(null, body) module.exports = Client
[ { "context": "# kicad.js v0.1.0\n# (c) 2015 Ricardo (XenGi) Band\n\n\ncolor = {}\ncolor['Fg'] = {'r': 255", "end": 36, "score": 0.9998683333396912, "start": 29, "tag": "NAME", "value": "Ricardo" }, { "context": "# kicad.js v0.1.0\n# (c) 2015 Ricardo (XenGi) Band\n\n\ncolor = {}\ncolo...
kicad.coffee
luxferresum/kicad.js
0
# kicad.js v0.1.0 # (c) 2015 Ricardo (XenGi) Band color = {} color['Fg'] = {'r': 255, 'g': 255, 'b': 255} color['Bg'] = {'r': 0, 'g': 0, 'b': 0} color['F.Cu'] = {'r': 132, 'g': 0, 'b': 0} color['B.Cu'] = {'r': 0, 'g': 132, 'b': 0} color['F.Adhes'] = {'r': 132, 'g': 0, 'b': 132} color['B.Adhes'] = {'r': 0, 'g': 0, 'b': 132} color['F.Paste'] = {'r': 132, 'g': 0, 'b': 0} color['B.Paste'] = {'r': 0, 'g': 194, 'b': 194} color['F.SilkS'] = {'r': 0, 'g': 132, 'b': 132} color['B.SilkS'] = {'r': 132, 'g': 0, 'b': 132} color['F.Mask'] = {'r': 132, 'g': 0, 'b': 132} color['B.Mask'] = {'r': 132, 'g': 132, 'b': 0} color['Dwgs.User'] = {'r': 194, 'g': 194, 'b': 194} color['Cmts.User'] = {'r': 0, 'g': 0, 'b': 132} color['Eco1.User'] = {'r': 0, 'g': 132, 'b': 0} color['Eco2.user'] = {'r': 194, 'g': 194, 'b': 0} color['Egde.Cuts'] = {'r': 194, 'g': 194, 'b': 0} color['Margin'] = {'r': 194, 'g': 0, 'b': 194} color['F.CrtYd'] = {'r': 132, 'g': 132, 'b': 132} color['B.CrtYd'] = {'r': 0, 'g': 0, 'b': 0} color['F.Fab'] = {'r': 194, 'g': 194, 'b': 0} color['B.Fab'] = {'r': 132, 'g': 0, 'b': 0} draw_grid = (c, size, w, h) -> center_x = w / 2 center_y = h / 2 dots_x = parseInt(w / size) dots_x += dots_x % 2 dots_y = parseInt(h / size) dots_y += dots_y % 2 for x in [0..dots_x] for y in [0..dots_y] _x = x*size + center_x _y = y*size + center_y console.log("dot at #{_x},#{_y}") c.beginPath() c.strokeStyle = "rgba(132, 132, 132, 1)" c.arc(_x - dots_x / 2 * size, _y - dots_y / 2 * size, 1, 0, 2 * Math.PI, false) #c.lineWidth = 1 c.stroke() draw_fpline = (c, fpline) -> c.strokeStyle = "rgba(#{color[fpline['layer']]['r']}, #{color[fpline['layer']]['g']}, #{color[fpline['layer']]['b']}, 1)" c.lineWidth = fpline['width'] c.lineCap = 'square' c.beginPath() c.moveTo(fpline['x1'], fpline['y1']) c.lineTo(fpline['x2'], fpline['y2']) c.stroke() draw_fpcircle = (c, fpcircle) -> c.beginPath() c.strokeStyle = "rgba(#{color[fpcircle['layer']]['r']}, #{color[fpcircle['layer']]['g']}, #{color[fpcircle['layer']]['b']}, 1)" c.arc(fpcircle['center_x'], fpcircle['center_y'], fpcircle['radius'], 0, 2 * Math.PI, false) c.lineWidth = fpcircle['width'] c.stroke() draw_fparc = (c, fparc) -> # TODO: implement me! return draw_fptext = (c, fptext) -> # TODO: implement me! return draw_pad = (c, pad) -> if pad['shape'] == 'circle' c.beginPath() c.arc(pad['x'], pad['y'], pad['width'] / 2, 0, 2 * Math.PI, false) c.fillStyle = "rgba(#{color['B.Mask']['r']}, #{color['B.Mask']['g']}, #{color['B.Mask']['b']}, 1)" c.fill() #else if pad['shape'] == 'oval' # TODO: implement me! #c.beginPath() # #c.fillStyle = "rgba(#{color['B.Mask']['r']}, # #{color['B.Mask']['g']}, # #{color['B.Mask']['b']}, # 1)" #c.fill() else if pad['shape'] == 'rect' c.beginPath() c.fillRect(pad['x'], pad['y'], pad['width'], pad['height']) c.fillStyle = "rgba(#{color['B.Mask']['r']}, #{color['B.Mask']['g']}, #{color['B.Mask']['b']}, 1)" c.fill() if pad['type'] == 'thru_hole' c.beginPath() c.arc(pad['x'], pad['y'], pad['drill'] / 2, 0, 2 * Math.PI, false) c.fillStyle = "rgba(#{color['Bg']['r']}, #{color['Bg']['g']}, #{color['Bg']['b']}, 1)" c.fill() #else if pad['type'] == 'np_thru_hole' # TODO: implement me! #else if pad['type'] == 'smd' # TODO: implement me! if pad['num'] != '' c.beginPath() c.textAlign = 'center' c.textBaseline = 'middle' c.fillStyle = "rgba(#{color['Fg']['r']}, #{color['Fg']['g']}, #{color['Fg']['b']}, 1)" c.fillText(pad['num'], pad['x'], pad['y']) draw_footprint = (canvas, data) -> if canvas.getContext context = canvas.getContext('2d') # draw background context.fillStyle = "rgb(#{color['Bg']['r']}, #{color['Bg']['g']}, #{color['Bg']['b']})" context.fillRect(0, 0, canvas.width, canvas.height) # set outer boundaries of pretty file left = 0 top = 0 right = 0 bottom = 0 update_dimensions = (x, y) -> if parseFloat(x) < parseFloat(left) left = x else if parseFloat(x) > parseFloat(right) right = x if parseFloat(y) < parseFloat(bottom) bottom = y else if parseFloat(y) > parseFloat(top) top = y # save all lines in a list to draw them later fp_lines = [] fp_circles = [] fp_arcs = [] fp_texts = [] pads = [] # read pretty file prettylines = data.split('\n') for l in prettylines l = l.trim() regex_fpline = /\(fp_line\ \(start\ ([-.\d]*)\ ([-.\d]*)\)\ \(end\ ([-.\d]*)\ ([-.\d]*)\)\ \(layer\ ([.a-zA-Z]*)\)\ \(width\ ([-.\d]*)\)\)/g while((m = regex_fpline.exec(l)) != null) # TODO: forgot what the next 2 lines do.. if (m.index == regex_fpline.lastIndex) regex_fpline.lastIndex++ fp_line = {} fp_line['x1'] = parseFloat(m[1]) fp_line['y1'] = parseFloat(m[2]) fp_line['x2'] = parseFloat(m[3]) fp_line['y2'] = parseFloat(m[4]) fp_line['layer'] = m[5] fp_line['width'] = parseFloat(m[6]) update_dimensions(fp_line['x1'], fp_line['y1']) update_dimensions(fp_line['x2'], fp_line['y2']) fp_lines.push(fp_line) regex_fpcircle = /\(fp_circle\ \(center\ ([-.\d]+)\ ([-.\d]+)\)\ \(end\ ([-.\d]+)\ ([-.\d]+)\)\ \(layer\ ([.\w]+)\)\ \(width\ ([.\d]+)\)\)/g while((m = regex_fpcircle.exec(l)) != null) if(m.index == regex_fpcircle.astIndex) regex_fpcircle.lastIndex++ fp_circle = {} fp_circle['center_x'] = parseFloat(m[1]) fp_circle['center_y'] = parseFloat(m[2]) x = parseFloat(m[3]) y = parseFloat(m[4]) fp_circle['radius'] = Math.sqrt(Math.pow(fp_circle['center_x'] - x, 2) + Math.pow(fp_circle['center_y'] - y, 2)) fp_circle['layer'] = m[5] fp_circle['width'] = parseFloat(m[6]) update_dimensions(fp_circle['center_x'] - fp_circle['radius'], fp_circle['center_y'] - fp_circle['radius']) update_dimensions(fp_circle['center_x'] + fp_circle['radius'], fp_circle['center_y'] + fp_circle['radius']) fp_circles.push(fp_circle) regex_pad = /\(pad\ ([\d]*)\ ([_a-z]*)\ ([a-z]*)\ \(at\ ([-.\d]*)\ ([-.\d]*)\)\ \(size\ ([.\d]*)\ ([.\d]*)\)\ \(drill\ ([.\d]*)\)\ \(layers\ ([\w\d\s\.\*]*)\)\)/g while((m = regex_pad.exec(l)) != null) # TODO: forgot what the next 2 lines do.. if (m.index == regex_pad.lastIndex) regex_pad.lastIndex++ pad = {} pad['num'] = '' if m[1] != '""' pad['num'] = m[1] pad['type'] = m[2] pad['shape'] = m[3] pad['x'] = parseFloat(m[4]) pad['y'] = parseFloat(m[5]) pad['width'] = parseFloat(m[6]) pad['height'] = parseFloat(m[7]) pad['drill'] = parseFloat(m[8]) pad['layers'] = m[9].split(' ') update_dimensions(pad['x'] - pad['width'] / 2, pad['y'] - pad['height'] / 2) update_dimensions(pad['x'] + pad['width'] / 2, pad['y'] + pad['height'] / 2) pads.push(pad) console.log("DEBUG: found #{fp_lines.length} fp_lines") console.log("DEBUG: found #{fp_circles.length} fp_circles") console.log("DEBUG: found #{fp_arcs.length} fp_arcs") console.log("DEBUG: found #{fp_texts.length} fp_texts") console.log("DEBUG: found #{pads.length} pads") # calculate zoom factor cw = canvas.width / 2 ch = canvas.height / 2 maxw = Math.max(Math.abs(left), Math.abs(right)) maxh = Math.max(Math.abs(top), Math.abs(bottom)) zoom = Math.min((cw - 10) / maxw, (ch - 10) / maxh) console.log("DEBUG: max dimensions: left=#{left}; right=#{right}; top=#{top}; bottom=#{bottom}") console.log("DEBUG: zoom: #{zoom}") # draw everything draw_grid(context, 1.27 * zoom, canvas.width, canvas.height) for fpline in fp_lines # translate coords fpline['x1'] = fpline['x1'] * zoom + cw fpline['y1'] = fpline['y1'] * zoom + ch fpline['x2'] = fpline['x2'] * zoom + cw fpline['y2'] = fpline['y2'] * zoom + ch fpline['width'] *= zoom draw_fpline(context, fpline) for fpcircle in fp_circles fpcircle['center_x'] = fpcircle['center_x'] * zoom + cw fpcircle['center_y'] = fpcircle['center_y'] * zoom + ch fpcircle['radius'] *= zoom fpcircle['width'] *= zoom draw_fpcircle(context, fpcircle) for fparc in fp_arcs #fparc['center_x'] = fparc['center_x'] * zoom + cw #fparc['center_y'] = fparc['center_y'] * zoom + ch #fparc['width'] *= zoom draw_fparc(context, fparc) for fptext in fp_texts #fptext['center_x'] = fptext['center_x'] * zoom + cw #fptext['center_y'] = fptext['center_y'] * zoom + ch #fptext['width'] *= zoom draw_fptext(context, fptext) for pad in pads pad['x'] = pad['x'] * zoom + cw pad['y'] = pad['y'] * zoom + ch pad['width'] *= zoom pad['height'] *= zoom pad['drill'] *= zoom draw_pad(context, pad) Kicad = (canvas) -> data = {}; zoom = 0; this.render = () -> draw_footprint(canvas, data); this.load = (d) -> data = d; this.zoom = (level) -> zoom = zoom + level; render() return this if typeof(define) != 'undefined' define 'kicad', [], () -> return Kicad else if typeof(module) != 'undefined' && typeof(moule.exports) != 'undefined' module.exports = Kicad else if window window.Kicad = Kicad else if global global.Kicad = Kicad
126039
# kicad.js v0.1.0 # (c) 2015 <NAME> (<NAME>Gi) Band color = {} color['Fg'] = {'r': 255, 'g': 255, 'b': 255} color['Bg'] = {'r': 0, 'g': 0, 'b': 0} color['F.Cu'] = {'r': 132, 'g': 0, 'b': 0} color['B.Cu'] = {'r': 0, 'g': 132, 'b': 0} color['F.Adhes'] = {'r': 132, 'g': 0, 'b': 132} color['B.Adhes'] = {'r': 0, 'g': 0, 'b': 132} color['F.Paste'] = {'r': 132, 'g': 0, 'b': 0} color['B.Paste'] = {'r': 0, 'g': 194, 'b': 194} color['F.SilkS'] = {'r': 0, 'g': 132, 'b': 132} color['B.SilkS'] = {'r': 132, 'g': 0, 'b': 132} color['F.Mask'] = {'r': 132, 'g': 0, 'b': 132} color['B.Mask'] = {'r': 132, 'g': 132, 'b': 0} color['Dwgs.User'] = {'r': 194, 'g': 194, 'b': 194} color['Cmts.User'] = {'r': 0, 'g': 0, 'b': 132} color['Eco1.User'] = {'r': 0, 'g': 132, 'b': 0} color['Eco2.user'] = {'r': 194, 'g': 194, 'b': 0} color['Egde.Cuts'] = {'r': 194, 'g': 194, 'b': 0} color['Margin'] = {'r': 194, 'g': 0, 'b': 194} color['F.CrtYd'] = {'r': 132, 'g': 132, 'b': 132} color['B.CrtYd'] = {'r': 0, 'g': 0, 'b': 0} color['F.Fab'] = {'r': 194, 'g': 194, 'b': 0} color['B.Fab'] = {'r': 132, 'g': 0, 'b': 0} draw_grid = (c, size, w, h) -> center_x = w / 2 center_y = h / 2 dots_x = parseInt(w / size) dots_x += dots_x % 2 dots_y = parseInt(h / size) dots_y += dots_y % 2 for x in [0..dots_x] for y in [0..dots_y] _x = x*size + center_x _y = y*size + center_y console.log("dot at #{_x},#{_y}") c.beginPath() c.strokeStyle = "rgba(132, 132, 132, 1)" c.arc(_x - dots_x / 2 * size, _y - dots_y / 2 * size, 1, 0, 2 * Math.PI, false) #c.lineWidth = 1 c.stroke() draw_fpline = (c, fpline) -> c.strokeStyle = "rgba(#{color[fpline['layer']]['r']}, #{color[fpline['layer']]['g']}, #{color[fpline['layer']]['b']}, 1)" c.lineWidth = fpline['width'] c.lineCap = 'square' c.beginPath() c.moveTo(fpline['x1'], fpline['y1']) c.lineTo(fpline['x2'], fpline['y2']) c.stroke() draw_fpcircle = (c, fpcircle) -> c.beginPath() c.strokeStyle = "rgba(#{color[fpcircle['layer']]['r']}, #{color[fpcircle['layer']]['g']}, #{color[fpcircle['layer']]['b']}, 1)" c.arc(fpcircle['center_x'], fpcircle['center_y'], fpcircle['radius'], 0, 2 * Math.PI, false) c.lineWidth = fpcircle['width'] c.stroke() draw_fparc = (c, fparc) -> # TODO: implement me! return draw_fptext = (c, fptext) -> # TODO: implement me! return draw_pad = (c, pad) -> if pad['shape'] == 'circle' c.beginPath() c.arc(pad['x'], pad['y'], pad['width'] / 2, 0, 2 * Math.PI, false) c.fillStyle = "rgba(#{color['B.Mask']['r']}, #{color['B.Mask']['g']}, #{color['B.Mask']['b']}, 1)" c.fill() #else if pad['shape'] == 'oval' # TODO: implement me! #c.beginPath() # #c.fillStyle = "rgba(#{color['B.Mask']['r']}, # #{color['B.Mask']['g']}, # #{color['B.Mask']['b']}, # 1)" #c.fill() else if pad['shape'] == 'rect' c.beginPath() c.fillRect(pad['x'], pad['y'], pad['width'], pad['height']) c.fillStyle = "rgba(#{color['B.Mask']['r']}, #{color['B.Mask']['g']}, #{color['B.Mask']['b']}, 1)" c.fill() if pad['type'] == 'thru_hole' c.beginPath() c.arc(pad['x'], pad['y'], pad['drill'] / 2, 0, 2 * Math.PI, false) c.fillStyle = "rgba(#{color['Bg']['r']}, #{color['Bg']['g']}, #{color['Bg']['b']}, 1)" c.fill() #else if pad['type'] == 'np_thru_hole' # TODO: implement me! #else if pad['type'] == 'smd' # TODO: implement me! if pad['num'] != '' c.beginPath() c.textAlign = 'center' c.textBaseline = 'middle' c.fillStyle = "rgba(#{color['Fg']['r']}, #{color['Fg']['g']}, #{color['Fg']['b']}, 1)" c.fillText(pad['num'], pad['x'], pad['y']) draw_footprint = (canvas, data) -> if canvas.getContext context = canvas.getContext('2d') # draw background context.fillStyle = "rgb(#{color['Bg']['r']}, #{color['Bg']['g']}, #{color['Bg']['b']})" context.fillRect(0, 0, canvas.width, canvas.height) # set outer boundaries of pretty file left = 0 top = 0 right = 0 bottom = 0 update_dimensions = (x, y) -> if parseFloat(x) < parseFloat(left) left = x else if parseFloat(x) > parseFloat(right) right = x if parseFloat(y) < parseFloat(bottom) bottom = y else if parseFloat(y) > parseFloat(top) top = y # save all lines in a list to draw them later fp_lines = [] fp_circles = [] fp_arcs = [] fp_texts = [] pads = [] # read pretty file prettylines = data.split('\n') for l in prettylines l = l.trim() regex_fpline = /\(fp_line\ \(start\ ([-.\d]*)\ ([-.\d]*)\)\ \(end\ ([-.\d]*)\ ([-.\d]*)\)\ \(layer\ ([.a-zA-Z]*)\)\ \(width\ ([-.\d]*)\)\)/g while((m = regex_fpline.exec(l)) != null) # TODO: forgot what the next 2 lines do.. if (m.index == regex_fpline.lastIndex) regex_fpline.lastIndex++ fp_line = {} fp_line['x1'] = parseFloat(m[1]) fp_line['y1'] = parseFloat(m[2]) fp_line['x2'] = parseFloat(m[3]) fp_line['y2'] = parseFloat(m[4]) fp_line['layer'] = m[5] fp_line['width'] = parseFloat(m[6]) update_dimensions(fp_line['x1'], fp_line['y1']) update_dimensions(fp_line['x2'], fp_line['y2']) fp_lines.push(fp_line) regex_fpcircle = /\(fp_circle\ \(center\ ([-.\d]+)\ ([-.\d]+)\)\ \(end\ ([-.\d]+)\ ([-.\d]+)\)\ \(layer\ ([.\w]+)\)\ \(width\ ([.\d]+)\)\)/g while((m = regex_fpcircle.exec(l)) != null) if(m.index == regex_fpcircle.astIndex) regex_fpcircle.lastIndex++ fp_circle = {} fp_circle['center_x'] = parseFloat(m[1]) fp_circle['center_y'] = parseFloat(m[2]) x = parseFloat(m[3]) y = parseFloat(m[4]) fp_circle['radius'] = Math.sqrt(Math.pow(fp_circle['center_x'] - x, 2) + Math.pow(fp_circle['center_y'] - y, 2)) fp_circle['layer'] = m[5] fp_circle['width'] = parseFloat(m[6]) update_dimensions(fp_circle['center_x'] - fp_circle['radius'], fp_circle['center_y'] - fp_circle['radius']) update_dimensions(fp_circle['center_x'] + fp_circle['radius'], fp_circle['center_y'] + fp_circle['radius']) fp_circles.push(fp_circle) regex_pad = /\(pad\ ([\d]*)\ ([_a-z]*)\ ([a-z]*)\ \(at\ ([-.\d]*)\ ([-.\d]*)\)\ \(size\ ([.\d]*)\ ([.\d]*)\)\ \(drill\ ([.\d]*)\)\ \(layers\ ([\w\d\s\.\*]*)\)\)/g while((m = regex_pad.exec(l)) != null) # TODO: forgot what the next 2 lines do.. if (m.index == regex_pad.lastIndex) regex_pad.lastIndex++ pad = {} pad['num'] = '' if m[1] != '""' pad['num'] = m[1] pad['type'] = m[2] pad['shape'] = m[3] pad['x'] = parseFloat(m[4]) pad['y'] = parseFloat(m[5]) pad['width'] = parseFloat(m[6]) pad['height'] = parseFloat(m[7]) pad['drill'] = parseFloat(m[8]) pad['layers'] = m[9].split(' ') update_dimensions(pad['x'] - pad['width'] / 2, pad['y'] - pad['height'] / 2) update_dimensions(pad['x'] + pad['width'] / 2, pad['y'] + pad['height'] / 2) pads.push(pad) console.log("DEBUG: found #{fp_lines.length} fp_lines") console.log("DEBUG: found #{fp_circles.length} fp_circles") console.log("DEBUG: found #{fp_arcs.length} fp_arcs") console.log("DEBUG: found #{fp_texts.length} fp_texts") console.log("DEBUG: found #{pads.length} pads") # calculate zoom factor cw = canvas.width / 2 ch = canvas.height / 2 maxw = Math.max(Math.abs(left), Math.abs(right)) maxh = Math.max(Math.abs(top), Math.abs(bottom)) zoom = Math.min((cw - 10) / maxw, (ch - 10) / maxh) console.log("DEBUG: max dimensions: left=#{left}; right=#{right}; top=#{top}; bottom=#{bottom}") console.log("DEBUG: zoom: #{zoom}") # draw everything draw_grid(context, 1.27 * zoom, canvas.width, canvas.height) for fpline in fp_lines # translate coords fpline['x1'] = fpline['x1'] * zoom + cw fpline['y1'] = fpline['y1'] * zoom + ch fpline['x2'] = fpline['x2'] * zoom + cw fpline['y2'] = fpline['y2'] * zoom + ch fpline['width'] *= zoom draw_fpline(context, fpline) for fpcircle in fp_circles fpcircle['center_x'] = fpcircle['center_x'] * zoom + cw fpcircle['center_y'] = fpcircle['center_y'] * zoom + ch fpcircle['radius'] *= zoom fpcircle['width'] *= zoom draw_fpcircle(context, fpcircle) for fparc in fp_arcs #fparc['center_x'] = fparc['center_x'] * zoom + cw #fparc['center_y'] = fparc['center_y'] * zoom + ch #fparc['width'] *= zoom draw_fparc(context, fparc) for fptext in fp_texts #fptext['center_x'] = fptext['center_x'] * zoom + cw #fptext['center_y'] = fptext['center_y'] * zoom + ch #fptext['width'] *= zoom draw_fptext(context, fptext) for pad in pads pad['x'] = pad['x'] * zoom + cw pad['y'] = pad['y'] * zoom + ch pad['width'] *= zoom pad['height'] *= zoom pad['drill'] *= zoom draw_pad(context, pad) Kicad = (canvas) -> data = {}; zoom = 0; this.render = () -> draw_footprint(canvas, data); this.load = (d) -> data = d; this.zoom = (level) -> zoom = zoom + level; render() return this if typeof(define) != 'undefined' define 'kicad', [], () -> return Kicad else if typeof(module) != 'undefined' && typeof(moule.exports) != 'undefined' module.exports = Kicad else if window window.Kicad = Kicad else if global global.Kicad = Kicad
true
# kicad.js v0.1.0 # (c) 2015 PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PIGi) Band color = {} color['Fg'] = {'r': 255, 'g': 255, 'b': 255} color['Bg'] = {'r': 0, 'g': 0, 'b': 0} color['F.Cu'] = {'r': 132, 'g': 0, 'b': 0} color['B.Cu'] = {'r': 0, 'g': 132, 'b': 0} color['F.Adhes'] = {'r': 132, 'g': 0, 'b': 132} color['B.Adhes'] = {'r': 0, 'g': 0, 'b': 132} color['F.Paste'] = {'r': 132, 'g': 0, 'b': 0} color['B.Paste'] = {'r': 0, 'g': 194, 'b': 194} color['F.SilkS'] = {'r': 0, 'g': 132, 'b': 132} color['B.SilkS'] = {'r': 132, 'g': 0, 'b': 132} color['F.Mask'] = {'r': 132, 'g': 0, 'b': 132} color['B.Mask'] = {'r': 132, 'g': 132, 'b': 0} color['Dwgs.User'] = {'r': 194, 'g': 194, 'b': 194} color['Cmts.User'] = {'r': 0, 'g': 0, 'b': 132} color['Eco1.User'] = {'r': 0, 'g': 132, 'b': 0} color['Eco2.user'] = {'r': 194, 'g': 194, 'b': 0} color['Egde.Cuts'] = {'r': 194, 'g': 194, 'b': 0} color['Margin'] = {'r': 194, 'g': 0, 'b': 194} color['F.CrtYd'] = {'r': 132, 'g': 132, 'b': 132} color['B.CrtYd'] = {'r': 0, 'g': 0, 'b': 0} color['F.Fab'] = {'r': 194, 'g': 194, 'b': 0} color['B.Fab'] = {'r': 132, 'g': 0, 'b': 0} draw_grid = (c, size, w, h) -> center_x = w / 2 center_y = h / 2 dots_x = parseInt(w / size) dots_x += dots_x % 2 dots_y = parseInt(h / size) dots_y += dots_y % 2 for x in [0..dots_x] for y in [0..dots_y] _x = x*size + center_x _y = y*size + center_y console.log("dot at #{_x},#{_y}") c.beginPath() c.strokeStyle = "rgba(132, 132, 132, 1)" c.arc(_x - dots_x / 2 * size, _y - dots_y / 2 * size, 1, 0, 2 * Math.PI, false) #c.lineWidth = 1 c.stroke() draw_fpline = (c, fpline) -> c.strokeStyle = "rgba(#{color[fpline['layer']]['r']}, #{color[fpline['layer']]['g']}, #{color[fpline['layer']]['b']}, 1)" c.lineWidth = fpline['width'] c.lineCap = 'square' c.beginPath() c.moveTo(fpline['x1'], fpline['y1']) c.lineTo(fpline['x2'], fpline['y2']) c.stroke() draw_fpcircle = (c, fpcircle) -> c.beginPath() c.strokeStyle = "rgba(#{color[fpcircle['layer']]['r']}, #{color[fpcircle['layer']]['g']}, #{color[fpcircle['layer']]['b']}, 1)" c.arc(fpcircle['center_x'], fpcircle['center_y'], fpcircle['radius'], 0, 2 * Math.PI, false) c.lineWidth = fpcircle['width'] c.stroke() draw_fparc = (c, fparc) -> # TODO: implement me! return draw_fptext = (c, fptext) -> # TODO: implement me! return draw_pad = (c, pad) -> if pad['shape'] == 'circle' c.beginPath() c.arc(pad['x'], pad['y'], pad['width'] / 2, 0, 2 * Math.PI, false) c.fillStyle = "rgba(#{color['B.Mask']['r']}, #{color['B.Mask']['g']}, #{color['B.Mask']['b']}, 1)" c.fill() #else if pad['shape'] == 'oval' # TODO: implement me! #c.beginPath() # #c.fillStyle = "rgba(#{color['B.Mask']['r']}, # #{color['B.Mask']['g']}, # #{color['B.Mask']['b']}, # 1)" #c.fill() else if pad['shape'] == 'rect' c.beginPath() c.fillRect(pad['x'], pad['y'], pad['width'], pad['height']) c.fillStyle = "rgba(#{color['B.Mask']['r']}, #{color['B.Mask']['g']}, #{color['B.Mask']['b']}, 1)" c.fill() if pad['type'] == 'thru_hole' c.beginPath() c.arc(pad['x'], pad['y'], pad['drill'] / 2, 0, 2 * Math.PI, false) c.fillStyle = "rgba(#{color['Bg']['r']}, #{color['Bg']['g']}, #{color['Bg']['b']}, 1)" c.fill() #else if pad['type'] == 'np_thru_hole' # TODO: implement me! #else if pad['type'] == 'smd' # TODO: implement me! if pad['num'] != '' c.beginPath() c.textAlign = 'center' c.textBaseline = 'middle' c.fillStyle = "rgba(#{color['Fg']['r']}, #{color['Fg']['g']}, #{color['Fg']['b']}, 1)" c.fillText(pad['num'], pad['x'], pad['y']) draw_footprint = (canvas, data) -> if canvas.getContext context = canvas.getContext('2d') # draw background context.fillStyle = "rgb(#{color['Bg']['r']}, #{color['Bg']['g']}, #{color['Bg']['b']})" context.fillRect(0, 0, canvas.width, canvas.height) # set outer boundaries of pretty file left = 0 top = 0 right = 0 bottom = 0 update_dimensions = (x, y) -> if parseFloat(x) < parseFloat(left) left = x else if parseFloat(x) > parseFloat(right) right = x if parseFloat(y) < parseFloat(bottom) bottom = y else if parseFloat(y) > parseFloat(top) top = y # save all lines in a list to draw them later fp_lines = [] fp_circles = [] fp_arcs = [] fp_texts = [] pads = [] # read pretty file prettylines = data.split('\n') for l in prettylines l = l.trim() regex_fpline = /\(fp_line\ \(start\ ([-.\d]*)\ ([-.\d]*)\)\ \(end\ ([-.\d]*)\ ([-.\d]*)\)\ \(layer\ ([.a-zA-Z]*)\)\ \(width\ ([-.\d]*)\)\)/g while((m = regex_fpline.exec(l)) != null) # TODO: forgot what the next 2 lines do.. if (m.index == regex_fpline.lastIndex) regex_fpline.lastIndex++ fp_line = {} fp_line['x1'] = parseFloat(m[1]) fp_line['y1'] = parseFloat(m[2]) fp_line['x2'] = parseFloat(m[3]) fp_line['y2'] = parseFloat(m[4]) fp_line['layer'] = m[5] fp_line['width'] = parseFloat(m[6]) update_dimensions(fp_line['x1'], fp_line['y1']) update_dimensions(fp_line['x2'], fp_line['y2']) fp_lines.push(fp_line) regex_fpcircle = /\(fp_circle\ \(center\ ([-.\d]+)\ ([-.\d]+)\)\ \(end\ ([-.\d]+)\ ([-.\d]+)\)\ \(layer\ ([.\w]+)\)\ \(width\ ([.\d]+)\)\)/g while((m = regex_fpcircle.exec(l)) != null) if(m.index == regex_fpcircle.astIndex) regex_fpcircle.lastIndex++ fp_circle = {} fp_circle['center_x'] = parseFloat(m[1]) fp_circle['center_y'] = parseFloat(m[2]) x = parseFloat(m[3]) y = parseFloat(m[4]) fp_circle['radius'] = Math.sqrt(Math.pow(fp_circle['center_x'] - x, 2) + Math.pow(fp_circle['center_y'] - y, 2)) fp_circle['layer'] = m[5] fp_circle['width'] = parseFloat(m[6]) update_dimensions(fp_circle['center_x'] - fp_circle['radius'], fp_circle['center_y'] - fp_circle['radius']) update_dimensions(fp_circle['center_x'] + fp_circle['radius'], fp_circle['center_y'] + fp_circle['radius']) fp_circles.push(fp_circle) regex_pad = /\(pad\ ([\d]*)\ ([_a-z]*)\ ([a-z]*)\ \(at\ ([-.\d]*)\ ([-.\d]*)\)\ \(size\ ([.\d]*)\ ([.\d]*)\)\ \(drill\ ([.\d]*)\)\ \(layers\ ([\w\d\s\.\*]*)\)\)/g while((m = regex_pad.exec(l)) != null) # TODO: forgot what the next 2 lines do.. if (m.index == regex_pad.lastIndex) regex_pad.lastIndex++ pad = {} pad['num'] = '' if m[1] != '""' pad['num'] = m[1] pad['type'] = m[2] pad['shape'] = m[3] pad['x'] = parseFloat(m[4]) pad['y'] = parseFloat(m[5]) pad['width'] = parseFloat(m[6]) pad['height'] = parseFloat(m[7]) pad['drill'] = parseFloat(m[8]) pad['layers'] = m[9].split(' ') update_dimensions(pad['x'] - pad['width'] / 2, pad['y'] - pad['height'] / 2) update_dimensions(pad['x'] + pad['width'] / 2, pad['y'] + pad['height'] / 2) pads.push(pad) console.log("DEBUG: found #{fp_lines.length} fp_lines") console.log("DEBUG: found #{fp_circles.length} fp_circles") console.log("DEBUG: found #{fp_arcs.length} fp_arcs") console.log("DEBUG: found #{fp_texts.length} fp_texts") console.log("DEBUG: found #{pads.length} pads") # calculate zoom factor cw = canvas.width / 2 ch = canvas.height / 2 maxw = Math.max(Math.abs(left), Math.abs(right)) maxh = Math.max(Math.abs(top), Math.abs(bottom)) zoom = Math.min((cw - 10) / maxw, (ch - 10) / maxh) console.log("DEBUG: max dimensions: left=#{left}; right=#{right}; top=#{top}; bottom=#{bottom}") console.log("DEBUG: zoom: #{zoom}") # draw everything draw_grid(context, 1.27 * zoom, canvas.width, canvas.height) for fpline in fp_lines # translate coords fpline['x1'] = fpline['x1'] * zoom + cw fpline['y1'] = fpline['y1'] * zoom + ch fpline['x2'] = fpline['x2'] * zoom + cw fpline['y2'] = fpline['y2'] * zoom + ch fpline['width'] *= zoom draw_fpline(context, fpline) for fpcircle in fp_circles fpcircle['center_x'] = fpcircle['center_x'] * zoom + cw fpcircle['center_y'] = fpcircle['center_y'] * zoom + ch fpcircle['radius'] *= zoom fpcircle['width'] *= zoom draw_fpcircle(context, fpcircle) for fparc in fp_arcs #fparc['center_x'] = fparc['center_x'] * zoom + cw #fparc['center_y'] = fparc['center_y'] * zoom + ch #fparc['width'] *= zoom draw_fparc(context, fparc) for fptext in fp_texts #fptext['center_x'] = fptext['center_x'] * zoom + cw #fptext['center_y'] = fptext['center_y'] * zoom + ch #fptext['width'] *= zoom draw_fptext(context, fptext) for pad in pads pad['x'] = pad['x'] * zoom + cw pad['y'] = pad['y'] * zoom + ch pad['width'] *= zoom pad['height'] *= zoom pad['drill'] *= zoom draw_pad(context, pad) Kicad = (canvas) -> data = {}; zoom = 0; this.render = () -> draw_footprint(canvas, data); this.load = (d) -> data = d; this.zoom = (level) -> zoom = zoom + level; render() return this if typeof(define) != 'undefined' define 'kicad', [], () -> return Kicad else if typeof(module) != 'undefined' && typeof(moule.exports) != 'undefined' module.exports = Kicad else if window window.Kicad = Kicad else if global global.Kicad = Kicad
[ { "context": "S: \"Tags\"\nPAGES: \"Pages\"\nPOSTS: \"Posts\"\nAUTHORS: \"Autoren\"\nSEARCH: \"Suche\"\nSEARCH_START: \"Type a keyword\"\nS", "end": 401, "score": 0.9919517040252686, "start": 394, "tag": "NAME", "value": "Autoren" }, { "context": "PAGES: \"Pages\"\nTITLE_POSTS: \"Pos...
src/i18n/de.cson
caiocrd/politicaemfoco-ionic
772
PULL_TO_REFRESH: "Ziehen zum Aktualisieren!" RETRY: "Wiederholen" CANCEL: "Cancel" SUBMIT: "Submit" BACK: "Zurück" ERROR: "Etwas ging schief. Bitte erneut versuchen." ATTEMPT_TO_CONNECT: "Verbinden: Versuch(e) {{attempt}} von {{attemptMax}}." OK: "Ok" YES: "Ja" NO: "Nein" EMPTY_LIST: "Keine Inhalte bisher!" MENU: "Menü" HOME: "Startseite" TAGS: "Tags" PAGES: "Pages" POSTS: "Posts" AUTHORS: "Autoren" SEARCH: "Suche" SEARCH_START: "Type a keyword" SOCIAL_NETWORKS: "Soziale Netzwerke" CATEGORIES: "Kategorien" SETTINGS: "Einstellungen" ZOOM: "Zoom" FEATURED: "Hervorgehoben" OPEN_IN_BROWSER: "Im Browser öffnen" ABOUT: "Über" COMMENTS: "Kommentare" CUSTOM_POSTS: "Custom posts" CUSTOM_TAXO: "Custom Taxonomy" CUSTOM_TAXO_TITLE: "{{term}}: {{name}}" PUSH_NOTIFS: "Push notifications" PUSH_NOTIF_TITLE: "Neue Inhalte!" PUSH_NOTIF_TEXT: "Neu! Seite/Beitrag: '{{postTitle}}' wurde in {{appTitle}} veröffentlich, willst du es dir jetzt ansehen?" BOOKMARKS: "Lesenzeichen" BOOKMARKS_EMPTY: "Bisher noch nichts gespeichert!" BOOKMARK_ADDED : "Lesezeichen gespeichert!" BOOKMARK_REMOVED: "Lesezeichen gelöscht!" CACHE_CLEAR: "Clear cache" CACHE_CLEAR_PROMPT: "This cannot be undone!" CACHE_CLEARED: "Cache cleared" TITLE_TAGS: "Tags" TITLE_TAG: "Tag: {{name}}" TITLE_CATEGORIES: "Kategorien" TITLE_CATEGORY: "Kategorie: {{name}}" TITLE_HOME: "Startseite" TITLE_SEARCH: "Suche" TITLE_PAGES: "Pages" TITLE_POSTS: "Posts" TITLE_USERS: "Autoren" TITLE_USER: "Autor" TITLE_USER_POSTS: "Autor: {{name}}" SHARE_SUCCESS: "Geteilt!" SHARE_ERROR: "Sharing failed"
160314
PULL_TO_REFRESH: "Ziehen zum Aktualisieren!" RETRY: "Wiederholen" CANCEL: "Cancel" SUBMIT: "Submit" BACK: "Zurück" ERROR: "Etwas ging schief. Bitte erneut versuchen." ATTEMPT_TO_CONNECT: "Verbinden: Versuch(e) {{attempt}} von {{attemptMax}}." OK: "Ok" YES: "Ja" NO: "Nein" EMPTY_LIST: "Keine Inhalte bisher!" MENU: "Menü" HOME: "Startseite" TAGS: "Tags" PAGES: "Pages" POSTS: "Posts" AUTHORS: "<NAME>" SEARCH: "Suche" SEARCH_START: "Type a keyword" SOCIAL_NETWORKS: "Soziale Netzwerke" CATEGORIES: "Kategorien" SETTINGS: "Einstellungen" ZOOM: "Zoom" FEATURED: "Hervorgehoben" OPEN_IN_BROWSER: "Im Browser öffnen" ABOUT: "Über" COMMENTS: "Kommentare" CUSTOM_POSTS: "Custom posts" CUSTOM_TAXO: "Custom Taxonomy" CUSTOM_TAXO_TITLE: "{{term}}: {{name}}" PUSH_NOTIFS: "Push notifications" PUSH_NOTIF_TITLE: "Neue Inhalte!" PUSH_NOTIF_TEXT: "Neu! Seite/Beitrag: '{{postTitle}}' wurde in {{appTitle}} veröffentlich, willst du es dir jetzt ansehen?" BOOKMARKS: "Lesenzeichen" BOOKMARKS_EMPTY: "Bisher noch nichts gespeichert!" BOOKMARK_ADDED : "Lesezeichen gespeichert!" BOOKMARK_REMOVED: "Lesezeichen gelöscht!" CACHE_CLEAR: "Clear cache" CACHE_CLEAR_PROMPT: "This cannot be undone!" CACHE_CLEARED: "Cache cleared" TITLE_TAGS: "Tags" TITLE_TAG: "Tag: {{name}}" TITLE_CATEGORIES: "Kategorien" TITLE_CATEGORY: "Kategorie: {{name}}" TITLE_HOME: "Startseite" TITLE_SEARCH: "Suche" TITLE_PAGES: "Pages" TITLE_POSTS: "Posts" TITLE_USERS: "Aut<NAME>" TITLE_USER: "<NAME>" TITLE_USER_POSTS: "Autor: {{name}}" SHARE_SUCCESS: "Geteilt!" SHARE_ERROR: "Sharing failed"
true
PULL_TO_REFRESH: "Ziehen zum Aktualisieren!" RETRY: "Wiederholen" CANCEL: "Cancel" SUBMIT: "Submit" BACK: "Zurück" ERROR: "Etwas ging schief. Bitte erneut versuchen." ATTEMPT_TO_CONNECT: "Verbinden: Versuch(e) {{attempt}} von {{attemptMax}}." OK: "Ok" YES: "Ja" NO: "Nein" EMPTY_LIST: "Keine Inhalte bisher!" MENU: "Menü" HOME: "Startseite" TAGS: "Tags" PAGES: "Pages" POSTS: "Posts" AUTHORS: "PI:NAME:<NAME>END_PI" SEARCH: "Suche" SEARCH_START: "Type a keyword" SOCIAL_NETWORKS: "Soziale Netzwerke" CATEGORIES: "Kategorien" SETTINGS: "Einstellungen" ZOOM: "Zoom" FEATURED: "Hervorgehoben" OPEN_IN_BROWSER: "Im Browser öffnen" ABOUT: "Über" COMMENTS: "Kommentare" CUSTOM_POSTS: "Custom posts" CUSTOM_TAXO: "Custom Taxonomy" CUSTOM_TAXO_TITLE: "{{term}}: {{name}}" PUSH_NOTIFS: "Push notifications" PUSH_NOTIF_TITLE: "Neue Inhalte!" PUSH_NOTIF_TEXT: "Neu! Seite/Beitrag: '{{postTitle}}' wurde in {{appTitle}} veröffentlich, willst du es dir jetzt ansehen?" BOOKMARKS: "Lesenzeichen" BOOKMARKS_EMPTY: "Bisher noch nichts gespeichert!" BOOKMARK_ADDED : "Lesezeichen gespeichert!" BOOKMARK_REMOVED: "Lesezeichen gelöscht!" CACHE_CLEAR: "Clear cache" CACHE_CLEAR_PROMPT: "This cannot be undone!" CACHE_CLEARED: "Cache cleared" TITLE_TAGS: "Tags" TITLE_TAG: "Tag: {{name}}" TITLE_CATEGORIES: "Kategorien" TITLE_CATEGORY: "Kategorie: {{name}}" TITLE_HOME: "Startseite" TITLE_SEARCH: "Suche" TITLE_PAGES: "Pages" TITLE_POSTS: "Posts" TITLE_USERS: "AutPI:NAME:<NAME>END_PI" TITLE_USER: "PI:NAME:<NAME>END_PI" TITLE_USER_POSTS: "Autor: {{name}}" SHARE_SUCCESS: "Geteilt!" SHARE_ERROR: "Sharing failed"
[ { "context": "gs\n\n api\n) ->\n\n ###*\n # @author David Bouman\n # @module App\n # @submodule ", "end": 584, "score": 0.9998652935028076, "start": 572, "tag": "NAME", "value": "David Bouman" } ]
generators/app/templates/src/models/settings-environment.coffee
marviq/generator-bat
3
'use strict' ( ( factory ) -> if typeof exports is 'object' module.exports = factory( require( 'backbone' ) require( 'bluebird' ) require( 'madlib-settings' ) require( './../apis/env.coffee' ) ) else if typeof define is 'function' and define.amd define( [ 'backbone' 'bluebird' 'madlib-settings' './../apis/env.coffee' ], factory ) return )(( Backbone Promise settings api ) -> ###* # @author David Bouman # @module App # @submodule Models ### ## Stamped logs ## log = ( args... ) -> console.log( '[SETTINGS]', args... ) ###* # Settings for the target environment. # # @class SettingsEnvironmentModel # @extends Backbone.Model # @static ### class SettingsEnvironmentModel extends Backbone.Model ###* # List of [valid attribute names](#attrs). # # @property schema # @type Array[String] # @final ### ###* # A mapping of API names to their base URLs. For each API, the URL endpoints of its services will be assumed to be relative to the base # URLs laid out here. # # @attribute api # @type Object ### ###* # The name of the environment that these settings target. Useful values include: # # * `'local'` # * `'testing'` # * `'acceptance'` # * `'production'` # # @attribute environment # @type String ###<% if ( i18n ) { %> ###* # All available locales. # # The value is an object, mapping [BCP 47 language tags](https://tools.ietf.org/html/bcp47) to pre-localized language names. # Pre-localization includes that the language name be written in, and capitalized according to that locale's language and rules. # # The [language tag](https://tools.ietf.org/html/bcp47#section-2) should include these, and -only- these parts: # # * A single primary language subtag based on a two-letter language code from # [ISO 639-1 (2002)](https://en.wikipedia.org/wiki/ISO_639-1). # # * A optional region subtag based on a two-letter country code from # [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) (usually written in upper case). # # See also: [IETF language tags](https://en.wikipedia.org/wiki/IETF_language_tag#Syntax_of_language_tags). # # @attribute locales # @type Object ###<% } %> schema: [ 'api' 'environment'<% if ( i18n ) { %> 'locales'<% } %> ] ###* # Service API endpoint; defined in the {{#crossLink 'EnvApi/settingsEnvironment:attribute'}}`EnvApi`{{/crossLink}}. # # @property url # @type ApiServiceModel # @final # # @default '<EnvApi.url>/settings.json' ### url: api.get( 'settingsEnvironment' ) ###* # @method initialize # @protected ### initialize: () -> ###* # A `Promise` that the environment settings will have been loaded and initialized on the `madlib-settings` singleton object. # # @property initialized # @type Promise # @final ### @initialized = Promise.resolve( @fetch( cache: false ) ).then( ( attributes ) => ### jshint unused: false ### ###* # The target-environment's settings. # # @attribute environment # @for Settings # @type Object ### ###* # A mapping of API names to their base URLs. For each API, the URL endpoints of its services will be assumed to be # relative to the base URLs laid out here. # # @attribute environment.api # @for Settings # @type Object # @final ### ###* # The name of the environment that these settings target. Useful values include: # # * `'local'` # * `'testing'` # * `'acceptance'` # * `'production'` # # @attribute environment.environment # @for Settings # @type String # @final ###<% if ( i18n ) { %> ###* # All available locales. # # The value is an object, mapping [BCP 47 language tags](https://tools.ietf.org/html/bcp47) to pre-localized language names. # Pre-localization includes that the language name be written in, and capitalized according to that locale's language and rules. # # The [language tag](https://tools.ietf.org/html/bcp47#section-2) should include these, and -only- these parts: # # * A single primary language subtag based on a two-letter language code from # [ISO 639-1 (2002)](https://en.wikipedia.org/wiki/ISO_639-1). # # * A optional region subtag based on a two-letter country code from # [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) (usually written in upper case). # # See also: [IETF language tags](https://en.wikipedia.org/wiki/IETF_language_tag#Syntax_of_language_tags). # # @attribute environment.locales # @for Settings # @type Object # @final ###<% } %> settings.init( 'environment', @attributes ) environment = settings.get( 'environment.environment' ) log( "Environment settings loaded for \"#{environment}\" target." ) return @ ( jqXHR ) -> ### jshint unused: false ### message = 'Unable to load target environment settings.' log( message ) throw new Error( message ) ) return ## Export singleton. ## return new SettingsEnvironmentModel() )
167890
'use strict' ( ( factory ) -> if typeof exports is 'object' module.exports = factory( require( 'backbone' ) require( 'bluebird' ) require( 'madlib-settings' ) require( './../apis/env.coffee' ) ) else if typeof define is 'function' and define.amd define( [ 'backbone' 'bluebird' 'madlib-settings' './../apis/env.coffee' ], factory ) return )(( Backbone Promise settings api ) -> ###* # @author <NAME> # @module App # @submodule Models ### ## Stamped logs ## log = ( args... ) -> console.log( '[SETTINGS]', args... ) ###* # Settings for the target environment. # # @class SettingsEnvironmentModel # @extends Backbone.Model # @static ### class SettingsEnvironmentModel extends Backbone.Model ###* # List of [valid attribute names](#attrs). # # @property schema # @type Array[String] # @final ### ###* # A mapping of API names to their base URLs. For each API, the URL endpoints of its services will be assumed to be relative to the base # URLs laid out here. # # @attribute api # @type Object ### ###* # The name of the environment that these settings target. Useful values include: # # * `'local'` # * `'testing'` # * `'acceptance'` # * `'production'` # # @attribute environment # @type String ###<% if ( i18n ) { %> ###* # All available locales. # # The value is an object, mapping [BCP 47 language tags](https://tools.ietf.org/html/bcp47) to pre-localized language names. # Pre-localization includes that the language name be written in, and capitalized according to that locale's language and rules. # # The [language tag](https://tools.ietf.org/html/bcp47#section-2) should include these, and -only- these parts: # # * A single primary language subtag based on a two-letter language code from # [ISO 639-1 (2002)](https://en.wikipedia.org/wiki/ISO_639-1). # # * A optional region subtag based on a two-letter country code from # [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) (usually written in upper case). # # See also: [IETF language tags](https://en.wikipedia.org/wiki/IETF_language_tag#Syntax_of_language_tags). # # @attribute locales # @type Object ###<% } %> schema: [ 'api' 'environment'<% if ( i18n ) { %> 'locales'<% } %> ] ###* # Service API endpoint; defined in the {{#crossLink 'EnvApi/settingsEnvironment:attribute'}}`EnvApi`{{/crossLink}}. # # @property url # @type ApiServiceModel # @final # # @default '<EnvApi.url>/settings.json' ### url: api.get( 'settingsEnvironment' ) ###* # @method initialize # @protected ### initialize: () -> ###* # A `Promise` that the environment settings will have been loaded and initialized on the `madlib-settings` singleton object. # # @property initialized # @type Promise # @final ### @initialized = Promise.resolve( @fetch( cache: false ) ).then( ( attributes ) => ### jshint unused: false ### ###* # The target-environment's settings. # # @attribute environment # @for Settings # @type Object ### ###* # A mapping of API names to their base URLs. For each API, the URL endpoints of its services will be assumed to be # relative to the base URLs laid out here. # # @attribute environment.api # @for Settings # @type Object # @final ### ###* # The name of the environment that these settings target. Useful values include: # # * `'local'` # * `'testing'` # * `'acceptance'` # * `'production'` # # @attribute environment.environment # @for Settings # @type String # @final ###<% if ( i18n ) { %> ###* # All available locales. # # The value is an object, mapping [BCP 47 language tags](https://tools.ietf.org/html/bcp47) to pre-localized language names. # Pre-localization includes that the language name be written in, and capitalized according to that locale's language and rules. # # The [language tag](https://tools.ietf.org/html/bcp47#section-2) should include these, and -only- these parts: # # * A single primary language subtag based on a two-letter language code from # [ISO 639-1 (2002)](https://en.wikipedia.org/wiki/ISO_639-1). # # * A optional region subtag based on a two-letter country code from # [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) (usually written in upper case). # # See also: [IETF language tags](https://en.wikipedia.org/wiki/IETF_language_tag#Syntax_of_language_tags). # # @attribute environment.locales # @for Settings # @type Object # @final ###<% } %> settings.init( 'environment', @attributes ) environment = settings.get( 'environment.environment' ) log( "Environment settings loaded for \"#{environment}\" target." ) return @ ( jqXHR ) -> ### jshint unused: false ### message = 'Unable to load target environment settings.' log( message ) throw new Error( message ) ) return ## Export singleton. ## return new SettingsEnvironmentModel() )
true
'use strict' ( ( factory ) -> if typeof exports is 'object' module.exports = factory( require( 'backbone' ) require( 'bluebird' ) require( 'madlib-settings' ) require( './../apis/env.coffee' ) ) else if typeof define is 'function' and define.amd define( [ 'backbone' 'bluebird' 'madlib-settings' './../apis/env.coffee' ], factory ) return )(( Backbone Promise settings api ) -> ###* # @author PI:NAME:<NAME>END_PI # @module App # @submodule Models ### ## Stamped logs ## log = ( args... ) -> console.log( '[SETTINGS]', args... ) ###* # Settings for the target environment. # # @class SettingsEnvironmentModel # @extends Backbone.Model # @static ### class SettingsEnvironmentModel extends Backbone.Model ###* # List of [valid attribute names](#attrs). # # @property schema # @type Array[String] # @final ### ###* # A mapping of API names to their base URLs. For each API, the URL endpoints of its services will be assumed to be relative to the base # URLs laid out here. # # @attribute api # @type Object ### ###* # The name of the environment that these settings target. Useful values include: # # * `'local'` # * `'testing'` # * `'acceptance'` # * `'production'` # # @attribute environment # @type String ###<% if ( i18n ) { %> ###* # All available locales. # # The value is an object, mapping [BCP 47 language tags](https://tools.ietf.org/html/bcp47) to pre-localized language names. # Pre-localization includes that the language name be written in, and capitalized according to that locale's language and rules. # # The [language tag](https://tools.ietf.org/html/bcp47#section-2) should include these, and -only- these parts: # # * A single primary language subtag based on a two-letter language code from # [ISO 639-1 (2002)](https://en.wikipedia.org/wiki/ISO_639-1). # # * A optional region subtag based on a two-letter country code from # [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) (usually written in upper case). # # See also: [IETF language tags](https://en.wikipedia.org/wiki/IETF_language_tag#Syntax_of_language_tags). # # @attribute locales # @type Object ###<% } %> schema: [ 'api' 'environment'<% if ( i18n ) { %> 'locales'<% } %> ] ###* # Service API endpoint; defined in the {{#crossLink 'EnvApi/settingsEnvironment:attribute'}}`EnvApi`{{/crossLink}}. # # @property url # @type ApiServiceModel # @final # # @default '<EnvApi.url>/settings.json' ### url: api.get( 'settingsEnvironment' ) ###* # @method initialize # @protected ### initialize: () -> ###* # A `Promise` that the environment settings will have been loaded and initialized on the `madlib-settings` singleton object. # # @property initialized # @type Promise # @final ### @initialized = Promise.resolve( @fetch( cache: false ) ).then( ( attributes ) => ### jshint unused: false ### ###* # The target-environment's settings. # # @attribute environment # @for Settings # @type Object ### ###* # A mapping of API names to their base URLs. For each API, the URL endpoints of its services will be assumed to be # relative to the base URLs laid out here. # # @attribute environment.api # @for Settings # @type Object # @final ### ###* # The name of the environment that these settings target. Useful values include: # # * `'local'` # * `'testing'` # * `'acceptance'` # * `'production'` # # @attribute environment.environment # @for Settings # @type String # @final ###<% if ( i18n ) { %> ###* # All available locales. # # The value is an object, mapping [BCP 47 language tags](https://tools.ietf.org/html/bcp47) to pre-localized language names. # Pre-localization includes that the language name be written in, and capitalized according to that locale's language and rules. # # The [language tag](https://tools.ietf.org/html/bcp47#section-2) should include these, and -only- these parts: # # * A single primary language subtag based on a two-letter language code from # [ISO 639-1 (2002)](https://en.wikipedia.org/wiki/ISO_639-1). # # * A optional region subtag based on a two-letter country code from # [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) (usually written in upper case). # # See also: [IETF language tags](https://en.wikipedia.org/wiki/IETF_language_tag#Syntax_of_language_tags). # # @attribute environment.locales # @for Settings # @type Object # @final ###<% } %> settings.init( 'environment', @attributes ) environment = settings.get( 'environment.environment' ) log( "Environment settings loaded for \"#{environment}\" target." ) return @ ( jqXHR ) -> ### jshint unused: false ### message = 'Unable to load target environment settings.' log( message ) throw new Error( message ) ) return ## Export singleton. ## return new SettingsEnvironmentModel() )
[ { "context": "'<%= version %>'\n github:\n repo: 'linemanjs/lineman'\n usernameVar: 'GITHUB_USERNAME'", "end": 574, "score": 0.9529964923858643, "start": 565, "tag": "USERNAME", "value": "linemanjs" }, { "context": "repo: 'linemanjs/lineman'\n userna...
Gruntfile.internal.coffee
hairstonm/lunchPad
304
#global module:false # Note: this Gruntfile is only for lineman's internal development # and, unlike almost everything else to do with Grunt, is not intended # for use by people's Lineman projects. # # Running internal grunt commands requires the --gruntfile option # # $ grunt release --gruntfile Gruntfile.internal.coffee --no-write module.exports = (grunt) -> grunt.loadNpmTasks('grunt-release') grunt.initConfig release: options: commitMessage: '<%= version %>' tagMessage: '<%= version %>' github: repo: 'linemanjs/lineman' usernameVar: 'GITHUB_USERNAME' passwordVar: 'GITHUB_PASSWORD'
146669
#global module:false # Note: this Gruntfile is only for lineman's internal development # and, unlike almost everything else to do with Grunt, is not intended # for use by people's Lineman projects. # # Running internal grunt commands requires the --gruntfile option # # $ grunt release --gruntfile Gruntfile.internal.coffee --no-write module.exports = (grunt) -> grunt.loadNpmTasks('grunt-release') grunt.initConfig release: options: commitMessage: '<%= version %>' tagMessage: '<%= version %>' github: repo: 'linemanjs/lineman' usernameVar: 'GITHUB_USERNAME' passwordVar: '<PASSWORD>'
true
#global module:false # Note: this Gruntfile is only for lineman's internal development # and, unlike almost everything else to do with Grunt, is not intended # for use by people's Lineman projects. # # Running internal grunt commands requires the --gruntfile option # # $ grunt release --gruntfile Gruntfile.internal.coffee --no-write module.exports = (grunt) -> grunt.loadNpmTasks('grunt-release') grunt.initConfig release: options: commitMessage: '<%= version %>' tagMessage: '<%= version %>' github: repo: 'linemanjs/lineman' usernameVar: 'GITHUB_USERNAME' passwordVar: 'PI:PASSWORD:<PASSWORD>END_PI'
[ { "context": "cloud_controller.write\",\"scim.read\",\"scim.write\",\"password.write\"]\n\nJSO.enablejQuery($);\njso = new JSO(opts);\n\njso", "end": 592, "score": 0.9123091697692871, "start": 578, "tag": "PASSWORD", "value": "password.write" }, { "context": "cloud_controller.write\"...
public/scripts/CfUsersBootstrap.coffee
MonsantoCo/cf-users
14
jQuery = require 'jquery' Router = require "./Router" JSO = require "./lib/jso/jso" q = document.URL.split("?") query = {} if(q.length>1) for pair in q[1].split('&') nameValue = pair.split('=') query[nameValue[0]] = nameValue[1] path = q[0].split('/') opts = provider : "smarf" response_type:"code" client_id: "cf_portal_client" redirect_uri: "https://#{location.host}/cf-users/roles" authorization : "https://#{window.loginDomain}/oauth/authorize" scopes : request :["openid","cloud_controller.read","cloud_controller.write","scim.read","scim.write","password.write"] JSO.enablejQuery($); jso = new JSO(opts); jso.callback(); jso.getToken (token) -> ajaxSettings = oauth: scopes : request :["openid","cloud_controller.read","cloud_controller.write","scim.read","scim.write","password.write" ] datatype: 'jsonp' headers : Authorization : "Bearer " + token.access_token $.ajaxSetup ajaxSettings $(document). ready () -> router = new Router({host: "#{location.host}", page:"#{path[path.length-1]}", query : query, jso: jso}) , opts
62679
jQuery = require 'jquery' Router = require "./Router" JSO = require "./lib/jso/jso" q = document.URL.split("?") query = {} if(q.length>1) for pair in q[1].split('&') nameValue = pair.split('=') query[nameValue[0]] = nameValue[1] path = q[0].split('/') opts = provider : "smarf" response_type:"code" client_id: "cf_portal_client" redirect_uri: "https://#{location.host}/cf-users/roles" authorization : "https://#{window.loginDomain}/oauth/authorize" scopes : request :["openid","cloud_controller.read","cloud_controller.write","scim.read","scim.write","<PASSWORD>"] JSO.enablejQuery($); jso = new JSO(opts); jso.callback(); jso.getToken (token) -> ajaxSettings = oauth: scopes : request :["openid","cloud_controller.read","cloud_controller.write","scim.read","scim.write","<PASSWORD>" ] datatype: 'jsonp' headers : Authorization : "Bearer " + token.access_token $.ajaxSetup ajaxSettings $(document). ready () -> router = new Router({host: "#{location.host}", page:"#{path[path.length-1]}", query : query, jso: jso}) , opts
true
jQuery = require 'jquery' Router = require "./Router" JSO = require "./lib/jso/jso" q = document.URL.split("?") query = {} if(q.length>1) for pair in q[1].split('&') nameValue = pair.split('=') query[nameValue[0]] = nameValue[1] path = q[0].split('/') opts = provider : "smarf" response_type:"code" client_id: "cf_portal_client" redirect_uri: "https://#{location.host}/cf-users/roles" authorization : "https://#{window.loginDomain}/oauth/authorize" scopes : request :["openid","cloud_controller.read","cloud_controller.write","scim.read","scim.write","PI:PASSWORD:<PASSWORD>END_PI"] JSO.enablejQuery($); jso = new JSO(opts); jso.callback(); jso.getToken (token) -> ajaxSettings = oauth: scopes : request :["openid","cloud_controller.read","cloud_controller.write","scim.read","scim.write","PI:PASSWORD:<PASSWORD>END_PI" ] datatype: 'jsonp' headers : Authorization : "Bearer " + token.access_token $.ajaxSetup ajaxSettings $(document). ready () -> router = new Router({host: "#{location.host}", page:"#{path[path.length-1]}", query : query, jso: jso}) , opts
[ { "context": "rary\" : {\n \"identifier\" : {\n \"id\" : \"TestSnippet\",\n \"version\" : \"1\"\n },\n ", "end": 405, "score": 0.8880183696746826, "start": 401, "tag": "NAME", "value": "Test" }, { "context": "s\" : {\n \"def\" : [ {\n ...
Src/coffeescript/cql-execution/test/elm/reusable/data.coffee
MeasureAuthoringTool/clinical_quality_language
2
### WARNING: This is a GENERATED file. Do not manually edit! To generate this file: - Edit data.coffee to add a CQL Snippet - From java dir: ./gradlew :cql-to-elm:generateTestData ### ### ExpressionDef library TestSnippet version '1' using QUICK context Patient define Foo: 'Bar' ### module.exports['ExpressionDef'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "Foo", "context" : "Patient", "accessLevel" : "Public", "expression" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "Bar", "type" : "Literal" } } ] } } } ### ExpressionRef library TestSnippet version '1' using QUICK context Patient define Life: 42 define Foo: Life ### module.exports['ExpressionRef'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "Life", "context" : "Patient", "accessLevel" : "Public", "expression" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "42", "type" : "Literal" } }, { "name" : "Foo", "context" : "Patient", "accessLevel" : "Public", "expression" : { "name" : "Life", "type" : "ExpressionRef" } } ] } } } ### FunctionDefinitions library TestSnippet version '1' using QUICK context Patient define function foo (a Integer, b Integer) : a + b define testValue: foo(1,2) ### module.exports['FunctionDefinitions'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "foo", "context" : "Patient", "accessLevel" : "Public", "type" : "FunctionDef", "expression" : { "type" : "Add", "operand" : [ { "name" : "a", "type" : "OperandRef" }, { "name" : "b", "type" : "OperandRef" } ] }, "operand" : [ { "name" : "a", "operandTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } }, { "name" : "b", "operandTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] }, { "name" : "testValue", "context" : "Patient", "accessLevel" : "Public", "expression" : { "name" : "foo", "type" : "FunctionRef", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } } ] } } } ### FunctionOverloads library TestSnippet version '1' using QUICK context Patient define function foo (a System.Integer) : a + 1 define function foo (a System.String) : 'Hello ' + a define testValue1: foo(1) define testValue2: foo('World') ### module.exports['FunctionOverloads'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "Patient", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "foo", "context" : "Patient", "accessLevel" : "Public", "type" : "FunctionDef", "expression" : { "type" : "Add", "operand" : [ { "name" : "a", "type" : "OperandRef" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] }, "operand" : [ { "name" : "a", "operandTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] }, { "name" : "foo", "context" : "Patient", "accessLevel" : "Public", "type" : "FunctionDef", "expression" : { "type" : "Concatenate", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "Hello ", "type" : "Literal" }, { "name" : "a", "type" : "OperandRef" } ] }, "operand" : [ { "name" : "a", "operandTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}String", "type" : "NamedTypeSpecifier" } } ] }, { "name" : "testValue1", "context" : "Patient", "accessLevel" : "Public", "expression" : { "name" : "foo", "type" : "FunctionRef", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } }, { "name" : "testValue2", "context" : "Patient", "accessLevel" : "Public", "expression" : { "name" : "foo", "type" : "FunctionRef", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "World", "type" : "Literal" } ] } } ] } } }
202858
### WARNING: This is a GENERATED file. Do not manually edit! To generate this file: - Edit data.coffee to add a CQL Snippet - From java dir: ./gradlew :cql-to-elm:generateTestData ### ### ExpressionDef library TestSnippet version '1' using QUICK context Patient define Foo: 'Bar' ### module.exports['ExpressionDef'] = { "library" : { "identifier" : { "id" : "<NAME>Snippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "Bar", "type" : "Literal" } } ] } } } ### ExpressionRef library TestSnippet version '1' using QUICK context Patient define Life: 42 define Foo: Life ### module.exports['ExpressionRef'] = { "library" : { "identifier" : { "id" : "<NAME>Snippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "42", "type" : "Literal" } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "name" : "<NAME>", "type" : "ExpressionRef" } } ] } } } ### FunctionDefinitions library TestSnippet version '1' using QUICK context Patient define function foo (a Integer, b Integer) : a + b define testValue: foo(1,2) ### module.exports['FunctionDefinitions'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "type" : "FunctionDef", "expression" : { "type" : "Add", "operand" : [ { "name" : "<NAME>", "type" : "OperandRef" }, { "name" : "<NAME>", "type" : "OperandRef" } ] }, "operand" : [ { "name" : "<NAME>", "operandTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } }, { "name" : "<NAME>", "operandTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } } ] } } } ### FunctionOverloads library TestSnippet version '1' using QUICK context Patient define function foo (a System.Integer) : a + 1 define function foo (a System.String) : 'Hello ' + a define testValue1: foo(1) define testValue2: foo('World') ### module.exports['FunctionOverloads'] = { "library" : { "identifier" : { "id" : "<NAME>Snippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "<NAME>", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "type" : "FunctionDef", "expression" : { "type" : "Add", "operand" : [ { "name" : "a", "type" : "OperandRef" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] }, "operand" : [ { "name" : "a", "operandTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] }, { "name" : "<NAME>", "context" : "Patient", "accessLevel" : "Public", "type" : "FunctionDef", "expression" : { "type" : "Concatenate", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "Hello ", "type" : "Literal" }, { "name" : "<NAME>", "type" : "OperandRef" } ] }, "operand" : [ { "name" : "a", "operandTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}String", "type" : "NamedTypeSpecifier" } } ] }, { "name" : "<NAME>Value<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } }, { "name" : "<NAME>Value<NAME>", "context" : "Patient", "accessLevel" : "Public", "expression" : { "name" : "<NAME>", "type" : "FunctionRef", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "World", "type" : "Literal" } ] } } ] } } }
true
### WARNING: This is a GENERATED file. Do not manually edit! To generate this file: - Edit data.coffee to add a CQL Snippet - From java dir: ./gradlew :cql-to-elm:generateTestData ### ### ExpressionDef library TestSnippet version '1' using QUICK context Patient define Foo: 'Bar' ### module.exports['ExpressionDef'] = { "library" : { "identifier" : { "id" : "PI:NAME:<NAME>END_PISnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "Bar", "type" : "Literal" } } ] } } } ### ExpressionRef library TestSnippet version '1' using QUICK context Patient define Life: 42 define Foo: Life ### module.exports['ExpressionRef'] = { "library" : { "identifier" : { "id" : "PI:NAME:<NAME>END_PISnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "42", "type" : "Literal" } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "ExpressionRef" } } ] } } } ### FunctionDefinitions library TestSnippet version '1' using QUICK context Patient define function foo (a Integer, b Integer) : a + b define testValue: foo(1,2) ### module.exports['FunctionDefinitions'] = { "library" : { "identifier" : { "id" : "TestSnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "type" : "FunctionDef", "expression" : { "type" : "Add", "operand" : [ { "name" : "PI:NAME:<NAME>END_PI", "type" : "OperandRef" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "OperandRef" } ] }, "operand" : [ { "name" : "PI:NAME:<NAME>END_PI", "operandTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } }, { "name" : "PI:NAME:<NAME>END_PI", "operandTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "2", "type" : "Literal" } ] } } ] } } } ### FunctionOverloads library TestSnippet version '1' using QUICK context Patient define function foo (a System.Integer) : a + 1 define function foo (a System.String) : 'Hello ' + a define testValue1: foo(1) define testValue2: foo('World') ### module.exports['FunctionOverloads'] = { "library" : { "identifier" : { "id" : "PI:NAME:<NAME>END_PISnippet", "version" : "1" }, "schemaIdentifier" : { "id" : "urn:hl7-org:elm", "version" : "r1" }, "usings" : { "def" : [ { "localIdentifier" : "System", "uri" : "urn:hl7-org:elm-types:r1" }, { "localIdentifier" : "QUICK", "uri" : "http://hl7.org/fhir" } ] }, "statements" : { "def" : [ { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "expression" : { "type" : "SingletonFrom", "operand" : { "dataType" : "{http://hl7.org/fhir}Patient", "templateId" : "patient-qicore-qicore-patient", "type" : "Retrieve" } } }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "type" : "FunctionDef", "expression" : { "type" : "Add", "operand" : [ { "name" : "a", "type" : "OperandRef" }, { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] }, "operand" : [ { "name" : "a", "operandTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}Integer", "type" : "NamedTypeSpecifier" } } ] }, { "name" : "PI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "type" : "FunctionDef", "expression" : { "type" : "Concatenate", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "Hello ", "type" : "Literal" }, { "name" : "PI:NAME:<NAME>END_PI", "type" : "OperandRef" } ] }, "operand" : [ { "name" : "a", "operandTypeSpecifier" : { "name" : "{urn:hl7-org:elm-types:r1}String", "type" : "NamedTypeSpecifier" } } ] }, { "name" : "PI:NAME:<NAME>END_PIValuePI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}Integer", "value" : "1", "type" : "Literal" } ] } }, { "name" : "PI:NAME:<NAME>END_PIValuePI:NAME:<NAME>END_PI", "context" : "Patient", "accessLevel" : "Public", "expression" : { "name" : "PI:NAME:<NAME>END_PI", "type" : "FunctionRef", "operand" : [ { "valueType" : "{urn:hl7-org:elm-types:r1}String", "value" : "World", "type" : "Literal" } ] } } ] } } }
[ { "context": " { accessKeyId: \"AWSAccessKey\", secretAccessKey: \"SecretAccessKey\" }\n\n tableName = \"tableName\"\n key ", "end": 397, "score": 0.5657199621200562, "start": 391, "tag": "KEY", "value": "Secret" }, { "context": " tableName = \"tableName\"\n key = { hash: ...
test/tests.coffee
domenic/dynamo-as-promised
4
"use strict" sinon = require("sinon") Q = require("Q") sandboxedModule = require("sandboxed-module") describe "Client", -> dynodeClient = {} { Client } = sandboxedModule.require( "..", requires: { dynode: Client: sinon.spy(-> dynodeClient) }, globals: { Error: Error } ) client = null options = { accessKeyId: "AWSAccessKey", secretAccessKey: "SecretAccessKey" } tableName = "tableName" key = { hash: "hashValue" } hashAndRangeKey = { hash: "hashValue", range: 5 } stringKey = "hashValue" keys = ({ hash: i } for i in [1..54]) values = { foo: "bar" } scanOptions = ScanFilter: foo: AttributeValueList: [{ "S": "bar" }] ComparisonOperator: "EQ" beforeEach -> dynodeClient.getItem = sinon.stub().yields(null, null, {}) dynodeClient.putItem = sinon.stub().yields(null, null) dynodeClient.deleteItem = sinon.stub().yields(null, null) dynodeClient.updateItem = sinon.stub().yields(null, {}) dynodeClient.scan = sinon.stub().yields(null, null, {}) dynodeClient.query = sinon.stub().yields(null, {}) dynodeClient.batchWriteItem = sinon.stub().yields(null, null, {}) client = new Client(options) assertCallsCorrectly = (promiseGetter, dynodeMethod, args...) -> it "should call `dynodeClient.#{dynodeMethod}` with appropriate context and arguments", (done) -> promiseGetter().then(-> dynodeClient[dynodeMethod].should.have.been.calledOn(dynodeClient) dynodeClient[dynodeMethod].should.have.been.calledWith(args...) ).should.notify(done) assertFailsCorrectly = (promiseGetter, dynodeMethod) -> describe "when `dynodeClient.#{dynodeMethod}` fails", -> error = new Error() beforeEach -> dynodeClient[dynodeMethod].yields(error) it "should reject with that error", (done) -> promiseGetter().should.be.rejected.with(error).notify(done) describe "get", -> doIt = -> client.get(tableName, key) assertCallsCorrectly(doIt, "getItem", tableName, key) describe "when `dynodeClient.getItem` succeeds", -> result = { baz: "quux" } beforeEach -> dynodeClient.getItem.yields(null, result, {}) it "should fulfill with the result", (done) -> doIt().should.become(result).notify(done) assertFailsCorrectly(doIt, "getItem") describe "put", -> doIt = -> client.put(tableName, values) assertCallsCorrectly(doIt, "putItem", tableName, values) describe "when `dynodeClient.putItem` succeeds", -> beforeEach -> dynodeClient.putItem.yields(null, {}) it "should fulfill with `undefined`", (done) -> doIt().should.become(undefined).notify(done) assertFailsCorrectly(doIt, "putItem") describe "delete", -> doIt = -> client.delete(tableName, values) assertCallsCorrectly(doIt, "deleteItem", tableName, values) describe "when `dynodeClient.deleteItem` succeeds", -> beforeEach -> dynodeClient.deleteItem.yields(null, {}) it "should fulfill with `undefined`", (done) -> doIt().should.become(undefined).notify(done) assertFailsCorrectly(doIt, "deleteItem"); describe "update", -> doIt = -> client.update(tableName, key, values) assertCallsCorrectly(doIt, "updateItem", tableName, key, values) describe "when `dynodeClient.updateItem` succeeds", -> beforeEach -> dynodeClient.updateItem.yields(null, {}) it "should fulfill with `undefined`", (done) -> doIt().should.become(undefined).notify(done) assertFailsCorrectly(doIt, "updateItem") describe "with onlyIfExists option", -> describe "and a string for the key parameter", -> doIt = -> client.update(tableName, stringKey, values, { onlyIfExists: "hashKey" }) assertCallsCorrectly(doIt, "updateItem", tableName, stringKey, values, { Expected: hashKey: Value: S: "hashValue" }) describe "and an object with a `hash` property for the key parameter", -> doIt = -> client.update(tableName, key, values, { onlyIfExists: { hash: "hashKey" } }) assertCallsCorrectly(doIt, "updateItem", tableName, key, values, { Expected: hashKey: Value: S: "hashValue" }) describe "and an object with `hash` and `range` properties for the key parameter", -> doIt = -> client.update( tableName, hashAndRangeKey, values, { onlyIfExists: { hash: "hashKey", range: "rangeKey" } } ) assertCallsCorrectly(doIt, "updateItem", tableName, hashAndRangeKey, values, { Expected: hashKey: Value: S: "hashValue" rangeKey: Value: N: "5" }) describe "updateAndGet", -> doIt = -> client.updateAndGet(tableName, key, values) assertCallsCorrectly(doIt, "updateItem", tableName, key, values, { ReturnValues: "ALL_NEW" }) describe "when `dynodeClient.updateItem` succeeds", -> beforeEach -> dynodeClient.updateItem.yields( null, Attributes: foo: "x", bar: "baz" ConsumedCapacityUnits: 1 ) it "should fulfill with the results", (done) -> doIt().should.become(foo: "x", bar: "baz").notify(done) assertFailsCorrectly(doIt, "updateItem") describe "with onlyIfExists option", -> describe "and a string for the key parameter", -> doIt = -> client.updateAndGet(tableName, stringKey, values, { onlyIfExists: "hashKey" }) assertCallsCorrectly(doIt, "updateItem", tableName, stringKey, values, { ReturnValues: "ALL_NEW" Expected: hashKey: Value: S: "hashValue" }) describe "and an object with a `hash` property for the key parameter", -> doIt = -> client.updateAndGet(tableName, key, values, { onlyIfExists: { hash: "hashKey" } }) assertCallsCorrectly(doIt, "updateItem", tableName, key, values, { ReturnValues: "ALL_NEW" Expected: hashKey: Value: S: "hashValue" }) describe "and an object with `hash` and `range` properties for the key parameter", -> doIt = -> client.updateAndGet( tableName, hashAndRangeKey, values, { onlyIfExists: { hash: "hashKey", range: "rangeKey" } } ) assertCallsCorrectly(doIt, "updateItem", tableName, hashAndRangeKey, values, { ReturnValues: "ALL_NEW" Expected: hashKey: Value: S: "hashValue" rangeKey: Value: N: "5" }) describe "query", -> doIt = -> client.query(tableName, key.hash) assertCallsCorrectly(doIt, "query", tableName, key.hash) describe "when `dynodeClient.query` succeeds", -> items = [{ baz: "quux" }] result = Count: 1 Items: items ConsumedCapacityUnits: 1 beforeEach -> dynodeClient.query.yields(null, result) it "should fulfill with the array of results", (done) -> doIt().should.become(items).notify(done) assertFailsCorrectly(doIt, "query") describe "scan", -> doIt = -> client.scan(tableName, scanOptions) assertCallsCorrectly(doIt, "scan", tableName, scanOptions) describe "when `dynodeClient.scan` succeeds", -> result = [{ baz: "quux" }] beforeEach -> dynodeClient.scan.yields(null, result, {}) it "should fulfill with the array of results", (done) -> doIt().should.become(result).notify(done) assertFailsCorrectly(doIt, "scan") describe "with no arguments", -> doIt = -> client.scan(tableName) assertCallsCorrectly(doIt, "scan", tableName, {}) describe "deleteMultiple", -> doIt = -> client.deleteMultiple(tableName, keys) [batch1, batch2, batch3] = [{}, {}, {}] batch1[tableName] = ({ del: hash: i } for i in [1..25]) batch2[tableName] = ({ del: hash: i } for i in [26..50]) batch3[tableName] = ({ del: hash: i } for i in [51..54]) it "should call `dynodeClient.batchWriteItem` for 25 key at a time", (done) -> doIt().then(-> dynodeClient.batchWriteItem.should.have.been.calledThrice dynodeClient.batchWriteItem.should.always.have.been.calledOn(dynodeClient) dynodeClient.batchWriteItem.should.have.been.calledWith(batch1) dynodeClient.batchWriteItem.should.have.been.calledWith(batch2) dynodeClient.batchWriteItem.should.have.been.calledWith(batch3) ).should.notify(done) describe "when `dynodeClient.batchWriteItem` succeeds every time", -> beforeEach -> dynodeClient.batchWriteItem.yields(null, null, {}) it "should fulfill with `undefined`", (done) -> doIt().should.become(undefined).notify(done) describe "when `dynodeClient.batchWriteItem` fails every time", -> beforeEach -> dynodeClient.batchWriteItem.yields(new Error("boo"), null, null) it "should reject, mentioning that all batches failed", (done) -> doIt().should.be.rejected.with("3/3").notify(done) it "should have an errors property on the rejection with the failures", (done) -> doIt().fail((err) -> err.should.have.property("errors") err.errors.should.deep.equal([new Error("boo"), new Error("boo"), new Error("boo")]) ).should.notify(done) describe "when `dynodeClient.batchWriteItem` fails once out of three times", -> beforeEach -> dynodeClient.batchWriteItem.withArgs(batch1).yields(new Error("aaah"), null, null) .withArgs(batch2).yields(null, null, {}) .withArgs(batch3).yields(null, null, {}) it "should reject, mentioning that 1/3 batches failed", (done) -> doIt().should.be.rejected.with("1/3").notify(done) it "should have an errors property on the rejection with the failure", (done) -> doIt().fail((err) -> err.should.have.property("errors") err.errors.should.deep.equal([new Error("aaah")]) ).should.notify(done) describe "table", -> table = null beforeEach -> table = client.table(tableName) for method in ["get", "put", "delete", "update", "updateAndGet", "query", "scan", "deleteMultiple"] describe "when calling #{method} on the generated table", -> beforeEach -> client[method] = sinon.stub().returns(Q.resolve()) it "should #{method} on its parent client with the correct table name", (done) -> table[method]("a", "b", 1, 2).then(-> client[method].should.have.been.calledWithExactly(tableName, "a", "b", 1, 2) ).should.notify(done)
26187
"use strict" sinon = require("sinon") Q = require("Q") sandboxedModule = require("sandboxed-module") describe "Client", -> dynodeClient = {} { Client } = sandboxedModule.require( "..", requires: { dynode: Client: sinon.spy(-> dynodeClient) }, globals: { Error: Error } ) client = null options = { accessKeyId: "AWSAccessKey", secretAccessKey: "<KEY>AccessKey" } tableName = "tableName" key = { hash: "hash<KEY>" } hashAndRangeKey = { hash: "hashValue", range: 5 } stringKey = "<KEY>" keys = ({ hash: i } for i in [1..54]) values = { foo: "bar" } scanOptions = ScanFilter: foo: AttributeValueList: [{ "S": "bar" }] ComparisonOperator: "EQ" beforeEach -> dynodeClient.getItem = sinon.stub().yields(null, null, {}) dynodeClient.putItem = sinon.stub().yields(null, null) dynodeClient.deleteItem = sinon.stub().yields(null, null) dynodeClient.updateItem = sinon.stub().yields(null, {}) dynodeClient.scan = sinon.stub().yields(null, null, {}) dynodeClient.query = sinon.stub().yields(null, {}) dynodeClient.batchWriteItem = sinon.stub().yields(null, null, {}) client = new Client(options) assertCallsCorrectly = (promiseGetter, dynodeMethod, args...) -> it "should call `dynodeClient.#{dynodeMethod}` with appropriate context and arguments", (done) -> promiseGetter().then(-> dynodeClient[dynodeMethod].should.have.been.calledOn(dynodeClient) dynodeClient[dynodeMethod].should.have.been.calledWith(args...) ).should.notify(done) assertFailsCorrectly = (promiseGetter, dynodeMethod) -> describe "when `dynodeClient.#{dynodeMethod}` fails", -> error = new Error() beforeEach -> dynodeClient[dynodeMethod].yields(error) it "should reject with that error", (done) -> promiseGetter().should.be.rejected.with(error).notify(done) describe "get", -> doIt = -> client.get(tableName, key) assertCallsCorrectly(doIt, "getItem", tableName, key) describe "when `dynodeClient.getItem` succeeds", -> result = { baz: "quux" } beforeEach -> dynodeClient.getItem.yields(null, result, {}) it "should fulfill with the result", (done) -> doIt().should.become(result).notify(done) assertFailsCorrectly(doIt, "getItem") describe "put", -> doIt = -> client.put(tableName, values) assertCallsCorrectly(doIt, "putItem", tableName, values) describe "when `dynodeClient.putItem` succeeds", -> beforeEach -> dynodeClient.putItem.yields(null, {}) it "should fulfill with `undefined`", (done) -> doIt().should.become(undefined).notify(done) assertFailsCorrectly(doIt, "putItem") describe "delete", -> doIt = -> client.delete(tableName, values) assertCallsCorrectly(doIt, "deleteItem", tableName, values) describe "when `dynodeClient.deleteItem` succeeds", -> beforeEach -> dynodeClient.deleteItem.yields(null, {}) it "should fulfill with `undefined`", (done) -> doIt().should.become(undefined).notify(done) assertFailsCorrectly(doIt, "deleteItem"); describe "update", -> doIt = -> client.update(tableName, key, values) assertCallsCorrectly(doIt, "updateItem", tableName, key, values) describe "when `dynodeClient.updateItem` succeeds", -> beforeEach -> dynodeClient.updateItem.yields(null, {}) it "should fulfill with `undefined`", (done) -> doIt().should.become(undefined).notify(done) assertFailsCorrectly(doIt, "updateItem") describe "with onlyIfExists option", -> describe "and a string for the key parameter", -> doIt = -> client.update(tableName, stringKey, values, { onlyIfExists: "hashKey" }) assertCallsCorrectly(doIt, "updateItem", tableName, stringKey, values, { Expected: hashKey: Value: S: "hashValue" }) describe "and an object with a `hash` property for the key parameter", -> doIt = -> client.update(tableName, key, values, { onlyIfExists: { hash: "hashKey" } }) assertCallsCorrectly(doIt, "updateItem", tableName, key, values, { Expected: hashKey: Value: S: "hashValue" }) describe "and an object with `hash` and `range` properties for the key parameter", -> doIt = -> client.update( tableName, hashAndRangeKey, values, { onlyIfExists: { hash: "hashKey", range: "rangeKey" } } ) assertCallsCorrectly(doIt, "updateItem", tableName, hashAndRangeKey, values, { Expected: hashKey: Value: S: "hashValue" rangeKey: Value: N: "5" }) describe "updateAndGet", -> doIt = -> client.updateAndGet(tableName, key, values) assertCallsCorrectly(doIt, "updateItem", tableName, key, values, { ReturnValues: "ALL_NEW" }) describe "when `dynodeClient.updateItem` succeeds", -> beforeEach -> dynodeClient.updateItem.yields( null, Attributes: foo: "x", bar: "baz" ConsumedCapacityUnits: 1 ) it "should fulfill with the results", (done) -> doIt().should.become(foo: "x", bar: "baz").notify(done) assertFailsCorrectly(doIt, "updateItem") describe "with onlyIfExists option", -> describe "and a string for the key parameter", -> doIt = -> client.updateAndGet(tableName, stringKey, values, { onlyIfExists: "hashKey" }) assertCallsCorrectly(doIt, "updateItem", tableName, stringKey, values, { ReturnValues: "ALL_NEW" Expected: hashKey: Value: S: "hashValue" }) describe "and an object with a `hash` property for the key parameter", -> doIt = -> client.updateAndGet(tableName, key, values, { onlyIfExists: { hash: "hashKey" } }) assertCallsCorrectly(doIt, "updateItem", tableName, key, values, { ReturnValues: "ALL_NEW" Expected: hashKey: Value: S: "hashValue" }) describe "and an object with `hash` and `range` properties for the key parameter", -> doIt = -> client.updateAndGet( tableName, hashAndRangeKey, values, { onlyIfExists: { hash: "hashKey", range: "rangeKey" } } ) assertCallsCorrectly(doIt, "updateItem", tableName, hashAndRangeKey, values, { ReturnValues: "ALL_NEW" Expected: hashKey: Value: S: "hashValue" rangeKey: Value: N: "5" }) describe "query", -> doIt = -> client.query(tableName, key.hash) assertCallsCorrectly(doIt, "query", tableName, key.hash) describe "when `dynodeClient.query` succeeds", -> items = [{ baz: "quux" }] result = Count: 1 Items: items ConsumedCapacityUnits: 1 beforeEach -> dynodeClient.query.yields(null, result) it "should fulfill with the array of results", (done) -> doIt().should.become(items).notify(done) assertFailsCorrectly(doIt, "query") describe "scan", -> doIt = -> client.scan(tableName, scanOptions) assertCallsCorrectly(doIt, "scan", tableName, scanOptions) describe "when `dynodeClient.scan` succeeds", -> result = [{ baz: "quux" }] beforeEach -> dynodeClient.scan.yields(null, result, {}) it "should fulfill with the array of results", (done) -> doIt().should.become(result).notify(done) assertFailsCorrectly(doIt, "scan") describe "with no arguments", -> doIt = -> client.scan(tableName) assertCallsCorrectly(doIt, "scan", tableName, {}) describe "deleteMultiple", -> doIt = -> client.deleteMultiple(tableName, keys) [batch1, batch2, batch3] = [{}, {}, {}] batch1[tableName] = ({ del: hash: i } for i in [1..25]) batch2[tableName] = ({ del: hash: i } for i in [26..50]) batch3[tableName] = ({ del: hash: i } for i in [51..54]) it "should call `dynodeClient.batchWriteItem` for 25 key at a time", (done) -> doIt().then(-> dynodeClient.batchWriteItem.should.have.been.calledThrice dynodeClient.batchWriteItem.should.always.have.been.calledOn(dynodeClient) dynodeClient.batchWriteItem.should.have.been.calledWith(batch1) dynodeClient.batchWriteItem.should.have.been.calledWith(batch2) dynodeClient.batchWriteItem.should.have.been.calledWith(batch3) ).should.notify(done) describe "when `dynodeClient.batchWriteItem` succeeds every time", -> beforeEach -> dynodeClient.batchWriteItem.yields(null, null, {}) it "should fulfill with `undefined`", (done) -> doIt().should.become(undefined).notify(done) describe "when `dynodeClient.batchWriteItem` fails every time", -> beforeEach -> dynodeClient.batchWriteItem.yields(new Error("boo"), null, null) it "should reject, mentioning that all batches failed", (done) -> doIt().should.be.rejected.with("3/3").notify(done) it "should have an errors property on the rejection with the failures", (done) -> doIt().fail((err) -> err.should.have.property("errors") err.errors.should.deep.equal([new Error("boo"), new Error("boo"), new Error("boo")]) ).should.notify(done) describe "when `dynodeClient.batchWriteItem` fails once out of three times", -> beforeEach -> dynodeClient.batchWriteItem.withArgs(batch1).yields(new Error("aaah"), null, null) .withArgs(batch2).yields(null, null, {}) .withArgs(batch3).yields(null, null, {}) it "should reject, mentioning that 1/3 batches failed", (done) -> doIt().should.be.rejected.with("1/3").notify(done) it "should have an errors property on the rejection with the failure", (done) -> doIt().fail((err) -> err.should.have.property("errors") err.errors.should.deep.equal([new Error("aaah")]) ).should.notify(done) describe "table", -> table = null beforeEach -> table = client.table(tableName) for method in ["get", "put", "delete", "update", "updateAndGet", "query", "scan", "deleteMultiple"] describe "when calling #{method} on the generated table", -> beforeEach -> client[method] = sinon.stub().returns(Q.resolve()) it "should #{method} on its parent client with the correct table name", (done) -> table[method]("a", "b", 1, 2).then(-> client[method].should.have.been.calledWithExactly(tableName, "a", "b", 1, 2) ).should.notify(done)
true
"use strict" sinon = require("sinon") Q = require("Q") sandboxedModule = require("sandboxed-module") describe "Client", -> dynodeClient = {} { Client } = sandboxedModule.require( "..", requires: { dynode: Client: sinon.spy(-> dynodeClient) }, globals: { Error: Error } ) client = null options = { accessKeyId: "AWSAccessKey", secretAccessKey: "PI:KEY:<KEY>END_PIAccessKey" } tableName = "tableName" key = { hash: "hashPI:KEY:<KEY>END_PI" } hashAndRangeKey = { hash: "hashValue", range: 5 } stringKey = "PI:KEY:<KEY>END_PI" keys = ({ hash: i } for i in [1..54]) values = { foo: "bar" } scanOptions = ScanFilter: foo: AttributeValueList: [{ "S": "bar" }] ComparisonOperator: "EQ" beforeEach -> dynodeClient.getItem = sinon.stub().yields(null, null, {}) dynodeClient.putItem = sinon.stub().yields(null, null) dynodeClient.deleteItem = sinon.stub().yields(null, null) dynodeClient.updateItem = sinon.stub().yields(null, {}) dynodeClient.scan = sinon.stub().yields(null, null, {}) dynodeClient.query = sinon.stub().yields(null, {}) dynodeClient.batchWriteItem = sinon.stub().yields(null, null, {}) client = new Client(options) assertCallsCorrectly = (promiseGetter, dynodeMethod, args...) -> it "should call `dynodeClient.#{dynodeMethod}` with appropriate context and arguments", (done) -> promiseGetter().then(-> dynodeClient[dynodeMethod].should.have.been.calledOn(dynodeClient) dynodeClient[dynodeMethod].should.have.been.calledWith(args...) ).should.notify(done) assertFailsCorrectly = (promiseGetter, dynodeMethod) -> describe "when `dynodeClient.#{dynodeMethod}` fails", -> error = new Error() beforeEach -> dynodeClient[dynodeMethod].yields(error) it "should reject with that error", (done) -> promiseGetter().should.be.rejected.with(error).notify(done) describe "get", -> doIt = -> client.get(tableName, key) assertCallsCorrectly(doIt, "getItem", tableName, key) describe "when `dynodeClient.getItem` succeeds", -> result = { baz: "quux" } beforeEach -> dynodeClient.getItem.yields(null, result, {}) it "should fulfill with the result", (done) -> doIt().should.become(result).notify(done) assertFailsCorrectly(doIt, "getItem") describe "put", -> doIt = -> client.put(tableName, values) assertCallsCorrectly(doIt, "putItem", tableName, values) describe "when `dynodeClient.putItem` succeeds", -> beforeEach -> dynodeClient.putItem.yields(null, {}) it "should fulfill with `undefined`", (done) -> doIt().should.become(undefined).notify(done) assertFailsCorrectly(doIt, "putItem") describe "delete", -> doIt = -> client.delete(tableName, values) assertCallsCorrectly(doIt, "deleteItem", tableName, values) describe "when `dynodeClient.deleteItem` succeeds", -> beforeEach -> dynodeClient.deleteItem.yields(null, {}) it "should fulfill with `undefined`", (done) -> doIt().should.become(undefined).notify(done) assertFailsCorrectly(doIt, "deleteItem"); describe "update", -> doIt = -> client.update(tableName, key, values) assertCallsCorrectly(doIt, "updateItem", tableName, key, values) describe "when `dynodeClient.updateItem` succeeds", -> beforeEach -> dynodeClient.updateItem.yields(null, {}) it "should fulfill with `undefined`", (done) -> doIt().should.become(undefined).notify(done) assertFailsCorrectly(doIt, "updateItem") describe "with onlyIfExists option", -> describe "and a string for the key parameter", -> doIt = -> client.update(tableName, stringKey, values, { onlyIfExists: "hashKey" }) assertCallsCorrectly(doIt, "updateItem", tableName, stringKey, values, { Expected: hashKey: Value: S: "hashValue" }) describe "and an object with a `hash` property for the key parameter", -> doIt = -> client.update(tableName, key, values, { onlyIfExists: { hash: "hashKey" } }) assertCallsCorrectly(doIt, "updateItem", tableName, key, values, { Expected: hashKey: Value: S: "hashValue" }) describe "and an object with `hash` and `range` properties for the key parameter", -> doIt = -> client.update( tableName, hashAndRangeKey, values, { onlyIfExists: { hash: "hashKey", range: "rangeKey" } } ) assertCallsCorrectly(doIt, "updateItem", tableName, hashAndRangeKey, values, { Expected: hashKey: Value: S: "hashValue" rangeKey: Value: N: "5" }) describe "updateAndGet", -> doIt = -> client.updateAndGet(tableName, key, values) assertCallsCorrectly(doIt, "updateItem", tableName, key, values, { ReturnValues: "ALL_NEW" }) describe "when `dynodeClient.updateItem` succeeds", -> beforeEach -> dynodeClient.updateItem.yields( null, Attributes: foo: "x", bar: "baz" ConsumedCapacityUnits: 1 ) it "should fulfill with the results", (done) -> doIt().should.become(foo: "x", bar: "baz").notify(done) assertFailsCorrectly(doIt, "updateItem") describe "with onlyIfExists option", -> describe "and a string for the key parameter", -> doIt = -> client.updateAndGet(tableName, stringKey, values, { onlyIfExists: "hashKey" }) assertCallsCorrectly(doIt, "updateItem", tableName, stringKey, values, { ReturnValues: "ALL_NEW" Expected: hashKey: Value: S: "hashValue" }) describe "and an object with a `hash` property for the key parameter", -> doIt = -> client.updateAndGet(tableName, key, values, { onlyIfExists: { hash: "hashKey" } }) assertCallsCorrectly(doIt, "updateItem", tableName, key, values, { ReturnValues: "ALL_NEW" Expected: hashKey: Value: S: "hashValue" }) describe "and an object with `hash` and `range` properties for the key parameter", -> doIt = -> client.updateAndGet( tableName, hashAndRangeKey, values, { onlyIfExists: { hash: "hashKey", range: "rangeKey" } } ) assertCallsCorrectly(doIt, "updateItem", tableName, hashAndRangeKey, values, { ReturnValues: "ALL_NEW" Expected: hashKey: Value: S: "hashValue" rangeKey: Value: N: "5" }) describe "query", -> doIt = -> client.query(tableName, key.hash) assertCallsCorrectly(doIt, "query", tableName, key.hash) describe "when `dynodeClient.query` succeeds", -> items = [{ baz: "quux" }] result = Count: 1 Items: items ConsumedCapacityUnits: 1 beforeEach -> dynodeClient.query.yields(null, result) it "should fulfill with the array of results", (done) -> doIt().should.become(items).notify(done) assertFailsCorrectly(doIt, "query") describe "scan", -> doIt = -> client.scan(tableName, scanOptions) assertCallsCorrectly(doIt, "scan", tableName, scanOptions) describe "when `dynodeClient.scan` succeeds", -> result = [{ baz: "quux" }] beforeEach -> dynodeClient.scan.yields(null, result, {}) it "should fulfill with the array of results", (done) -> doIt().should.become(result).notify(done) assertFailsCorrectly(doIt, "scan") describe "with no arguments", -> doIt = -> client.scan(tableName) assertCallsCorrectly(doIt, "scan", tableName, {}) describe "deleteMultiple", -> doIt = -> client.deleteMultiple(tableName, keys) [batch1, batch2, batch3] = [{}, {}, {}] batch1[tableName] = ({ del: hash: i } for i in [1..25]) batch2[tableName] = ({ del: hash: i } for i in [26..50]) batch3[tableName] = ({ del: hash: i } for i in [51..54]) it "should call `dynodeClient.batchWriteItem` for 25 key at a time", (done) -> doIt().then(-> dynodeClient.batchWriteItem.should.have.been.calledThrice dynodeClient.batchWriteItem.should.always.have.been.calledOn(dynodeClient) dynodeClient.batchWriteItem.should.have.been.calledWith(batch1) dynodeClient.batchWriteItem.should.have.been.calledWith(batch2) dynodeClient.batchWriteItem.should.have.been.calledWith(batch3) ).should.notify(done) describe "when `dynodeClient.batchWriteItem` succeeds every time", -> beforeEach -> dynodeClient.batchWriteItem.yields(null, null, {}) it "should fulfill with `undefined`", (done) -> doIt().should.become(undefined).notify(done) describe "when `dynodeClient.batchWriteItem` fails every time", -> beforeEach -> dynodeClient.batchWriteItem.yields(new Error("boo"), null, null) it "should reject, mentioning that all batches failed", (done) -> doIt().should.be.rejected.with("3/3").notify(done) it "should have an errors property on the rejection with the failures", (done) -> doIt().fail((err) -> err.should.have.property("errors") err.errors.should.deep.equal([new Error("boo"), new Error("boo"), new Error("boo")]) ).should.notify(done) describe "when `dynodeClient.batchWriteItem` fails once out of three times", -> beforeEach -> dynodeClient.batchWriteItem.withArgs(batch1).yields(new Error("aaah"), null, null) .withArgs(batch2).yields(null, null, {}) .withArgs(batch3).yields(null, null, {}) it "should reject, mentioning that 1/3 batches failed", (done) -> doIt().should.be.rejected.with("1/3").notify(done) it "should have an errors property on the rejection with the failure", (done) -> doIt().fail((err) -> err.should.have.property("errors") err.errors.should.deep.equal([new Error("aaah")]) ).should.notify(done) describe "table", -> table = null beforeEach -> table = client.table(tableName) for method in ["get", "put", "delete", "update", "updateAndGet", "query", "scan", "deleteMultiple"] describe "when calling #{method} on the generated table", -> beforeEach -> client[method] = sinon.stub().returns(Q.resolve()) it "should #{method} on its parent client with the correct table name", (done) -> table[method]("a", "b", 1, 2).then(-> client[method].should.have.been.calledWithExactly(tableName, "a", "b", 1, 2) ).should.notify(done)
[ { "context": "n key, value of object\n newKey = if prefix then \"#{prefix}#{sep}#{key}\" else key\n\n if (typeof value is 'object') ", "end": 652, "score": 0.744536817073822, "start": 634, "tag": "KEY", "value": "\"#{prefix}#{sep}#{" }, { "context": "\n newKey = if prefix th...
node_modules/livereload/lib/commands/rpc.coffee
Acidburn0zzz/LiveReload
723
apitree = require 'apitree' Path = require 'path' JSONStreamTransport = require '../rpc/transports/jsonstream' exports.usage = [ "JSON RPC mode for the GUI." ' server', [ "Run in RPC mode, speaking JSON on stdin and stdout." ] ' console', [ "Run in debugging-friendly RPC REPL mode, speaking JSON on stdin and stdout via readline." ] ' print-apis', [ "Print the list of available RPC APIs." "This command is invoked by 'rake routing' to build the client-side proxy code." ] ] flattenHash = (object, sep='.', prefix='', result={}) -> for own key, value of object newKey = if prefix then "#{prefix}#{sep}#{key}" else key if (typeof value is 'object') && value.constructor is Object flattenHash value, sep, newKey, result else result[newKey] = value return result setupRpcEnvironment = (options, context) -> context.setupRpc(new JSONStreamTransport(process.stdin, process.stdout)) context.rpc.on 'end', -> process.exit(0) global.LR = require('../../config/env').createEnvironment(options, context) runServer = (options, context) -> process.title = "LiveReloadHelper" runConsoleServer = (options, context) -> LR.app.api.init.call context, { resourcesDir: context.paths.bundledPlugins, appDataDir: context.paths.bundledPlugins, logDir: process.env['TMPDIR'] or process.env['TEMP'] }, (err) -> if err throw err printApis = (options, context) -> tree = apitree.createApiTree context.paths.rpc, loadItem: (path) -> require(path).api || {} tree = flattenHash(tree) for k in Object.keys(tree) process.stdout.write "#{k}\n" exports.run = (options, context) -> switch options.subcommand when 'print-apis' printApis(options, context) when 'server' setupRpcEnvironment(options, context) runServer(options, context) when 'console' setupRpcEnvironment(options, context) runConsoleServer(options, context)
192841
apitree = require 'apitree' Path = require 'path' JSONStreamTransport = require '../rpc/transports/jsonstream' exports.usage = [ "JSON RPC mode for the GUI." ' server', [ "Run in RPC mode, speaking JSON on stdin and stdout." ] ' console', [ "Run in debugging-friendly RPC REPL mode, speaking JSON on stdin and stdout via readline." ] ' print-apis', [ "Print the list of available RPC APIs." "This command is invoked by 'rake routing' to build the client-side proxy code." ] ] flattenHash = (object, sep='.', prefix='', result={}) -> for own key, value of object newKey = if prefix then <KEY>key<KEY>}" else key if (typeof value is 'object') && value.constructor is Object flattenHash value, sep, newKey, result else result[newKey] = value return result setupRpcEnvironment = (options, context) -> context.setupRpc(new JSONStreamTransport(process.stdin, process.stdout)) context.rpc.on 'end', -> process.exit(0) global.LR = require('../../config/env').createEnvironment(options, context) runServer = (options, context) -> process.title = "LiveReloadHelper" runConsoleServer = (options, context) -> LR.app.api.init.call context, { resourcesDir: context.paths.bundledPlugins, appDataDir: context.paths.bundledPlugins, logDir: process.env['TMPDIR'] or process.env['TEMP'] }, (err) -> if err throw err printApis = (options, context) -> tree = apitree.createApiTree context.paths.rpc, loadItem: (path) -> require(path).api || {} tree = flattenHash(tree) for k in Object.keys(tree) process.stdout.write "#{k}\n" exports.run = (options, context) -> switch options.subcommand when 'print-apis' printApis(options, context) when 'server' setupRpcEnvironment(options, context) runServer(options, context) when 'console' setupRpcEnvironment(options, context) runConsoleServer(options, context)
true
apitree = require 'apitree' Path = require 'path' JSONStreamTransport = require '../rpc/transports/jsonstream' exports.usage = [ "JSON RPC mode for the GUI." ' server', [ "Run in RPC mode, speaking JSON on stdin and stdout." ] ' console', [ "Run in debugging-friendly RPC REPL mode, speaking JSON on stdin and stdout via readline." ] ' print-apis', [ "Print the list of available RPC APIs." "This command is invoked by 'rake routing' to build the client-side proxy code." ] ] flattenHash = (object, sep='.', prefix='', result={}) -> for own key, value of object newKey = if prefix then PI:KEY:<KEY>END_PIkeyPI:KEY:<KEY>END_PI}" else key if (typeof value is 'object') && value.constructor is Object flattenHash value, sep, newKey, result else result[newKey] = value return result setupRpcEnvironment = (options, context) -> context.setupRpc(new JSONStreamTransport(process.stdin, process.stdout)) context.rpc.on 'end', -> process.exit(0) global.LR = require('../../config/env').createEnvironment(options, context) runServer = (options, context) -> process.title = "LiveReloadHelper" runConsoleServer = (options, context) -> LR.app.api.init.call context, { resourcesDir: context.paths.bundledPlugins, appDataDir: context.paths.bundledPlugins, logDir: process.env['TMPDIR'] or process.env['TEMP'] }, (err) -> if err throw err printApis = (options, context) -> tree = apitree.createApiTree context.paths.rpc, loadItem: (path) -> require(path).api || {} tree = flattenHash(tree) for k in Object.keys(tree) process.stdout.write "#{k}\n" exports.run = (options, context) -> switch options.subcommand when 'print-apis' printApis(options, context) when 'server' setupRpcEnvironment(options, context) runServer(options, context) when 'console' setupRpcEnvironment(options, context) runConsoleServer(options, context)
[ { "context": "generateRandomUsername()\n password : 'testpass'\n inviteCode : ''\n passwordConfirm ", "end": 467, "score": 0.9994720816612244, "start": 459, "tag": "PASSWORD", "value": "testpass" }, { "context": " inviteCode : ''\n passwordConfirm...
servers/testhelper/handler/registerhelper.coffee
ezgikaysi/koding
1
{ expect request querystring generateUrl deepObjectExtend generateRandomEmail generateRandomString generateRandomUsername generateRequestParamsEncodeBody } = require '../index' generateRegisterRequestBody = (opts = {}) -> defaultBodyObject = _csrf : generateRandomString() email : generateRandomEmail() agree : 'on' username : generateRandomUsername() password : 'testpass' inviteCode : '' passwordConfirm : 'testpass' defaultBodyObject = deepObjectExtend defaultBodyObject, opts return defaultBodyObject # overwrites given options in the default params generateRegisterRequestParams = (opts = {}) -> body = generateRegisterRequestBody() params = url : generateUrl { route : 'Register' } body : body csrfCookie : body._csrf requestParams = generateRequestParamsEncodeBody params, opts return requestParams withRegisteredUser = (opts, callback) -> [opts, callback] = [callback, opts] unless callback opts ?= {} opts.body = generateRegisterRequestBody opts.body opts.csrfCookie = opts.body?._csrf registerRequestParams = generateRegisterRequestParams opts request.post registerRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 200 expect(body).to.be.empty extraParams = { headers: res.headers } callback opts.body, extraParams module.exports = { withRegisteredUser generateRegisterRequestBody generateRegisterRequestParams }
37242
{ expect request querystring generateUrl deepObjectExtend generateRandomEmail generateRandomString generateRandomUsername generateRequestParamsEncodeBody } = require '../index' generateRegisterRequestBody = (opts = {}) -> defaultBodyObject = _csrf : generateRandomString() email : generateRandomEmail() agree : 'on' username : generateRandomUsername() password : '<PASSWORD>' inviteCode : '' passwordConfirm : '<PASSWORD>' defaultBodyObject = deepObjectExtend defaultBodyObject, opts return defaultBodyObject # overwrites given options in the default params generateRegisterRequestParams = (opts = {}) -> body = generateRegisterRequestBody() params = url : generateUrl { route : 'Register' } body : body csrfCookie : body._csrf requestParams = generateRequestParamsEncodeBody params, opts return requestParams withRegisteredUser = (opts, callback) -> [opts, callback] = [callback, opts] unless callback opts ?= {} opts.body = generateRegisterRequestBody opts.body opts.csrfCookie = opts.body?._csrf registerRequestParams = generateRegisterRequestParams opts request.post registerRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 200 expect(body).to.be.empty extraParams = { headers: res.headers } callback opts.body, extraParams module.exports = { withRegisteredUser generateRegisterRequestBody generateRegisterRequestParams }
true
{ expect request querystring generateUrl deepObjectExtend generateRandomEmail generateRandomString generateRandomUsername generateRequestParamsEncodeBody } = require '../index' generateRegisterRequestBody = (opts = {}) -> defaultBodyObject = _csrf : generateRandomString() email : generateRandomEmail() agree : 'on' username : generateRandomUsername() password : 'PI:PASSWORD:<PASSWORD>END_PI' inviteCode : '' passwordConfirm : 'PI:PASSWORD:<PASSWORD>END_PI' defaultBodyObject = deepObjectExtend defaultBodyObject, opts return defaultBodyObject # overwrites given options in the default params generateRegisterRequestParams = (opts = {}) -> body = generateRegisterRequestBody() params = url : generateUrl { route : 'Register' } body : body csrfCookie : body._csrf requestParams = generateRequestParamsEncodeBody params, opts return requestParams withRegisteredUser = (opts, callback) -> [opts, callback] = [callback, opts] unless callback opts ?= {} opts.body = generateRegisterRequestBody opts.body opts.csrfCookie = opts.body?._csrf registerRequestParams = generateRegisterRequestParams opts request.post registerRequestParams, (err, res, body) -> expect(err).to.not.exist expect(res.statusCode).to.be.equal 200 expect(body).to.be.empty extraParams = { headers: res.headers } callback opts.body, extraParams module.exports = { withRegisteredUser generateRegisterRequestBody generateRegisterRequestParams }
[ { "context": "//localhost/mysite.html with 401, authenticated as me@home.com'\n expect(match).to.eql {\n method: 'get'\n ", "end": 1691, "score": 0.9998828768730164, "start": 1680, "tag": "EMAIL", "value": "me@home.com" }, { "context": " format: null\n statusCode: 401\n...
test/methods.coffee
pstaender/visitjs
0
expect = require('expect.js') visitor = { extractRequestFromTitle } = require('../src')() describe 'unit tests for visitjs', -> it 'expect to convert a title to request options', -> # get /mysite as JSON with status code 200 match = visitor.extractRequestFromTitle 'get /mysite as json with status code 301' expect(match).to.eql { method: 'get' url: '/mysite' format: 'json' statusCode: 301 user: null imageTitle: null } match = visitor.extractRequestFromTitle 'should get an error by visiting /mysite as json with status code 200 because it is unauthroized (401) by default' expect(match).to.eql { method: 'get' url: '/mysite' format: 'json' statusCode: 200 user: null imageTitle: null } # get /mysite.json -> 200 match = visitor.extractRequestFromTitle 'get /mysite.json -> 200' expect(match).to.eql { method: 'get' url: '/mysite.json' format: null statusCode: 200 user: null imageTitle: null } match = visitor.extractRequestFromTitle 'visit /mysite.json' expect(match).to.eql { method: 'get' url: '/mysite.json' format: null statusCode: null user: null imageTitle: null } # post /mysite with status 200 match = visitor.extractRequestFromTitle 'post /mysite.html with status 404' expect(match).to.eql { method: 'post' url: '/mysite.html' format: null statusCode: 404 user: null imageTitle: null } match = visitor.extractRequestFromTitle 'it expects to visit http://localhost/mysite.html with 401, authenticated as me@home.com' expect(match).to.eql { method: 'get' url: 'http://localhost/mysite.html' format: null statusCode: 401 user: 'me@home.com' imageTitle: null } match = visitor.extractRequestFromTitle 'it expects to visit /mysite.html having xml with 401 (logged in as admin)' expect(match).to.eql { method: 'get' url: '/mysite.html' format: 'xml' user: 'admin' statusCode: 401 imageTitle: null } match = visitor.extractRequestFromTitle 'expect to visit http://localhost/mysite/admin , login as admin' expect(match).to.eql { method: 'get' url: 'http://localhost/mysite/admin' format: null user: 'admin' statusCode: null imageTitle: null } it 'expect to convert a title to request options with image title', -> match = visitor.extractRequestFromTitle 'expect to visit /mysite/settings -> 404 (authenticated as admin) ![my_settings_admin]' expect(match).to.eql { method: 'get' url: '/mysite/settings' format: null user: 'admin' statusCode: 404 imageTitle: 'my_settings_admin' }
143989
expect = require('expect.js') visitor = { extractRequestFromTitle } = require('../src')() describe 'unit tests for visitjs', -> it 'expect to convert a title to request options', -> # get /mysite as JSON with status code 200 match = visitor.extractRequestFromTitle 'get /mysite as json with status code 301' expect(match).to.eql { method: 'get' url: '/mysite' format: 'json' statusCode: 301 user: null imageTitle: null } match = visitor.extractRequestFromTitle 'should get an error by visiting /mysite as json with status code 200 because it is unauthroized (401) by default' expect(match).to.eql { method: 'get' url: '/mysite' format: 'json' statusCode: 200 user: null imageTitle: null } # get /mysite.json -> 200 match = visitor.extractRequestFromTitle 'get /mysite.json -> 200' expect(match).to.eql { method: 'get' url: '/mysite.json' format: null statusCode: 200 user: null imageTitle: null } match = visitor.extractRequestFromTitle 'visit /mysite.json' expect(match).to.eql { method: 'get' url: '/mysite.json' format: null statusCode: null user: null imageTitle: null } # post /mysite with status 200 match = visitor.extractRequestFromTitle 'post /mysite.html with status 404' expect(match).to.eql { method: 'post' url: '/mysite.html' format: null statusCode: 404 user: null imageTitle: null } match = visitor.extractRequestFromTitle 'it expects to visit http://localhost/mysite.html with 401, authenticated as <EMAIL>' expect(match).to.eql { method: 'get' url: 'http://localhost/mysite.html' format: null statusCode: 401 user: '<EMAIL>' imageTitle: null } match = visitor.extractRequestFromTitle 'it expects to visit /mysite.html having xml with 401 (logged in as admin)' expect(match).to.eql { method: 'get' url: '/mysite.html' format: 'xml' user: 'admin' statusCode: 401 imageTitle: null } match = visitor.extractRequestFromTitle 'expect to visit http://localhost/mysite/admin , login as admin' expect(match).to.eql { method: 'get' url: 'http://localhost/mysite/admin' format: null user: 'admin' statusCode: null imageTitle: null } it 'expect to convert a title to request options with image title', -> match = visitor.extractRequestFromTitle 'expect to visit /mysite/settings -> 404 (authenticated as admin) ![my_settings_admin]' expect(match).to.eql { method: 'get' url: '/mysite/settings' format: null user: 'admin' statusCode: 404 imageTitle: 'my_settings_admin' }
true
expect = require('expect.js') visitor = { extractRequestFromTitle } = require('../src')() describe 'unit tests for visitjs', -> it 'expect to convert a title to request options', -> # get /mysite as JSON with status code 200 match = visitor.extractRequestFromTitle 'get /mysite as json with status code 301' expect(match).to.eql { method: 'get' url: '/mysite' format: 'json' statusCode: 301 user: null imageTitle: null } match = visitor.extractRequestFromTitle 'should get an error by visiting /mysite as json with status code 200 because it is unauthroized (401) by default' expect(match).to.eql { method: 'get' url: '/mysite' format: 'json' statusCode: 200 user: null imageTitle: null } # get /mysite.json -> 200 match = visitor.extractRequestFromTitle 'get /mysite.json -> 200' expect(match).to.eql { method: 'get' url: '/mysite.json' format: null statusCode: 200 user: null imageTitle: null } match = visitor.extractRequestFromTitle 'visit /mysite.json' expect(match).to.eql { method: 'get' url: '/mysite.json' format: null statusCode: null user: null imageTitle: null } # post /mysite with status 200 match = visitor.extractRequestFromTitle 'post /mysite.html with status 404' expect(match).to.eql { method: 'post' url: '/mysite.html' format: null statusCode: 404 user: null imageTitle: null } match = visitor.extractRequestFromTitle 'it expects to visit http://localhost/mysite.html with 401, authenticated as PI:EMAIL:<EMAIL>END_PI' expect(match).to.eql { method: 'get' url: 'http://localhost/mysite.html' format: null statusCode: 401 user: 'PI:EMAIL:<EMAIL>END_PI' imageTitle: null } match = visitor.extractRequestFromTitle 'it expects to visit /mysite.html having xml with 401 (logged in as admin)' expect(match).to.eql { method: 'get' url: '/mysite.html' format: 'xml' user: 'admin' statusCode: 401 imageTitle: null } match = visitor.extractRequestFromTitle 'expect to visit http://localhost/mysite/admin , login as admin' expect(match).to.eql { method: 'get' url: 'http://localhost/mysite/admin' format: null user: 'admin' statusCode: null imageTitle: null } it 'expect to convert a title to request options with image title', -> match = visitor.extractRequestFromTitle 'expect to visit /mysite/settings -> 404 (authenticated as admin) ![my_settings_admin]' expect(match).to.eql { method: 'get' url: '/mysite/settings' format: null user: 'admin' statusCode: 404 imageTitle: 'my_settings_admin' }
[ { "context": "uery = User.find()\n query.where('name').in([\"Tom\",\"Rob\"])\n params = {}\n\n query = util.fo", "end": 297, "score": 0.9997919201850891, "start": 294, "tag": "NAME", "value": "Tom" }, { "context": " User.find()\n query.where('name').in([\"Tom\",\"...
test/formatParams.coffee
wearefractal/crudify
8
{util} = crudify = require '../' should = require 'should' require 'mocha' db = require './fixtures/connection' User = db.model 'User' describe 'formatParams()', -> describe 'flags', -> it 'should create flags object', (done) -> query = User.find() query.where('name').in(["Tom","Rob"]) params = {} query = util.formatParams params, User should.exist query.flags done() describe 'skip', -> it 'should work with valid string number', (done) -> query = User.find() query.where('name').in(["Tom","Rob"]) params = skip: "10" query = util.formatParams params, User should.exist query.skip query.skip.should.equal 10 done() it 'should work with valid number', (done) -> query = User.find() query.where('name').in(["Tom","Rob"]) params = skip: 10 query = util.formatParams params, User should.exist query.skip query.skip.should.equal 10 done() it 'should ignore invalid number', (done) -> query = User.find() query.where('name').in(["Tom","Rob"]) params = skip: "blah" query = util.formatParams params, User should.not.exist query.skip done() it 'should ignore 0 number', (done) -> query = User.find() query.where('name').in(["Tom","Rob"]) params = skip: 0 query = util.formatParams params, User should.not.exist query.skip done() describe 'limit', -> it 'should work with valid string number', (done) -> query = User.find() query.where('name').in(["Tom","Rob"]) params = limit: "10" query = util.formatParams params, User should.exist query.limit query.limit.should.equal 10 done() it 'should work with valid number', (done) -> query = User.find() query.where('name').in(["Tom","Rob"]) params = limit: 10 query = util.formatParams params, User should.exist query.limit query.limit.should.equal 10 done() it 'should ignore invalid number', (done) -> query = User.find() query.where('name').in(["Tom","Rob"]) params = limit: "blah" query = util.formatParams params, User should.not.exist query.limit done() it 'should ignore 0 number', (done) -> query = User.find() query.where('name').in(["Tom","Rob"]) params = limit: 0 query = util.formatParams params, User should.not.exist query.limit done() describe 'sort', -> it 'should work with valid field name', (done) -> query = User.find() query.where('name').in(["Tom","Rob"]) params = sort: "score" query = util.formatParams params, User should.exist query.sort query.sort.should.eql ['score'] done() it 'should work with valid field name and - operator', (done) -> query = User.find() query.where('name').in(["Tom","Rob"]) params = sort: "-score" query = util.formatParams params, User should.exist query.sort query.sort.should.eql ['-score'] done() it 'should ignore invalid field name', (done) -> query = User.find() query.where('name').in(["Tom","Rob"]) params = sort: "blah" query = util.formatParams params, User query.sort.should.eql [] done() it 'should ignore invalid field name with - operator', (done) -> query = User.find() query.where('name').in(["Tom","Rob"]) params = sort: "-blah" query = util.formatParams params, User query.sort.should.eql [] done() describe 'populate', -> it 'should work with valid field name', (done) -> query = User.find() query.where('name').in(["Tom","Rob"]) params = populate: "bestFriend" query = util.formatParams params, User should.exist query.populate query.populate.should.eql ["bestFriend"] done() it 'should ignore invalid field name', (done) -> query = User.find() query.where('name').in(["Tom","Rob"]) params = populate: "blah" query = util.formatParams params, User query.populate.should.eql [] done() describe 'where', -> it 'should work with valid field name', (done) -> query = User.find() params = name: "Tom" score: 100 query = util.formatParams params, User should.exist query.conditions query.conditions.should.eql name: "Tom" score: 100 done() it 'should ignore invalid field names from valid', (done) -> query = User.find() params = blah: "Tom" score: 100 query = util.formatParams params, User should.exist query.conditions query.conditions.should.eql score: 100 done() it 'should ignore invalid field names completely', (done) -> query = User.find() params = blah: "Tom" zzz: 100 query = util.formatParams params, User should.exist query.conditions should.not.exist query.conditions.blah should.not.exist query.conditions.zzz done()
6095
{util} = crudify = require '../' should = require 'should' require 'mocha' db = require './fixtures/connection' User = db.model 'User' describe 'formatParams()', -> describe 'flags', -> it 'should create flags object', (done) -> query = User.find() query.where('name').in(["<NAME>","<NAME>"]) params = {} query = util.formatParams params, User should.exist query.flags done() describe 'skip', -> it 'should work with valid string number', (done) -> query = User.find() query.where('name').in(["<NAME>","<NAME>"]) params = skip: "10" query = util.formatParams params, User should.exist query.skip query.skip.should.equal 10 done() it 'should work with valid number', (done) -> query = User.find() query.where('name').in(["<NAME>","<NAME>"]) params = skip: 10 query = util.formatParams params, User should.exist query.skip query.skip.should.equal 10 done() it 'should ignore invalid number', (done) -> query = User.find() query.where('name').in(["<NAME>","<NAME>"]) params = skip: "blah" query = util.formatParams params, User should.not.exist query.skip done() it 'should ignore 0 number', (done) -> query = User.find() query.where('name').in(["<NAME>","<NAME>"]) params = skip: 0 query = util.formatParams params, User should.not.exist query.skip done() describe 'limit', -> it 'should work with valid string number', (done) -> query = User.find() query.where('name').in(["<NAME>","<NAME>"]) params = limit: "10" query = util.formatParams params, User should.exist query.limit query.limit.should.equal 10 done() it 'should work with valid number', (done) -> query = User.find() query.where('name').in(["<NAME>","<NAME>"]) params = limit: 10 query = util.formatParams params, User should.exist query.limit query.limit.should.equal 10 done() it 'should ignore invalid number', (done) -> query = User.find() query.where('name').in(["<NAME>","<NAME>"]) params = limit: "blah" query = util.formatParams params, User should.not.exist query.limit done() it 'should ignore 0 number', (done) -> query = User.find() query.where('name').in(["<NAME>","<NAME>"]) params = limit: 0 query = util.formatParams params, User should.not.exist query.limit done() describe 'sort', -> it 'should work with valid field name', (done) -> query = User.find() query.where('name').in(["<NAME>","<NAME>"]) params = sort: "score" query = util.formatParams params, User should.exist query.sort query.sort.should.eql ['score'] done() it 'should work with valid field name and - operator', (done) -> query = User.find() query.where('name').in(["<NAME>","<NAME>"]) params = sort: "-score" query = util.formatParams params, User should.exist query.sort query.sort.should.eql ['-score'] done() it 'should ignore invalid field name', (done) -> query = User.find() query.where('name').in(["<NAME>","<NAME>"]) params = sort: "blah" query = util.formatParams params, User query.sort.should.eql [] done() it 'should ignore invalid field name with - operator', (done) -> query = User.find() query.where('name').in(["<NAME>","<NAME>"]) params = sort: "-blah" query = util.formatParams params, User query.sort.should.eql [] done() describe 'populate', -> it 'should work with valid field name', (done) -> query = User.find() query.where('name').in(["<NAME>","<NAME>"]) params = populate: "bestFriend" query = util.formatParams params, User should.exist query.populate query.populate.should.eql ["bestFriend"] done() it 'should ignore invalid field name', (done) -> query = User.find() query.where('name').in(["<NAME>","<NAME>"]) params = populate: "blah" query = util.formatParams params, User query.populate.should.eql [] done() describe 'where', -> it 'should work with valid field name', (done) -> query = User.find() params = name: "<NAME>" score: 100 query = util.formatParams params, User should.exist query.conditions query.conditions.should.eql name: "<NAME>" score: 100 done() it 'should ignore invalid field names from valid', (done) -> query = User.find() params = blah: "<NAME>" score: 100 query = util.formatParams params, User should.exist query.conditions query.conditions.should.eql score: 100 done() it 'should ignore invalid field names completely', (done) -> query = User.find() params = blah: "<NAME>" zzz: 100 query = util.formatParams params, User should.exist query.conditions should.not.exist query.conditions.blah should.not.exist query.conditions.zzz done()
true
{util} = crudify = require '../' should = require 'should' require 'mocha' db = require './fixtures/connection' User = db.model 'User' describe 'formatParams()', -> describe 'flags', -> it 'should create flags object', (done) -> query = User.find() query.where('name').in(["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]) params = {} query = util.formatParams params, User should.exist query.flags done() describe 'skip', -> it 'should work with valid string number', (done) -> query = User.find() query.where('name').in(["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]) params = skip: "10" query = util.formatParams params, User should.exist query.skip query.skip.should.equal 10 done() it 'should work with valid number', (done) -> query = User.find() query.where('name').in(["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]) params = skip: 10 query = util.formatParams params, User should.exist query.skip query.skip.should.equal 10 done() it 'should ignore invalid number', (done) -> query = User.find() query.where('name').in(["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]) params = skip: "blah" query = util.formatParams params, User should.not.exist query.skip done() it 'should ignore 0 number', (done) -> query = User.find() query.where('name').in(["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]) params = skip: 0 query = util.formatParams params, User should.not.exist query.skip done() describe 'limit', -> it 'should work with valid string number', (done) -> query = User.find() query.where('name').in(["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]) params = limit: "10" query = util.formatParams params, User should.exist query.limit query.limit.should.equal 10 done() it 'should work with valid number', (done) -> query = User.find() query.where('name').in(["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]) params = limit: 10 query = util.formatParams params, User should.exist query.limit query.limit.should.equal 10 done() it 'should ignore invalid number', (done) -> query = User.find() query.where('name').in(["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]) params = limit: "blah" query = util.formatParams params, User should.not.exist query.limit done() it 'should ignore 0 number', (done) -> query = User.find() query.where('name').in(["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]) params = limit: 0 query = util.formatParams params, User should.not.exist query.limit done() describe 'sort', -> it 'should work with valid field name', (done) -> query = User.find() query.where('name').in(["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]) params = sort: "score" query = util.formatParams params, User should.exist query.sort query.sort.should.eql ['score'] done() it 'should work with valid field name and - operator', (done) -> query = User.find() query.where('name').in(["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]) params = sort: "-score" query = util.formatParams params, User should.exist query.sort query.sort.should.eql ['-score'] done() it 'should ignore invalid field name', (done) -> query = User.find() query.where('name').in(["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]) params = sort: "blah" query = util.formatParams params, User query.sort.should.eql [] done() it 'should ignore invalid field name with - operator', (done) -> query = User.find() query.where('name').in(["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]) params = sort: "-blah" query = util.formatParams params, User query.sort.should.eql [] done() describe 'populate', -> it 'should work with valid field name', (done) -> query = User.find() query.where('name').in(["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]) params = populate: "bestFriend" query = util.formatParams params, User should.exist query.populate query.populate.should.eql ["bestFriend"] done() it 'should ignore invalid field name', (done) -> query = User.find() query.where('name').in(["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI"]) params = populate: "blah" query = util.formatParams params, User query.populate.should.eql [] done() describe 'where', -> it 'should work with valid field name', (done) -> query = User.find() params = name: "PI:NAME:<NAME>END_PI" score: 100 query = util.formatParams params, User should.exist query.conditions query.conditions.should.eql name: "PI:NAME:<NAME>END_PI" score: 100 done() it 'should ignore invalid field names from valid', (done) -> query = User.find() params = blah: "PI:NAME:<NAME>END_PI" score: 100 query = util.formatParams params, User should.exist query.conditions query.conditions.should.eql score: 100 done() it 'should ignore invalid field names completely', (done) -> query = User.find() params = blah: "PI:NAME:<NAME>END_PI" zzz: 100 query = util.formatParams params, User should.exist query.conditions should.not.exist query.conditions.blah should.not.exist query.conditions.zzz done()
[ { "context": "# Copyright (c) 2008-2013 Michael Dvorkin and contributors.\n#\n# Eatech CRM is freely distri", "end": 41, "score": 0.9998661875724792, "start": 26, "tag": "NAME", "value": "Michael Dvorkin" } ]
app/assets/javascripts/crm_chosen.js.coffee
amiteatech/fat_free_crm
0
# Copyright (c) 2008-2013 Michael Dvorkin and contributors. # # Eatech CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ (($) -> window.crm ||= {} # Use the 'ajax_chosen' class on select boxes that need to lookup values from server # Each select should have a 'data-url' attribute to specify the autocomplete path #---------------------------------------------------------------------------- crm.makeAjaxChosen = -> $("select.ajax_chosen").each -> $(this).ajaxChosen({ url: $(this).data('url') jsonTermKey: "auto_complete_query", minTermLength: 2}, null, {allow_single_deselect: true, show_on_activate: true} ) $(document).ready -> crm.makeAjaxChosen() $(document).ajaxComplete -> crm.makeAjaxChosen() ) jQuery
167541
# Copyright (c) 2008-2013 <NAME> and contributors. # # Eatech CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ (($) -> window.crm ||= {} # Use the 'ajax_chosen' class on select boxes that need to lookup values from server # Each select should have a 'data-url' attribute to specify the autocomplete path #---------------------------------------------------------------------------- crm.makeAjaxChosen = -> $("select.ajax_chosen").each -> $(this).ajaxChosen({ url: $(this).data('url') jsonTermKey: "auto_complete_query", minTermLength: 2}, null, {allow_single_deselect: true, show_on_activate: true} ) $(document).ready -> crm.makeAjaxChosen() $(document).ajaxComplete -> crm.makeAjaxChosen() ) jQuery
true
# Copyright (c) 2008-2013 PI:NAME:<NAME>END_PI and contributors. # # Eatech CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ (($) -> window.crm ||= {} # Use the 'ajax_chosen' class on select boxes that need to lookup values from server # Each select should have a 'data-url' attribute to specify the autocomplete path #---------------------------------------------------------------------------- crm.makeAjaxChosen = -> $("select.ajax_chosen").each -> $(this).ajaxChosen({ url: $(this).data('url') jsonTermKey: "auto_complete_query", minTermLength: 2}, null, {allow_single_deselect: true, show_on_activate: true} ) $(document).ready -> crm.makeAjaxChosen() $(document).ajaxComplete -> crm.makeAjaxChosen() ) jQuery
[ { "context": "sel and Bootstrap 3 modals.\n@version 1.0.0\n@author Se7enSky studio <info@se7ensky.com>\n@dependencies\n -", "end": 130, "score": 0.5062513947486877, "start": 128, "tag": "USERNAME", "value": "Se" }, { "context": "3 modals.\n@version 1.0.0\n@author Se7enSky studio <inf...
jquery-owlbox.coffee
SE7ENSKY/jquery-owlbox
0
### @name jquery-owlbox @description Lightbox-like gallery, based on owlCarousel and Bootstrap 3 modals. @version 1.0.0 @author Se7enSky studio <info@se7ensky.com> @dependencies - [owlCarousel](http://owlgraphic.com/owlcarousel/) - [Bootstrap 3 modals](http://getbootstrap.com/javascript/#modals) ### ###! jquery-owlbox 1.0.0 http://github.com/Se7enSky/jquery-owlbox### plugin = ($) -> "use strict" $.fn.owlbox = -> @each -> $(@).click (e) -> e.preventDefault() group = $(@).attr "rel" $items = if group then $("a[rel='#{group}'][href]") else $(@) currentIndex = $items.index(@) items = (for item in $items thumb: $(item).find("img").attr("src") or $(item).find("img").attr("data-src") big: $(item).attr("href") ) popupHTML = """ <div aria-hidden="true" role="dialog" class="gallery-popup modal fade" data-keyboard="true" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button aria-hidden="true" data-dismiss="modal" type="button" class="close"></button> <div class="counter small">Фотография <span>1</span> из <span>#{items.length}</span></div> </div> <div class="modal-body"> <div class="owl_synced"> <ul class="gallery owl owl_single carousel"> """ popupHTML += """ <li class="gallery-item item"> <div class="gallery-item__link"> <img data-src="#{item.big}" alt="" class="lazyOwl"/> </div> </li> """ for item in items popupHTML += """ </ul> <ul class="gallery owl owl_thumbs carousel"> """ popupHTML += """ <li class="gallery-item item"> <div class="gallery-item__link"> <img data-src="#{item.thumb}" alt="" class="lazyOwl"/> </div> </li> """ for item in items popupHTML += """ </ul> </div> </div> </div> </div> </div> """ $popup = $ popupHTML OWL_SYNCED_CLASS = "owl-item_current" sync1 = $popup.find(".owl:first") sync2 = $popup.find(".owl:last") center = (number) -> sync2visible = sync2.data("owlCarousel").visibleItems return unless sync2visible num = number found = false for i of sync2visible found = true if num is sync2visible[i] if found is false if num > sync2visible[sync2visible.length - 1] sync2.trigger "owl.goTo", num - sync2visible.length + 2 else num = 0 if num - 1 is -1 sync2.trigger "owl.goTo", num else if num is sync2visible[sync2visible.length - 1] sync2.trigger "owl.goTo", sync2visible[1] else sync2.trigger "owl.goTo", num - 1 if num is sync2visible[0] sync1.owlCarousel singleItem: true slideSpeed: 394 navigation: on pagination: off navigationText: ["",""] rewindNav: off lazyLoad: on afterAction: (el) -> current = @currentItem $popup.find(".counter span:first").text current + 1 sync2.find(".owl-item").removeClass(OWL_SYNCED_CLASS).eq(current).addClass OWL_SYNCED_CLASS center current if sync2.data("owlCarousel") afterInit: (el) -> window.owl1 = @ @jumpTo currentIndex sync2.owlCarousel navigation: on pagination: off navigationText: ["",""] rewindNav: off lazyLoad: on items: 7 itemsDesktop: off itemsDesktopSmall: off itemsTablet: off itemsTabletSmall: off itemsMobile: off afterInit: (el) -> window.owl2 = @ sync2.on "click", ".owl-item", (e) -> e.preventDefault() sync1.trigger "owl.goTo", $(@).data("owlItem") keysHandler = (e) -> switch e.which when 37 # left sync1.trigger "owl.prev" e.preventDefault() when 39 # right sync1.trigger "owl.next" e.preventDefault() $("section.modals").append $popup $popup.modal "show" $("body").on "keydown", keysHandler $popup.on "hidden.bs.modal", -> $popup.remove() $("body").off "keydown", keysHandler # UMD if typeof define is 'function' and define.amd then define(['jquery'], plugin) else plugin(jQuery)
77849
### @name jquery-owlbox @description Lightbox-like gallery, based on owlCarousel and Bootstrap 3 modals. @version 1.0.0 @author Se7enSky studio <<EMAIL>> @dependencies - [owlCarousel](http://owlgraphic.com/owlcarousel/) - [Bootstrap 3 modals](http://getbootstrap.com/javascript/#modals) ### ###! jquery-owlbox 1.0.0 http://github.com/Se7enSky/jquery-owlbox### plugin = ($) -> "use strict" $.fn.owlbox = -> @each -> $(@).click (e) -> e.preventDefault() group = $(@).attr "rel" $items = if group then $("a[rel='#{group}'][href]") else $(@) currentIndex = $items.index(@) items = (for item in $items thumb: $(item).find("img").attr("src") or $(item).find("img").attr("data-src") big: $(item).attr("href") ) popupHTML = """ <div aria-hidden="true" role="dialog" class="gallery-popup modal fade" data-keyboard="true" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button aria-hidden="true" data-dismiss="modal" type="button" class="close"></button> <div class="counter small">Фотография <span>1</span> из <span>#{items.length}</span></div> </div> <div class="modal-body"> <div class="owl_synced"> <ul class="gallery owl owl_single carousel"> """ popupHTML += """ <li class="gallery-item item"> <div class="gallery-item__link"> <img data-src="#{item.big}" alt="" class="lazyOwl"/> </div> </li> """ for item in items popupHTML += """ </ul> <ul class="gallery owl owl_thumbs carousel"> """ popupHTML += """ <li class="gallery-item item"> <div class="gallery-item__link"> <img data-src="#{item.thumb}" alt="" class="lazyOwl"/> </div> </li> """ for item in items popupHTML += """ </ul> </div> </div> </div> </div> </div> """ $popup = $ popupHTML OWL_SYNCED_CLASS = "owl-item_current" sync1 = $popup.find(".owl:first") sync2 = $popup.find(".owl:last") center = (number) -> sync2visible = sync2.data("owlCarousel").visibleItems return unless sync2visible num = number found = false for i of sync2visible found = true if num is sync2visible[i] if found is false if num > sync2visible[sync2visible.length - 1] sync2.trigger "owl.goTo", num - sync2visible.length + 2 else num = 0 if num - 1 is -1 sync2.trigger "owl.goTo", num else if num is sync2visible[sync2visible.length - 1] sync2.trigger "owl.goTo", sync2visible[1] else sync2.trigger "owl.goTo", num - 1 if num is sync2visible[0] sync1.owlCarousel singleItem: true slideSpeed: 394 navigation: on pagination: off navigationText: ["",""] rewindNav: off lazyLoad: on afterAction: (el) -> current = @currentItem $popup.find(".counter span:first").text current + 1 sync2.find(".owl-item").removeClass(OWL_SYNCED_CLASS).eq(current).addClass OWL_SYNCED_CLASS center current if sync2.data("owlCarousel") afterInit: (el) -> window.owl1 = @ @jumpTo currentIndex sync2.owlCarousel navigation: on pagination: off navigationText: ["",""] rewindNav: off lazyLoad: on items: 7 itemsDesktop: off itemsDesktopSmall: off itemsTablet: off itemsTabletSmall: off itemsMobile: off afterInit: (el) -> window.owl2 = @ sync2.on "click", ".owl-item", (e) -> e.preventDefault() sync1.trigger "owl.goTo", $(@).data("owlItem") keysHandler = (e) -> switch e.which when 37 # left sync1.trigger "owl.prev" e.preventDefault() when 39 # right sync1.trigger "owl.next" e.preventDefault() $("section.modals").append $popup $popup.modal "show" $("body").on "keydown", keysHandler $popup.on "hidden.bs.modal", -> $popup.remove() $("body").off "keydown", keysHandler # UMD if typeof define is 'function' and define.amd then define(['jquery'], plugin) else plugin(jQuery)
true
### @name jquery-owlbox @description Lightbox-like gallery, based on owlCarousel and Bootstrap 3 modals. @version 1.0.0 @author Se7enSky studio <PI:EMAIL:<EMAIL>END_PI> @dependencies - [owlCarousel](http://owlgraphic.com/owlcarousel/) - [Bootstrap 3 modals](http://getbootstrap.com/javascript/#modals) ### ###! jquery-owlbox 1.0.0 http://github.com/Se7enSky/jquery-owlbox### plugin = ($) -> "use strict" $.fn.owlbox = -> @each -> $(@).click (e) -> e.preventDefault() group = $(@).attr "rel" $items = if group then $("a[rel='#{group}'][href]") else $(@) currentIndex = $items.index(@) items = (for item in $items thumb: $(item).find("img").attr("src") or $(item).find("img").attr("data-src") big: $(item).attr("href") ) popupHTML = """ <div aria-hidden="true" role="dialog" class="gallery-popup modal fade" data-keyboard="true" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button aria-hidden="true" data-dismiss="modal" type="button" class="close"></button> <div class="counter small">Фотография <span>1</span> из <span>#{items.length}</span></div> </div> <div class="modal-body"> <div class="owl_synced"> <ul class="gallery owl owl_single carousel"> """ popupHTML += """ <li class="gallery-item item"> <div class="gallery-item__link"> <img data-src="#{item.big}" alt="" class="lazyOwl"/> </div> </li> """ for item in items popupHTML += """ </ul> <ul class="gallery owl owl_thumbs carousel"> """ popupHTML += """ <li class="gallery-item item"> <div class="gallery-item__link"> <img data-src="#{item.thumb}" alt="" class="lazyOwl"/> </div> </li> """ for item in items popupHTML += """ </ul> </div> </div> </div> </div> </div> """ $popup = $ popupHTML OWL_SYNCED_CLASS = "owl-item_current" sync1 = $popup.find(".owl:first") sync2 = $popup.find(".owl:last") center = (number) -> sync2visible = sync2.data("owlCarousel").visibleItems return unless sync2visible num = number found = false for i of sync2visible found = true if num is sync2visible[i] if found is false if num > sync2visible[sync2visible.length - 1] sync2.trigger "owl.goTo", num - sync2visible.length + 2 else num = 0 if num - 1 is -1 sync2.trigger "owl.goTo", num else if num is sync2visible[sync2visible.length - 1] sync2.trigger "owl.goTo", sync2visible[1] else sync2.trigger "owl.goTo", num - 1 if num is sync2visible[0] sync1.owlCarousel singleItem: true slideSpeed: 394 navigation: on pagination: off navigationText: ["",""] rewindNav: off lazyLoad: on afterAction: (el) -> current = @currentItem $popup.find(".counter span:first").text current + 1 sync2.find(".owl-item").removeClass(OWL_SYNCED_CLASS).eq(current).addClass OWL_SYNCED_CLASS center current if sync2.data("owlCarousel") afterInit: (el) -> window.owl1 = @ @jumpTo currentIndex sync2.owlCarousel navigation: on pagination: off navigationText: ["",""] rewindNav: off lazyLoad: on items: 7 itemsDesktop: off itemsDesktopSmall: off itemsTablet: off itemsTabletSmall: off itemsMobile: off afterInit: (el) -> window.owl2 = @ sync2.on "click", ".owl-item", (e) -> e.preventDefault() sync1.trigger "owl.goTo", $(@).data("owlItem") keysHandler = (e) -> switch e.which when 37 # left sync1.trigger "owl.prev" e.preventDefault() when 39 # right sync1.trigger "owl.next" e.preventDefault() $("section.modals").append $popup $popup.modal "show" $("body").on "keydown", keysHandler $popup.on "hidden.bs.modal", -> $popup.remove() $("body").off "keydown", keysHandler # UMD if typeof define is 'function' and define.amd then define(['jquery'], plugin) else plugin(jQuery)
[ { "context": " <div id=\"avatar\"></div>\n <h1 id=\"name\"><span>Dan Daniels</span></h1>\n <button id=\"follow\" class=\"primar", "end": 9600, "score": 0.999664306640625, "start": 9589, "tag": "NAME", "value": "Dan Daniels" }, { "context": "onducted a successful rescue operati...
spec/poly-test/full.coffee
gss/document
13
DEMOS = FACE_DETECTION_SECTION: """ <section class="demo"> <h1 class="title" id="title">We've already broken ground on more than 30 layout filters.</h1> <h2 class="subtitle">Before we invest the hard work of making each bullet-proof, we need to know this is wanted & needed, become a founding member & help us help you!</h2> <img class="image" src="image.png"> </section> <style type="text/gss" scoped> [md] == 72 !require; [md-sub] == 8; $[width] == $[intrinsic-width]; .demo { @if $[width] < 500 { .title { &margin-top == [md-sub]; } } @else { .title { &margin-top == [md]; &padding-top == ([md-sub] * 6) - 8; } } } </style> """ SCOPING: """ <button id="box1" class="box w-virtual" onclick=" this.setAttribute('class', 'box ' + (this.className.indexOf('wo') > -1 ? 'w-virtual' : 'wo-virtual'))"> <div class="innie" id="innie1" ></div> </button> <button id="box2" class="box wo-virtual" onclick="this.setAttribute('class', 'box ' + (this.className.indexOf('wo') > -1 && 'w-virtual' || 'wo-virtual'))"> <div class="innie" id="innie2" ></div> </button> <button id="box3" class="box w-virtual" onclick="this.setAttribute('class', 'box ' + (this.className.indexOf('wo') > -1 && 'w-virtual' || 'wo-virtual'))"> <div class="innie" id="innie3" ></div> </button> <style> * { box-sizing: border-box; } .box { background-color: hsl(220,50%,50%); } .wo-virtual .innie { background-color: hsl(360,100%,50%); } .w-virtual .innie { background-color: hsl(180,100%,50%); } .w-virtual:after { content: 'W/ SCOPED VIRTUAL'; font-size: 40px; top: 32px; left: 32px; position:absolute; } .wo-virtual:after { content: 'W/O VIRTUAL'; font-size: 40px; top: 32px; left: 32px; position:absolute; } </style> <style type="text/gss"> $[left] == 0; $[top] == 0; $[height] == $[intrinsic-height]; $[width] == $[intrinsic-width]; .box { "zone" { @h |-(&)-| in(&.w-virtual) gap(20); @h |(&.w-virtual .innie)|; } } .box.w-virtual { @v |-(&"zone")-| in(&) gap(20); @v |(& .innie)| in(&"zone"); } .box.wo-virtual { @h |-(& .innie)-| in(&) gap(20); @v |-(& .innie)-| in(&) gap(20); } @v |-10-(.box)-20-... in($) { @h |~100~(&)~100~| in($); &[x] + 20 == &:next[x]; &[right] - 20 == &:next[right]; height: == 300; } </style> """, GSS1: """ <style scoped> header { background: orange; height: 50px; } main { background: yellow; height: 100px; z-index: 10; } footer { background: red; width: 10px; height: 20px; } aside { background: blue; width: 100px; } ul li { list-style: none; background: green; top: 5px; } </style> <style type="text/gss" scoped> // plural selectors can be used as singular, a la jQ [left-margin] == (main)[right]; // global condition with nested rules @if (main)[top] > 50 { main { background: blue; } } header { ::[left] == 0; // condition inside css rule @if ($[intrinsic-width] > $[intrinsic-height]) { ::[width] == $[intrinsic-width] / 4; opacity: 0.5; } @else { ::[width] == $[intrinsic-width] / 2; opacity: 0.75; } } footer { ::[top] == $(main)[height]; ::[height] == $[intrinsic-height] * 2; } aside { ::[left] == ($ main)[right]; ::[height] == 100; ::[top] == $(header)[intrinsic-height] + $(header)[intrinsic-y]; } main { // Bind things to scroll position ::[top] == $scroll-top;// + header[intrinsic-y]; ::[width] == $(aside)[intrinsic-width]; ::[left] == $(header)[right]; ::[height] == $[intrinsic-height] - $(header)[intrinsic-height]; } // Custom combinators ul li !~ li { ::[height] == 30; // FIXME: Regular css style is never removed (needs specificity sorting and groupping); background-color: yellowgreen; } // Chains ul li { // justify by using variable ::[width] == $[li-width]; :previous[right] == &[left]; :last[right] == $[intrinsic-width] - 16; :first[left] == 0; } </style> <header id="header"></header> <main id="main"> <ul> <li id="li1">1</li> <li id="li2">2</li> <li id="li3">3</li> </ul> </main> <aside id="aside"></aside> <footer id="footer"></footer> """ PROFILE_CARD: """ <style> #profile-card-demo * { box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; } #profile-card-demo { background-color: hsl(3, 18%, 43%); } #profile-card-demo * { -webkit-backface-visibility: hidden; margin: 0px; padding: 0px; outline: none; } #background { background-color: hsl(3, 18%, 43%); position: absolute; top: 0px; bottom: 0px; right: 0px; left: 0px; z-index: -1; background-image: url('assets/cover.jpg'); background-size: cover; background-position: 50% 50%; opacity: .7; -webkit-filter: blur(5px) contrast(.7); } #cover { background-color: #ccc; background-image: url('assets/cover.jpg'); background-size: cover; background-position: 50% 50%; } #avatar { background-image: url('assets/avatar.jpg'); background-size: cover; background-position: 50% 50%; border: 10px solid hsl(39, 40%, 90%); box-shadow: 0 1px 1px hsla(0,0%,0%,.5); } #profile-card-demo h1 { color: white; text-shadow: 0 1px 1px hsla(0,0%,0%,.5); font-size: 40px; line-height: 1.5em; font-family: "adelle",georgia,serif; font-style: normal; font-weight: 400; } #profile-card-demo button { color: hsl(3, 18%, 43%); background-color: hsl(39, 40%, 90%); text-shadow: 0 1px hsla(3, 18%, 100%, .5); font-family: "proxima-nova-soft",sans-serif; font-style: normal; font-weight: 700; font-size: 14px; text-transform:uppercase; letter-spacing:.1em; border: none; } #profile-card-demo button.primary { background-color: #e38f71; color: white; text-shadow: 0 -1px hsla(3, 18%, 43%, .5); } #profile-card-demo #profile-card, .card { background-color: hsl(39, 40%, 90%); border: 1px solid hsla(0,0%,100%,.6); box-shadow: 0 5px 8px hsla(0,0%,0%,.3); } </style> <style type="text/gss" scoped> /* vars */ [gap] == 20 !required; [flex-gap] >= [gap] * 2 !required; [radius] == 10 !required; [outer-radius] == [radius] * 2 !required; /* scope-as-window for tests */ $[left] == 0; $[top] == 0; $[width] == $[intrinsic-width] !require; $[height] == $[intrinsic-height] !require; /* elements */ #profile-card { &width == $[width] - 480 !strong; &height == $[height] - 480; &[center-x] == $[center-x]; &[center-y] == $[center-y]; &border-radius == [outer-radius]; } #avatar { &height == 160 !required; &width == ::[height]; &border-radius == ::[height] / 2; } #name { &height == ::[intrinsic-height] !required; &width == ::[intrinsic-width] !required; } #cover { &border-radius == [radius]; } button { &width == ::[intrinsic-width] !required; &height == ::[intrinsic-height] !required; &padding == [gap]; &padding-top == [gap] / 2; &padding-bottom == [gap] / 2; &border-radius == [radius]; } @h |~-~(#name)~-~| in(#cover) gap([gap]*2) !strong; /* landscape profile-card */ @if #profile-card[width] >= #profile-card[height] { @v | - (#avatar) - (#name) - | in(#cover) gap([gap]) outer-gap([flex-gap]) { &[center-x] == ($ #cover)[center-x]; } @h |-10-(#cover)-10-| in(#profile-card); @v | -10- (#cover) - (#follow) - | in(#profile-card) gap([gap]) !strong; #follow[center-x] == #profile-card[center-x]; @h |-(#message)~-~(#follow)~-~(#following)-(#followers)-| in(#profile-card) gap([gap]) !strong { :next[top] == &top; } } /* portrait profile-card */ @else { @v | - (#avatar) - (#name) - (#follow) - (#message) - (#following) - (#followers) - | in(#cover) gap([gap]) outer-gap([flex-gap]) !strong { &[center-x] == ($ #profile-card)[center-x]; } @h |-10-(#cover)-10-| in(#profile-card) !strong; @v |-10-(#cover)-10-| in(#profile-card) !strong; } </style> <div id="background"></div> <div id="profile-card"></div> <div id="cover"></div> <div id="avatar"></div> <h1 id="name"><span>Dan Daniels</span></h1> <button id="follow" class="primary">Follow</button> <button id="following">Following</button> <button id="followers">Followers</button> <button id="message">Message</button> """ ADAPTIVE_ASPECT: """ <header id="header">header</header> <article id="article"> <p>ISTANBUL — Forty-nine Turkish hostages who had been held for months in Iraq by Islamic State militants were returned to Turkey on Saturday after what Turkey said was a covert operation led by its intelligence agency.</p> <p>The hostages, including diplomats and their families, had been seized in June from the Turkish Consulate in Mosul, in northern Iraq.</p> <p>“The Turkish intelligence agency has followed the situation very sensitively and patiently since the beginning and, as a result, conducted a successful rescue operation,” President Recep Tayyip Erdogan said in a statement Saturday.</p> <p>The details of the hostages’ release were unclear. The semiofficial Turkish news agency Anadolu reported that Turkey had not paid ransom or engaged in a military operation, but said it had used drones to track the hostages, who had been moved at least eight times during their 101 days in captivity.</p> <p>Times Topic: Islamic State in Iraq and Syria (ISIS) Back and Forth, Wearily, Across the ISIS BorderSEPT. 20, 2014 The agency said that Turkish intelligence teams had tried five times to rescue the hostages, but that each attempt had been thwarted by clashes in the area where they were being held.</p> <p>An employee of the Turkish Consulate in Mosul was greeted by family members. Credit Reuters One senior American official, who asked not to be named, said Saturday that Turkey had not notified the United States before securing the return of the hostages, or made a specific request for American military help in connection with their release.</p> <p>“I am sharing joyful news, which as a nation we have been waiting for,” Prime Minister Ahmet Davutoglu said in Baku, Azerbaijan, where he was on an official visit.</p> <p>“After intense efforts that lasted days and weeks, in the early hours, our citizens were handed over to us and we brought them back to our country,” he said.</p> <p>The prime minister left Baku for the Turkish province of Urfa, where the freed hostages, who included Consul General Ozturk Yilmaz, other diplomats, children and consulate guards, had been brought from Raqqa, Syria, the de facto headquarters of the Islamic State militants.</p> </article> <footer id="footer">footer</footer> <style> * { box-sizing: border-box; margin: 0; } html { background-color: hsl(0,0%,95%); } article { background-color: hsl(0,0%,99%); padding: 72px; -webkit-column-width: 400px; column-width: 400px; overflow-x: #{window.atob && 'auto' || 'hidden'}; font-size: 20px; line-height: 30px; } header { background-color: hsl(0,0%,90%); padding: 16px; text-align: center; } footer { background-color: hsl(0,0%,85%); padding: 16px; text-align: center; } p { margin-bottom: 1em; } </style> <style type="text/gss"> // vertical article $[left] == 0; $[top] == 0; $[height] == $[intrinsic-height]; $[width] == $[intrinsic-width]; $[article-gap] >= 16; @if $[intrinsic-width] < $[intrinsic-height] { @h |-(article)-| gap($[article-gap]) in($) { height: == &[intrinsic-height]; width: <= 800; } @v | -72- (header) (article) (footer) in($); header, footer { height: == 72; @h |(&)| in($ article); } } // horizontal article @else { @v |-(article)-| gap($[article-gap]) in($) { width: == &[intrinsic-width]; height: <= 600; } @h | -16- (header) (footer) (article) in($); header, footer { width: == 72; @v |(&)| in($ article); } } </style> """ DEMOS.ADAPTIVE_ASPECT_LINEAR = DEMOS.ADAPTIVE_ASPECT. replace('$[intrinsic-width] < $[intrinsic-height]', '$[width] < $[height]') roughAssert = (a, b, threshold = 15) -> expect(Math.abs(a - b) < threshold).to.eql true assert = chai.assert expect = chai.expect remove = (el) -> el?.parentNode?.removeChild(el) describe 'Full page tests', -> engine = container = null afterEach -> remove(container) engine.destroy() @timeout 100000 for type, index in ['With worker', 'Without worker'] do (type, index) -> describe type, -> it 'scoping', (done) -> container = document.createElement('div') container.style.height = '1000px' container.style.width = '1000px' container.style.position = 'absolute' container.style.overflow = 'auto' container.style.left = 0 container.style.top = 0 window.$engine = engine = new GSS(container, index == 0) document.getElementById('fixtures').appendChild container container.innerHTML = DEMOS.SCOPING engine.then (solution) -> expectation = "$1[height]": 1000 "$1[intrinsic-height]": 1000 "$1[intrinsic-width]": 1000 "$1[width]": 1000 "$1[x]": 0 "$1[y]": 0 "$box1'zone'[height]": 260 "$box1'zone'[width]": 760 "$box1'zone'[x]": 120 "$box1'zone'[y]": 30 "$box1[height]": 300 "$box1[width]": 800 "$box1[x]": 100 "$box1[y]": 10 "$box2[height]": 300 "$box2[width]": 760 "$box2[x]": 120 "$box2[y]": 330 '$box3"zone"[height]': 260 '$box3"zone"[width]': 680 '$box3"zone"[x]': 160 '$box3"zone"[y]': 670 "$box3[height]": 300 "$box3[width]": 720 "$box3[x]": 140 "$box3[y]": 650 "$innie1[height]": 260 "$innie1[width]": 760 "$innie1[x]": 120 "$innie1[y]": 30 "$innie2[height]": 260 "$innie2[width]": 720 "$innie2[x]": 140 "$innie2[y]": 350 "$innie3[height]": 260 "$innie3[width]": 680 "$innie3[x]": 160 "$innie3[y]": 670 for expect, value in expectation assert(engine.values[expect]).to.eql value engine.id('box1').click() engine.then (solution) -> expect(solution['$box1"zone"[height]']).to.eql null expect(solution['$box1"zone"[width]']).to.eql null expect(solution['$box1"zone"[x]']).to.eql null expect(solution['$box1"zone"[y]']).to.eql null engine.id('box1').click() engine.then (solution) -> expect(solution['$box1"zone"[height]']).to.eql 260 expect(solution['$box1"zone"[width]']).to.eql 760 expect(solution['$box1"zone"[x]']).to.eql 120 expect(solution['$box1"zone"[y]']).to.eql 30 engine.id('box2').click() engine.then (solution) -> expect(solution['$box2"zone"[height]']).to.eql 260 expect(solution['$box2"zone"[width]']).to.eql 720 expect(solution['$box2"zone"[x]']).to.eql 140 expect(solution['$box2"zone"[y]']).to.eql 350 engine.id('box2').click() engine.then (solution) -> expect(solution['$box2"zone"[height]']).to.eql null expect(solution['$box2"zone"[width]']).to.eql null expect(solution['$box2"zone"[x]']).to.eql null expect(solution['$box2"zone"[y]']).to.eql null engine.id('box3').click() engine.then (solution) -> expect(solution['$box3"zone"[height]']).to.eql null expect(solution['$box3"zone"[width]']).to.eql null expect(solution['$box3"zone"[x]']).to.eql null expect(solution['$box3"zone"[y]']).to.eql null engine.id('box3').click() engine.then (solution) -> expect(solution['$box3"zone"[height]']).to.eql 260 expect(solution['$box3"zone"[width]']).to.eql 680 expect(solution['$box3"zone"[x]']).to.eql 160 expect(solution['$box3"zone"[y]']).to.eql 670 engine.scope.innerHTML = "" engine.then (solution) -> expect(engine.values).to.eql {} done() @timeout 100000 it 'gss1 demo', (done) -> container = document.createElement('div') container.style.height = '640px' container.style.width = '640px' container.style.position = 'absolute' container.style.overflow = 'auto' container.style.left = 0 container.style.top = 0 window.$engine = engine = new GSS(container, index == 0) document.getElementById('fixtures').appendChild container container.innerHTML = DEMOS.GSS1 engine.then (solution) -> expect(solution['li-width']).to.eql((640 - 16) / 3) expect(solution['$aside[x]']).to.eql(640 / 2 + 100) expect(solution['$header[width]']).to.eql(Math.round(640 / 2)) li = engine.scope.querySelector('ul li:last-child') clone = li.cloneNode() clone.id = 'li4' clone.innerHTML = '4' li.parentNode.appendChild(clone) engine.then (solution) -> expect(Math.round(solution['li-width'])).to.eql((640 - 16) / 4) li = engine.scope.querySelector('ul li:first-child') li.parentNode.removeChild(li) engine.then (solution) -> expect(Math.round solution['li-width']).to.eql((640 - 16) / 3) expect(solution['$li2[x]']).to.eql(0) expect(solution['$li1[x]']).to.eql(null) engine.scope.setAttribute('style', 'width: 1024px; height: 640px') engine.then (solution) -> expect(Math.round solution['li-width']).to.eql(Math.round((1024 - 16) / 3)) expect(solution['$header[width]']).to.eql(1024 / 4) container.innerHTML = "" engine.then (solution) -> done() for type, j in ['with intrinsic condition', 'with linear condition'] do (type, j) -> describe type, (done) -> it 'should handle face detection section', (done) -> container = document.createElement('div') container.id = 'face-demo' window.$engine = engine = new GSS(container, index == 0) document.getElementById('fixtures').appendChild container html = DEMOS.FACE_DETECTION_SECTION if j == 0 html = html.replace('$[width] < 500', '$[intrinsic-width] < 500') container.innerHTML = html container.setAttribute('style', 'height: 640px; width: 640px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> expect(solution).to.eql '$title[margin-top]': 72 '$title[padding-top]': 40 '$face-demo[intrinsic-width]': 640 '$face-demo[width]': 640 'md': 72 'md-sub': 8 container.setAttribute('style', 'height: 640px; width: 400px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> expect(solution['$title[margin-top]']).to.eql 8 expect(solution['$title[padding-top]']).to.eql null expect(solution['$face-demo[intrinsic-width]']).to.eql 400 expect(solution['$face-demo[width]']).to.eql 400 container.innerHTML = "" engine.then (solution) -> expect(solution).to.eql '$title[margin-top]': null '$face-demo[intrinsic-width]': null '$face-demo[width]': null 'md': null 'md-sub': null done() it 'profile card', (done) -> container = document.createElement('div') container.id = 'profile-card-demo' window.$engine = engine = new GSS(container, index == 0) document.getElementById('fixtures').appendChild container container.innerHTML = DEMOS.PROFILE_CARD container.setAttribute('style', 'height: 1024px; width: 768px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> # phantom gives slightly different measurements roughAssert(solution['$follow[y]'], 540) roughAssert(solution['$follow[x]'], 329.5) roughAssert(solution['flex-gap'], 40) container.setAttribute('style', 'height: 768px; width: 1124px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> roughAssert(solution['$follow[x]'], 435, 25) unless window.callPhantom roughAssert(solution['$follow[y]'], 537) container.setAttribute('style', 'height: 1024px; width: 768px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> roughAssert(solution['flex-gap'], 40) roughAssert(solution['$follow[y]'], 544) roughAssert(solution['$follow[x]'], 320) container.setAttribute('style', 'height: 1280px; width: 768px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> roughAssert(solution['$follow[y]'], 668) #roughAssert(solution['$follow[x]'], 329.5) roughAssert(solution['flex-gap'], 158) container.setAttribute('style', 'height: 1024px; width: 768px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> roughAssert(solution['$follow[y]'], 540) roughAssert(solution['flex-gap'], 40) container.innerHTML = "" engine.then (solution) -> expect(engine.values).to.eql {} done() for type, j in ['with intrinsic condition', 'with linear condition'] do (type, j) -> expectation = window.atob && document.body.style.msTouchAction? && 544 || 480 describe type, -> it 'Adaptive aspect', (done) -> container = document.createElement('div') container.style.height = '640px' container.style.width = '640px' container.style.position = 'absolute' overflow = window.atob && 'auto' || 'hidden' container.style.overflow = overflow container.style.left = 0 container.style.top = 0 window.$engine = engine = new GSS(container, index == 0) document.getElementById('fixtures').appendChild container if j == 0 container.innerHTML = DEMOS.ADAPTIVE_ASPECT else container.innerHTML = DEMOS.ADAPTIVE_ASPECT_LINEAR engine.then (solution) -> expect(solution['$article[height]']).to.eql 600 expect(solution['$article[width]']).to.eql expectation expect(solution['$footer[height]']).to.eql 600 expect(solution['$footer[width]']).to.eql 72 expect(solution['$header[height]']).to.eql 600 expect(solution['$header[width]']).to.eql 72 expect(solution['article-gap']).to.eql 20 container.setAttribute('style', "height: 800px; width: 640px; position: absolute; overflow: #{overflow}; left: 0; top: 0") engine.then (solution) -> expect(solution['$article[height]'] > 1400).to.eql true expect(solution['article-gap']).to.eql 16 expect(solution['$article[width]']).to.eql 608 expect(solution['$footer[height]']).to.eql 72 expect(solution['$footer[width]']).to.eql 608 expect(solution['$header[height]']).to.eql 72 expect(solution['$header[width]']).to.eql 608 container.setAttribute('style', "height: 640px; width: 640px; position: absolute; overflow: #{overflow}; left: 0; top: 0") engine.then (solution) -> expect(solution['article-gap']).to.eql 20 expect(solution['$article[height]']).to.eql 600 expect(solution['$article[width]']).to.eql expectation expect(solution['$footer[height]']).to.eql 600 expect(solution['$footer[width]']).to.eql 72 expect(solution['$header[height]']).to.eql 600 expect(solution['$header[width]']).to.eql 72 container.setAttribute('style', "height: 800px; width: 640px; position: absolute; overflow: #{overflow}; left: 0; top: 0") engine.then (solution) -> expect(solution['$article[height]'] > 1400).to.eql true expect(solution['$article[width]']).to.eql 608 expect(solution['$footer[height]']).to.eql 72 expect(solution['$footer[width]']).to.eql 608 expect(solution['$header[height]']).to.eql 72 expect(solution['$header[width]']).to.eql 608 expect(solution['article-gap']).to.eql 16 container.setAttribute('style', "height: 800px; width: 600px; position: absolute; overflow: #{overflow}; left: 0; top: 0") engine.then (solution) -> expect(solution['$article[height]'] > 1400).to.eql true expect(solution['$article[width]']).to.eql 568 expect(solution['$footer[width]']).to.eql 568 expect(solution['$header[width]']).to.eql 568 engine.scope.innerHTML = "" engine.then -> expect(engine.values).to.eql {} done()
158693
DEMOS = FACE_DETECTION_SECTION: """ <section class="demo"> <h1 class="title" id="title">We've already broken ground on more than 30 layout filters.</h1> <h2 class="subtitle">Before we invest the hard work of making each bullet-proof, we need to know this is wanted & needed, become a founding member & help us help you!</h2> <img class="image" src="image.png"> </section> <style type="text/gss" scoped> [md] == 72 !require; [md-sub] == 8; $[width] == $[intrinsic-width]; .demo { @if $[width] < 500 { .title { &margin-top == [md-sub]; } } @else { .title { &margin-top == [md]; &padding-top == ([md-sub] * 6) - 8; } } } </style> """ SCOPING: """ <button id="box1" class="box w-virtual" onclick=" this.setAttribute('class', 'box ' + (this.className.indexOf('wo') > -1 ? 'w-virtual' : 'wo-virtual'))"> <div class="innie" id="innie1" ></div> </button> <button id="box2" class="box wo-virtual" onclick="this.setAttribute('class', 'box ' + (this.className.indexOf('wo') > -1 && 'w-virtual' || 'wo-virtual'))"> <div class="innie" id="innie2" ></div> </button> <button id="box3" class="box w-virtual" onclick="this.setAttribute('class', 'box ' + (this.className.indexOf('wo') > -1 && 'w-virtual' || 'wo-virtual'))"> <div class="innie" id="innie3" ></div> </button> <style> * { box-sizing: border-box; } .box { background-color: hsl(220,50%,50%); } .wo-virtual .innie { background-color: hsl(360,100%,50%); } .w-virtual .innie { background-color: hsl(180,100%,50%); } .w-virtual:after { content: 'W/ SCOPED VIRTUAL'; font-size: 40px; top: 32px; left: 32px; position:absolute; } .wo-virtual:after { content: 'W/O VIRTUAL'; font-size: 40px; top: 32px; left: 32px; position:absolute; } </style> <style type="text/gss"> $[left] == 0; $[top] == 0; $[height] == $[intrinsic-height]; $[width] == $[intrinsic-width]; .box { "zone" { @h |-(&)-| in(&.w-virtual) gap(20); @h |(&.w-virtual .innie)|; } } .box.w-virtual { @v |-(&"zone")-| in(&) gap(20); @v |(& .innie)| in(&"zone"); } .box.wo-virtual { @h |-(& .innie)-| in(&) gap(20); @v |-(& .innie)-| in(&) gap(20); } @v |-10-(.box)-20-... in($) { @h |~100~(&)~100~| in($); &[x] + 20 == &:next[x]; &[right] - 20 == &:next[right]; height: == 300; } </style> """, GSS1: """ <style scoped> header { background: orange; height: 50px; } main { background: yellow; height: 100px; z-index: 10; } footer { background: red; width: 10px; height: 20px; } aside { background: blue; width: 100px; } ul li { list-style: none; background: green; top: 5px; } </style> <style type="text/gss" scoped> // plural selectors can be used as singular, a la jQ [left-margin] == (main)[right]; // global condition with nested rules @if (main)[top] > 50 { main { background: blue; } } header { ::[left] == 0; // condition inside css rule @if ($[intrinsic-width] > $[intrinsic-height]) { ::[width] == $[intrinsic-width] / 4; opacity: 0.5; } @else { ::[width] == $[intrinsic-width] / 2; opacity: 0.75; } } footer { ::[top] == $(main)[height]; ::[height] == $[intrinsic-height] * 2; } aside { ::[left] == ($ main)[right]; ::[height] == 100; ::[top] == $(header)[intrinsic-height] + $(header)[intrinsic-y]; } main { // Bind things to scroll position ::[top] == $scroll-top;// + header[intrinsic-y]; ::[width] == $(aside)[intrinsic-width]; ::[left] == $(header)[right]; ::[height] == $[intrinsic-height] - $(header)[intrinsic-height]; } // Custom combinators ul li !~ li { ::[height] == 30; // FIXME: Regular css style is never removed (needs specificity sorting and groupping); background-color: yellowgreen; } // Chains ul li { // justify by using variable ::[width] == $[li-width]; :previous[right] == &[left]; :last[right] == $[intrinsic-width] - 16; :first[left] == 0; } </style> <header id="header"></header> <main id="main"> <ul> <li id="li1">1</li> <li id="li2">2</li> <li id="li3">3</li> </ul> </main> <aside id="aside"></aside> <footer id="footer"></footer> """ PROFILE_CARD: """ <style> #profile-card-demo * { box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; } #profile-card-demo { background-color: hsl(3, 18%, 43%); } #profile-card-demo * { -webkit-backface-visibility: hidden; margin: 0px; padding: 0px; outline: none; } #background { background-color: hsl(3, 18%, 43%); position: absolute; top: 0px; bottom: 0px; right: 0px; left: 0px; z-index: -1; background-image: url('assets/cover.jpg'); background-size: cover; background-position: 50% 50%; opacity: .7; -webkit-filter: blur(5px) contrast(.7); } #cover { background-color: #ccc; background-image: url('assets/cover.jpg'); background-size: cover; background-position: 50% 50%; } #avatar { background-image: url('assets/avatar.jpg'); background-size: cover; background-position: 50% 50%; border: 10px solid hsl(39, 40%, 90%); box-shadow: 0 1px 1px hsla(0,0%,0%,.5); } #profile-card-demo h1 { color: white; text-shadow: 0 1px 1px hsla(0,0%,0%,.5); font-size: 40px; line-height: 1.5em; font-family: "adelle",georgia,serif; font-style: normal; font-weight: 400; } #profile-card-demo button { color: hsl(3, 18%, 43%); background-color: hsl(39, 40%, 90%); text-shadow: 0 1px hsla(3, 18%, 100%, .5); font-family: "proxima-nova-soft",sans-serif; font-style: normal; font-weight: 700; font-size: 14px; text-transform:uppercase; letter-spacing:.1em; border: none; } #profile-card-demo button.primary { background-color: #e38f71; color: white; text-shadow: 0 -1px hsla(3, 18%, 43%, .5); } #profile-card-demo #profile-card, .card { background-color: hsl(39, 40%, 90%); border: 1px solid hsla(0,0%,100%,.6); box-shadow: 0 5px 8px hsla(0,0%,0%,.3); } </style> <style type="text/gss" scoped> /* vars */ [gap] == 20 !required; [flex-gap] >= [gap] * 2 !required; [radius] == 10 !required; [outer-radius] == [radius] * 2 !required; /* scope-as-window for tests */ $[left] == 0; $[top] == 0; $[width] == $[intrinsic-width] !require; $[height] == $[intrinsic-height] !require; /* elements */ #profile-card { &width == $[width] - 480 !strong; &height == $[height] - 480; &[center-x] == $[center-x]; &[center-y] == $[center-y]; &border-radius == [outer-radius]; } #avatar { &height == 160 !required; &width == ::[height]; &border-radius == ::[height] / 2; } #name { &height == ::[intrinsic-height] !required; &width == ::[intrinsic-width] !required; } #cover { &border-radius == [radius]; } button { &width == ::[intrinsic-width] !required; &height == ::[intrinsic-height] !required; &padding == [gap]; &padding-top == [gap] / 2; &padding-bottom == [gap] / 2; &border-radius == [radius]; } @h |~-~(#name)~-~| in(#cover) gap([gap]*2) !strong; /* landscape profile-card */ @if #profile-card[width] >= #profile-card[height] { @v | - (#avatar) - (#name) - | in(#cover) gap([gap]) outer-gap([flex-gap]) { &[center-x] == ($ #cover)[center-x]; } @h |-10-(#cover)-10-| in(#profile-card); @v | -10- (#cover) - (#follow) - | in(#profile-card) gap([gap]) !strong; #follow[center-x] == #profile-card[center-x]; @h |-(#message)~-~(#follow)~-~(#following)-(#followers)-| in(#profile-card) gap([gap]) !strong { :next[top] == &top; } } /* portrait profile-card */ @else { @v | - (#avatar) - (#name) - (#follow) - (#message) - (#following) - (#followers) - | in(#cover) gap([gap]) outer-gap([flex-gap]) !strong { &[center-x] == ($ #profile-card)[center-x]; } @h |-10-(#cover)-10-| in(#profile-card) !strong; @v |-10-(#cover)-10-| in(#profile-card) !strong; } </style> <div id="background"></div> <div id="profile-card"></div> <div id="cover"></div> <div id="avatar"></div> <h1 id="name"><span><NAME></span></h1> <button id="follow" class="primary">Follow</button> <button id="following">Following</button> <button id="followers">Followers</button> <button id="message">Message</button> """ ADAPTIVE_ASPECT: """ <header id="header">header</header> <article id="article"> <p>ISTANBUL — Forty-nine Turkish hostages who had been held for months in Iraq by Islamic State militants were returned to Turkey on Saturday after what Turkey said was a covert operation led by its intelligence agency.</p> <p>The hostages, including diplomats and their families, had been seized in June from the Turkish Consulate in Mosul, in northern Iraq.</p> <p>“The Turkish intelligence agency has followed the situation very sensitively and patiently since the beginning and, as a result, conducted a successful rescue operation,” President <NAME> said in a statement Saturday.</p> <p>The details of the hostages’ release were unclear. The semiofficial Turkish news agency Anadolu reported that Turkey had not paid ransom or engaged in a military operation, but said it had used drones to track the hostages, who had been moved at least eight times during their 101 days in captivity.</p> <p>Times Topic: Islamic State in Iraq and Syria (ISIS) Back and Forth, Wearily, Across the ISIS BorderSEPT. 20, 2014 The agency said that Turkish intelligence teams had tried five times to rescue the hostages, but that each attempt had been thwarted by clashes in the area where they were being held.</p> <p>An employee of the Turkish Consulate in Mosul was greeted by family members. Credit Reuters One senior American official, who asked not to be named, said Saturday that Turkey had not notified the United States before securing the return of the hostages, or made a specific request for American military help in connection with their release.</p> <p>“I am sharing joyful news, which as a nation we have been waiting for,” Prime Minister <NAME> said in Baku, Azerbaijan, where he was on an official visit.</p> <p>“After intense efforts that lasted days and weeks, in the early hours, our citizens were handed over to us and we brought them back to our country,” he said.</p> <p>The prime minister left Baku for the Turkish province of Urfa, where the freed hostages, who included Consul General O<NAME>, other diplomats, children and consulate guards, had been brought from Raqqa, Syria, the de facto headquarters of the Islamic State militants.</p> </article> <footer id="footer">footer</footer> <style> * { box-sizing: border-box; margin: 0; } html { background-color: hsl(0,0%,95%); } article { background-color: hsl(0,0%,99%); padding: 72px; -webkit-column-width: 400px; column-width: 400px; overflow-x: #{window.atob && 'auto' || 'hidden'}; font-size: 20px; line-height: 30px; } header { background-color: hsl(0,0%,90%); padding: 16px; text-align: center; } footer { background-color: hsl(0,0%,85%); padding: 16px; text-align: center; } p { margin-bottom: 1em; } </style> <style type="text/gss"> // vertical article $[left] == 0; $[top] == 0; $[height] == $[intrinsic-height]; $[width] == $[intrinsic-width]; $[article-gap] >= 16; @if $[intrinsic-width] < $[intrinsic-height] { @h |-(article)-| gap($[article-gap]) in($) { height: == &[intrinsic-height]; width: <= 800; } @v | -72- (header) (article) (footer) in($); header, footer { height: == 72; @h |(&)| in($ article); } } // horizontal article @else { @v |-(article)-| gap($[article-gap]) in($) { width: == &[intrinsic-width]; height: <= 600; } @h | -16- (header) (footer) (article) in($); header, footer { width: == 72; @v |(&)| in($ article); } } </style> """ DEMOS.ADAPTIVE_ASPECT_LINEAR = DEMOS.ADAPTIVE_ASPECT. replace('$[intrinsic-width] < $[intrinsic-height]', '$[width] < $[height]') roughAssert = (a, b, threshold = 15) -> expect(Math.abs(a - b) < threshold).to.eql true assert = chai.assert expect = chai.expect remove = (el) -> el?.parentNode?.removeChild(el) describe 'Full page tests', -> engine = container = null afterEach -> remove(container) engine.destroy() @timeout 100000 for type, index in ['With worker', 'Without worker'] do (type, index) -> describe type, -> it 'scoping', (done) -> container = document.createElement('div') container.style.height = '1000px' container.style.width = '1000px' container.style.position = 'absolute' container.style.overflow = 'auto' container.style.left = 0 container.style.top = 0 window.$engine = engine = new GSS(container, index == 0) document.getElementById('fixtures').appendChild container container.innerHTML = DEMOS.SCOPING engine.then (solution) -> expectation = "$1[height]": 1000 "$1[intrinsic-height]": 1000 "$1[intrinsic-width]": 1000 "$1[width]": 1000 "$1[x]": 0 "$1[y]": 0 "$box1'zone'[height]": 260 "$box1'zone'[width]": 760 "$box1'zone'[x]": 120 "$box1'zone'[y]": 30 "$box1[height]": 300 "$box1[width]": 800 "$box1[x]": 100 "$box1[y]": 10 "$box2[height]": 300 "$box2[width]": 760 "$box2[x]": 120 "$box2[y]": 330 '$box3"zone"[height]': 260 '$box3"zone"[width]': 680 '$box3"zone"[x]': 160 '$box3"zone"[y]': 670 "$box3[height]": 300 "$box3[width]": 720 "$box3[x]": 140 "$box3[y]": 650 "$innie1[height]": 260 "$innie1[width]": 760 "$innie1[x]": 120 "$innie1[y]": 30 "$innie2[height]": 260 "$innie2[width]": 720 "$innie2[x]": 140 "$innie2[y]": 350 "$innie3[height]": 260 "$innie3[width]": 680 "$innie3[x]": 160 "$innie3[y]": 670 for expect, value in expectation assert(engine.values[expect]).to.eql value engine.id('box1').click() engine.then (solution) -> expect(solution['$box1"zone"[height]']).to.eql null expect(solution['$box1"zone"[width]']).to.eql null expect(solution['$box1"zone"[x]']).to.eql null expect(solution['$box1"zone"[y]']).to.eql null engine.id('box1').click() engine.then (solution) -> expect(solution['$box1"zone"[height]']).to.eql 260 expect(solution['$box1"zone"[width]']).to.eql 760 expect(solution['$box1"zone"[x]']).to.eql 120 expect(solution['$box1"zone"[y]']).to.eql 30 engine.id('box2').click() engine.then (solution) -> expect(solution['$box2"zone"[height]']).to.eql 260 expect(solution['$box2"zone"[width]']).to.eql 720 expect(solution['$box2"zone"[x]']).to.eql 140 expect(solution['$box2"zone"[y]']).to.eql 350 engine.id('box2').click() engine.then (solution) -> expect(solution['$box2"zone"[height]']).to.eql null expect(solution['$box2"zone"[width]']).to.eql null expect(solution['$box2"zone"[x]']).to.eql null expect(solution['$box2"zone"[y]']).to.eql null engine.id('box3').click() engine.then (solution) -> expect(solution['$box3"zone"[height]']).to.eql null expect(solution['$box3"zone"[width]']).to.eql null expect(solution['$box3"zone"[x]']).to.eql null expect(solution['$box3"zone"[y]']).to.eql null engine.id('box3').click() engine.then (solution) -> expect(solution['$box3"zone"[height]']).to.eql 260 expect(solution['$box3"zone"[width]']).to.eql 680 expect(solution['$box3"zone"[x]']).to.eql 160 expect(solution['$box3"zone"[y]']).to.eql 670 engine.scope.innerHTML = "" engine.then (solution) -> expect(engine.values).to.eql {} done() @timeout 100000 it 'gss1 demo', (done) -> container = document.createElement('div') container.style.height = '640px' container.style.width = '640px' container.style.position = 'absolute' container.style.overflow = 'auto' container.style.left = 0 container.style.top = 0 window.$engine = engine = new GSS(container, index == 0) document.getElementById('fixtures').appendChild container container.innerHTML = DEMOS.GSS1 engine.then (solution) -> expect(solution['li-width']).to.eql((640 - 16) / 3) expect(solution['$aside[x]']).to.eql(640 / 2 + 100) expect(solution['$header[width]']).to.eql(Math.round(640 / 2)) li = engine.scope.querySelector('ul li:last-child') clone = li.cloneNode() clone.id = 'li4' clone.innerHTML = '4' li.parentNode.appendChild(clone) engine.then (solution) -> expect(Math.round(solution['li-width'])).to.eql((640 - 16) / 4) li = engine.scope.querySelector('ul li:first-child') li.parentNode.removeChild(li) engine.then (solution) -> expect(Math.round solution['li-width']).to.eql((640 - 16) / 3) expect(solution['$li2[x]']).to.eql(0) expect(solution['$li1[x]']).to.eql(null) engine.scope.setAttribute('style', 'width: 1024px; height: 640px') engine.then (solution) -> expect(Math.round solution['li-width']).to.eql(Math.round((1024 - 16) / 3)) expect(solution['$header[width]']).to.eql(1024 / 4) container.innerHTML = "" engine.then (solution) -> done() for type, j in ['with intrinsic condition', 'with linear condition'] do (type, j) -> describe type, (done) -> it 'should handle face detection section', (done) -> container = document.createElement('div') container.id = 'face-demo' window.$engine = engine = new GSS(container, index == 0) document.getElementById('fixtures').appendChild container html = DEMOS.FACE_DETECTION_SECTION if j == 0 html = html.replace('$[width] < 500', '$[intrinsic-width] < 500') container.innerHTML = html container.setAttribute('style', 'height: 640px; width: 640px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> expect(solution).to.eql '$title[margin-top]': 72 '$title[padding-top]': 40 '$face-demo[intrinsic-width]': 640 '$face-demo[width]': 640 'md': 72 'md-sub': 8 container.setAttribute('style', 'height: 640px; width: 400px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> expect(solution['$title[margin-top]']).to.eql 8 expect(solution['$title[padding-top]']).to.eql null expect(solution['$face-demo[intrinsic-width]']).to.eql 400 expect(solution['$face-demo[width]']).to.eql 400 container.innerHTML = "" engine.then (solution) -> expect(solution).to.eql '$title[margin-top]': null '$face-demo[intrinsic-width]': null '$face-demo[width]': null 'md': null 'md-sub': null done() it 'profile card', (done) -> container = document.createElement('div') container.id = 'profile-card-demo' window.$engine = engine = new GSS(container, index == 0) document.getElementById('fixtures').appendChild container container.innerHTML = DEMOS.PROFILE_CARD container.setAttribute('style', 'height: 1024px; width: 768px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> # phantom gives slightly different measurements roughAssert(solution['$follow[y]'], 540) roughAssert(solution['$follow[x]'], 329.5) roughAssert(solution['flex-gap'], 40) container.setAttribute('style', 'height: 768px; width: 1124px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> roughAssert(solution['$follow[x]'], 435, 25) unless window.callPhantom roughAssert(solution['$follow[y]'], 537) container.setAttribute('style', 'height: 1024px; width: 768px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> roughAssert(solution['flex-gap'], 40) roughAssert(solution['$follow[y]'], 544) roughAssert(solution['$follow[x]'], 320) container.setAttribute('style', 'height: 1280px; width: 768px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> roughAssert(solution['$follow[y]'], 668) #roughAssert(solution['$follow[x]'], 329.5) roughAssert(solution['flex-gap'], 158) container.setAttribute('style', 'height: 1024px; width: 768px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> roughAssert(solution['$follow[y]'], 540) roughAssert(solution['flex-gap'], 40) container.innerHTML = "" engine.then (solution) -> expect(engine.values).to.eql {} done() for type, j in ['with intrinsic condition', 'with linear condition'] do (type, j) -> expectation = window.atob && document.body.style.msTouchAction? && 544 || 480 describe type, -> it 'Adaptive aspect', (done) -> container = document.createElement('div') container.style.height = '640px' container.style.width = '640px' container.style.position = 'absolute' overflow = window.atob && 'auto' || 'hidden' container.style.overflow = overflow container.style.left = 0 container.style.top = 0 window.$engine = engine = new GSS(container, index == 0) document.getElementById('fixtures').appendChild container if j == 0 container.innerHTML = DEMOS.ADAPTIVE_ASPECT else container.innerHTML = DEMOS.ADAPTIVE_ASPECT_LINEAR engine.then (solution) -> expect(solution['$article[height]']).to.eql 600 expect(solution['$article[width]']).to.eql expectation expect(solution['$footer[height]']).to.eql 600 expect(solution['$footer[width]']).to.eql 72 expect(solution['$header[height]']).to.eql 600 expect(solution['$header[width]']).to.eql 72 expect(solution['article-gap']).to.eql 20 container.setAttribute('style', "height: 800px; width: 640px; position: absolute; overflow: #{overflow}; left: 0; top: 0") engine.then (solution) -> expect(solution['$article[height]'] > 1400).to.eql true expect(solution['article-gap']).to.eql 16 expect(solution['$article[width]']).to.eql 608 expect(solution['$footer[height]']).to.eql 72 expect(solution['$footer[width]']).to.eql 608 expect(solution['$header[height]']).to.eql 72 expect(solution['$header[width]']).to.eql 608 container.setAttribute('style', "height: 640px; width: 640px; position: absolute; overflow: #{overflow}; left: 0; top: 0") engine.then (solution) -> expect(solution['article-gap']).to.eql 20 expect(solution['$article[height]']).to.eql 600 expect(solution['$article[width]']).to.eql expectation expect(solution['$footer[height]']).to.eql 600 expect(solution['$footer[width]']).to.eql 72 expect(solution['$header[height]']).to.eql 600 expect(solution['$header[width]']).to.eql 72 container.setAttribute('style', "height: 800px; width: 640px; position: absolute; overflow: #{overflow}; left: 0; top: 0") engine.then (solution) -> expect(solution['$article[height]'] > 1400).to.eql true expect(solution['$article[width]']).to.eql 608 expect(solution['$footer[height]']).to.eql 72 expect(solution['$footer[width]']).to.eql 608 expect(solution['$header[height]']).to.eql 72 expect(solution['$header[width]']).to.eql 608 expect(solution['article-gap']).to.eql 16 container.setAttribute('style', "height: 800px; width: 600px; position: absolute; overflow: #{overflow}; left: 0; top: 0") engine.then (solution) -> expect(solution['$article[height]'] > 1400).to.eql true expect(solution['$article[width]']).to.eql 568 expect(solution['$footer[width]']).to.eql 568 expect(solution['$header[width]']).to.eql 568 engine.scope.innerHTML = "" engine.then -> expect(engine.values).to.eql {} done()
true
DEMOS = FACE_DETECTION_SECTION: """ <section class="demo"> <h1 class="title" id="title">We've already broken ground on more than 30 layout filters.</h1> <h2 class="subtitle">Before we invest the hard work of making each bullet-proof, we need to know this is wanted & needed, become a founding member & help us help you!</h2> <img class="image" src="image.png"> </section> <style type="text/gss" scoped> [md] == 72 !require; [md-sub] == 8; $[width] == $[intrinsic-width]; .demo { @if $[width] < 500 { .title { &margin-top == [md-sub]; } } @else { .title { &margin-top == [md]; &padding-top == ([md-sub] * 6) - 8; } } } </style> """ SCOPING: """ <button id="box1" class="box w-virtual" onclick=" this.setAttribute('class', 'box ' + (this.className.indexOf('wo') > -1 ? 'w-virtual' : 'wo-virtual'))"> <div class="innie" id="innie1" ></div> </button> <button id="box2" class="box wo-virtual" onclick="this.setAttribute('class', 'box ' + (this.className.indexOf('wo') > -1 && 'w-virtual' || 'wo-virtual'))"> <div class="innie" id="innie2" ></div> </button> <button id="box3" class="box w-virtual" onclick="this.setAttribute('class', 'box ' + (this.className.indexOf('wo') > -1 && 'w-virtual' || 'wo-virtual'))"> <div class="innie" id="innie3" ></div> </button> <style> * { box-sizing: border-box; } .box { background-color: hsl(220,50%,50%); } .wo-virtual .innie { background-color: hsl(360,100%,50%); } .w-virtual .innie { background-color: hsl(180,100%,50%); } .w-virtual:after { content: 'W/ SCOPED VIRTUAL'; font-size: 40px; top: 32px; left: 32px; position:absolute; } .wo-virtual:after { content: 'W/O VIRTUAL'; font-size: 40px; top: 32px; left: 32px; position:absolute; } </style> <style type="text/gss"> $[left] == 0; $[top] == 0; $[height] == $[intrinsic-height]; $[width] == $[intrinsic-width]; .box { "zone" { @h |-(&)-| in(&.w-virtual) gap(20); @h |(&.w-virtual .innie)|; } } .box.w-virtual { @v |-(&"zone")-| in(&) gap(20); @v |(& .innie)| in(&"zone"); } .box.wo-virtual { @h |-(& .innie)-| in(&) gap(20); @v |-(& .innie)-| in(&) gap(20); } @v |-10-(.box)-20-... in($) { @h |~100~(&)~100~| in($); &[x] + 20 == &:next[x]; &[right] - 20 == &:next[right]; height: == 300; } </style> """, GSS1: """ <style scoped> header { background: orange; height: 50px; } main { background: yellow; height: 100px; z-index: 10; } footer { background: red; width: 10px; height: 20px; } aside { background: blue; width: 100px; } ul li { list-style: none; background: green; top: 5px; } </style> <style type="text/gss" scoped> // plural selectors can be used as singular, a la jQ [left-margin] == (main)[right]; // global condition with nested rules @if (main)[top] > 50 { main { background: blue; } } header { ::[left] == 0; // condition inside css rule @if ($[intrinsic-width] > $[intrinsic-height]) { ::[width] == $[intrinsic-width] / 4; opacity: 0.5; } @else { ::[width] == $[intrinsic-width] / 2; opacity: 0.75; } } footer { ::[top] == $(main)[height]; ::[height] == $[intrinsic-height] * 2; } aside { ::[left] == ($ main)[right]; ::[height] == 100; ::[top] == $(header)[intrinsic-height] + $(header)[intrinsic-y]; } main { // Bind things to scroll position ::[top] == $scroll-top;// + header[intrinsic-y]; ::[width] == $(aside)[intrinsic-width]; ::[left] == $(header)[right]; ::[height] == $[intrinsic-height] - $(header)[intrinsic-height]; } // Custom combinators ul li !~ li { ::[height] == 30; // FIXME: Regular css style is never removed (needs specificity sorting and groupping); background-color: yellowgreen; } // Chains ul li { // justify by using variable ::[width] == $[li-width]; :previous[right] == &[left]; :last[right] == $[intrinsic-width] - 16; :first[left] == 0; } </style> <header id="header"></header> <main id="main"> <ul> <li id="li1">1</li> <li id="li2">2</li> <li id="li3">3</li> </ul> </main> <aside id="aside"></aside> <footer id="footer"></footer> """ PROFILE_CARD: """ <style> #profile-card-demo * { box-sizing: border-box; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; } #profile-card-demo { background-color: hsl(3, 18%, 43%); } #profile-card-demo * { -webkit-backface-visibility: hidden; margin: 0px; padding: 0px; outline: none; } #background { background-color: hsl(3, 18%, 43%); position: absolute; top: 0px; bottom: 0px; right: 0px; left: 0px; z-index: -1; background-image: url('assets/cover.jpg'); background-size: cover; background-position: 50% 50%; opacity: .7; -webkit-filter: blur(5px) contrast(.7); } #cover { background-color: #ccc; background-image: url('assets/cover.jpg'); background-size: cover; background-position: 50% 50%; } #avatar { background-image: url('assets/avatar.jpg'); background-size: cover; background-position: 50% 50%; border: 10px solid hsl(39, 40%, 90%); box-shadow: 0 1px 1px hsla(0,0%,0%,.5); } #profile-card-demo h1 { color: white; text-shadow: 0 1px 1px hsla(0,0%,0%,.5); font-size: 40px; line-height: 1.5em; font-family: "adelle",georgia,serif; font-style: normal; font-weight: 400; } #profile-card-demo button { color: hsl(3, 18%, 43%); background-color: hsl(39, 40%, 90%); text-shadow: 0 1px hsla(3, 18%, 100%, .5); font-family: "proxima-nova-soft",sans-serif; font-style: normal; font-weight: 700; font-size: 14px; text-transform:uppercase; letter-spacing:.1em; border: none; } #profile-card-demo button.primary { background-color: #e38f71; color: white; text-shadow: 0 -1px hsla(3, 18%, 43%, .5); } #profile-card-demo #profile-card, .card { background-color: hsl(39, 40%, 90%); border: 1px solid hsla(0,0%,100%,.6); box-shadow: 0 5px 8px hsla(0,0%,0%,.3); } </style> <style type="text/gss" scoped> /* vars */ [gap] == 20 !required; [flex-gap] >= [gap] * 2 !required; [radius] == 10 !required; [outer-radius] == [radius] * 2 !required; /* scope-as-window for tests */ $[left] == 0; $[top] == 0; $[width] == $[intrinsic-width] !require; $[height] == $[intrinsic-height] !require; /* elements */ #profile-card { &width == $[width] - 480 !strong; &height == $[height] - 480; &[center-x] == $[center-x]; &[center-y] == $[center-y]; &border-radius == [outer-radius]; } #avatar { &height == 160 !required; &width == ::[height]; &border-radius == ::[height] / 2; } #name { &height == ::[intrinsic-height] !required; &width == ::[intrinsic-width] !required; } #cover { &border-radius == [radius]; } button { &width == ::[intrinsic-width] !required; &height == ::[intrinsic-height] !required; &padding == [gap]; &padding-top == [gap] / 2; &padding-bottom == [gap] / 2; &border-radius == [radius]; } @h |~-~(#name)~-~| in(#cover) gap([gap]*2) !strong; /* landscape profile-card */ @if #profile-card[width] >= #profile-card[height] { @v | - (#avatar) - (#name) - | in(#cover) gap([gap]) outer-gap([flex-gap]) { &[center-x] == ($ #cover)[center-x]; } @h |-10-(#cover)-10-| in(#profile-card); @v | -10- (#cover) - (#follow) - | in(#profile-card) gap([gap]) !strong; #follow[center-x] == #profile-card[center-x]; @h |-(#message)~-~(#follow)~-~(#following)-(#followers)-| in(#profile-card) gap([gap]) !strong { :next[top] == &top; } } /* portrait profile-card */ @else { @v | - (#avatar) - (#name) - (#follow) - (#message) - (#following) - (#followers) - | in(#cover) gap([gap]) outer-gap([flex-gap]) !strong { &[center-x] == ($ #profile-card)[center-x]; } @h |-10-(#cover)-10-| in(#profile-card) !strong; @v |-10-(#cover)-10-| in(#profile-card) !strong; } </style> <div id="background"></div> <div id="profile-card"></div> <div id="cover"></div> <div id="avatar"></div> <h1 id="name"><span>PI:NAME:<NAME>END_PI</span></h1> <button id="follow" class="primary">Follow</button> <button id="following">Following</button> <button id="followers">Followers</button> <button id="message">Message</button> """ ADAPTIVE_ASPECT: """ <header id="header">header</header> <article id="article"> <p>ISTANBUL — Forty-nine Turkish hostages who had been held for months in Iraq by Islamic State militants were returned to Turkey on Saturday after what Turkey said was a covert operation led by its intelligence agency.</p> <p>The hostages, including diplomats and their families, had been seized in June from the Turkish Consulate in Mosul, in northern Iraq.</p> <p>“The Turkish intelligence agency has followed the situation very sensitively and patiently since the beginning and, as a result, conducted a successful rescue operation,” President PI:NAME:<NAME>END_PI said in a statement Saturday.</p> <p>The details of the hostages’ release were unclear. The semiofficial Turkish news agency Anadolu reported that Turkey had not paid ransom or engaged in a military operation, but said it had used drones to track the hostages, who had been moved at least eight times during their 101 days in captivity.</p> <p>Times Topic: Islamic State in Iraq and Syria (ISIS) Back and Forth, Wearily, Across the ISIS BorderSEPT. 20, 2014 The agency said that Turkish intelligence teams had tried five times to rescue the hostages, but that each attempt had been thwarted by clashes in the area where they were being held.</p> <p>An employee of the Turkish Consulate in Mosul was greeted by family members. Credit Reuters One senior American official, who asked not to be named, said Saturday that Turkey had not notified the United States before securing the return of the hostages, or made a specific request for American military help in connection with their release.</p> <p>“I am sharing joyful news, which as a nation we have been waiting for,” Prime Minister PI:NAME:<NAME>END_PI said in Baku, Azerbaijan, where he was on an official visit.</p> <p>“After intense efforts that lasted days and weeks, in the early hours, our citizens were handed over to us and we brought them back to our country,” he said.</p> <p>The prime minister left Baku for the Turkish province of Urfa, where the freed hostages, who included Consul General OPI:NAME:<NAME>END_PI, other diplomats, children and consulate guards, had been brought from Raqqa, Syria, the de facto headquarters of the Islamic State militants.</p> </article> <footer id="footer">footer</footer> <style> * { box-sizing: border-box; margin: 0; } html { background-color: hsl(0,0%,95%); } article { background-color: hsl(0,0%,99%); padding: 72px; -webkit-column-width: 400px; column-width: 400px; overflow-x: #{window.atob && 'auto' || 'hidden'}; font-size: 20px; line-height: 30px; } header { background-color: hsl(0,0%,90%); padding: 16px; text-align: center; } footer { background-color: hsl(0,0%,85%); padding: 16px; text-align: center; } p { margin-bottom: 1em; } </style> <style type="text/gss"> // vertical article $[left] == 0; $[top] == 0; $[height] == $[intrinsic-height]; $[width] == $[intrinsic-width]; $[article-gap] >= 16; @if $[intrinsic-width] < $[intrinsic-height] { @h |-(article)-| gap($[article-gap]) in($) { height: == &[intrinsic-height]; width: <= 800; } @v | -72- (header) (article) (footer) in($); header, footer { height: == 72; @h |(&)| in($ article); } } // horizontal article @else { @v |-(article)-| gap($[article-gap]) in($) { width: == &[intrinsic-width]; height: <= 600; } @h | -16- (header) (footer) (article) in($); header, footer { width: == 72; @v |(&)| in($ article); } } </style> """ DEMOS.ADAPTIVE_ASPECT_LINEAR = DEMOS.ADAPTIVE_ASPECT. replace('$[intrinsic-width] < $[intrinsic-height]', '$[width] < $[height]') roughAssert = (a, b, threshold = 15) -> expect(Math.abs(a - b) < threshold).to.eql true assert = chai.assert expect = chai.expect remove = (el) -> el?.parentNode?.removeChild(el) describe 'Full page tests', -> engine = container = null afterEach -> remove(container) engine.destroy() @timeout 100000 for type, index in ['With worker', 'Without worker'] do (type, index) -> describe type, -> it 'scoping', (done) -> container = document.createElement('div') container.style.height = '1000px' container.style.width = '1000px' container.style.position = 'absolute' container.style.overflow = 'auto' container.style.left = 0 container.style.top = 0 window.$engine = engine = new GSS(container, index == 0) document.getElementById('fixtures').appendChild container container.innerHTML = DEMOS.SCOPING engine.then (solution) -> expectation = "$1[height]": 1000 "$1[intrinsic-height]": 1000 "$1[intrinsic-width]": 1000 "$1[width]": 1000 "$1[x]": 0 "$1[y]": 0 "$box1'zone'[height]": 260 "$box1'zone'[width]": 760 "$box1'zone'[x]": 120 "$box1'zone'[y]": 30 "$box1[height]": 300 "$box1[width]": 800 "$box1[x]": 100 "$box1[y]": 10 "$box2[height]": 300 "$box2[width]": 760 "$box2[x]": 120 "$box2[y]": 330 '$box3"zone"[height]': 260 '$box3"zone"[width]': 680 '$box3"zone"[x]': 160 '$box3"zone"[y]': 670 "$box3[height]": 300 "$box3[width]": 720 "$box3[x]": 140 "$box3[y]": 650 "$innie1[height]": 260 "$innie1[width]": 760 "$innie1[x]": 120 "$innie1[y]": 30 "$innie2[height]": 260 "$innie2[width]": 720 "$innie2[x]": 140 "$innie2[y]": 350 "$innie3[height]": 260 "$innie3[width]": 680 "$innie3[x]": 160 "$innie3[y]": 670 for expect, value in expectation assert(engine.values[expect]).to.eql value engine.id('box1').click() engine.then (solution) -> expect(solution['$box1"zone"[height]']).to.eql null expect(solution['$box1"zone"[width]']).to.eql null expect(solution['$box1"zone"[x]']).to.eql null expect(solution['$box1"zone"[y]']).to.eql null engine.id('box1').click() engine.then (solution) -> expect(solution['$box1"zone"[height]']).to.eql 260 expect(solution['$box1"zone"[width]']).to.eql 760 expect(solution['$box1"zone"[x]']).to.eql 120 expect(solution['$box1"zone"[y]']).to.eql 30 engine.id('box2').click() engine.then (solution) -> expect(solution['$box2"zone"[height]']).to.eql 260 expect(solution['$box2"zone"[width]']).to.eql 720 expect(solution['$box2"zone"[x]']).to.eql 140 expect(solution['$box2"zone"[y]']).to.eql 350 engine.id('box2').click() engine.then (solution) -> expect(solution['$box2"zone"[height]']).to.eql null expect(solution['$box2"zone"[width]']).to.eql null expect(solution['$box2"zone"[x]']).to.eql null expect(solution['$box2"zone"[y]']).to.eql null engine.id('box3').click() engine.then (solution) -> expect(solution['$box3"zone"[height]']).to.eql null expect(solution['$box3"zone"[width]']).to.eql null expect(solution['$box3"zone"[x]']).to.eql null expect(solution['$box3"zone"[y]']).to.eql null engine.id('box3').click() engine.then (solution) -> expect(solution['$box3"zone"[height]']).to.eql 260 expect(solution['$box3"zone"[width]']).to.eql 680 expect(solution['$box3"zone"[x]']).to.eql 160 expect(solution['$box3"zone"[y]']).to.eql 670 engine.scope.innerHTML = "" engine.then (solution) -> expect(engine.values).to.eql {} done() @timeout 100000 it 'gss1 demo', (done) -> container = document.createElement('div') container.style.height = '640px' container.style.width = '640px' container.style.position = 'absolute' container.style.overflow = 'auto' container.style.left = 0 container.style.top = 0 window.$engine = engine = new GSS(container, index == 0) document.getElementById('fixtures').appendChild container container.innerHTML = DEMOS.GSS1 engine.then (solution) -> expect(solution['li-width']).to.eql((640 - 16) / 3) expect(solution['$aside[x]']).to.eql(640 / 2 + 100) expect(solution['$header[width]']).to.eql(Math.round(640 / 2)) li = engine.scope.querySelector('ul li:last-child') clone = li.cloneNode() clone.id = 'li4' clone.innerHTML = '4' li.parentNode.appendChild(clone) engine.then (solution) -> expect(Math.round(solution['li-width'])).to.eql((640 - 16) / 4) li = engine.scope.querySelector('ul li:first-child') li.parentNode.removeChild(li) engine.then (solution) -> expect(Math.round solution['li-width']).to.eql((640 - 16) / 3) expect(solution['$li2[x]']).to.eql(0) expect(solution['$li1[x]']).to.eql(null) engine.scope.setAttribute('style', 'width: 1024px; height: 640px') engine.then (solution) -> expect(Math.round solution['li-width']).to.eql(Math.round((1024 - 16) / 3)) expect(solution['$header[width]']).to.eql(1024 / 4) container.innerHTML = "" engine.then (solution) -> done() for type, j in ['with intrinsic condition', 'with linear condition'] do (type, j) -> describe type, (done) -> it 'should handle face detection section', (done) -> container = document.createElement('div') container.id = 'face-demo' window.$engine = engine = new GSS(container, index == 0) document.getElementById('fixtures').appendChild container html = DEMOS.FACE_DETECTION_SECTION if j == 0 html = html.replace('$[width] < 500', '$[intrinsic-width] < 500') container.innerHTML = html container.setAttribute('style', 'height: 640px; width: 640px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> expect(solution).to.eql '$title[margin-top]': 72 '$title[padding-top]': 40 '$face-demo[intrinsic-width]': 640 '$face-demo[width]': 640 'md': 72 'md-sub': 8 container.setAttribute('style', 'height: 640px; width: 400px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> expect(solution['$title[margin-top]']).to.eql 8 expect(solution['$title[padding-top]']).to.eql null expect(solution['$face-demo[intrinsic-width]']).to.eql 400 expect(solution['$face-demo[width]']).to.eql 400 container.innerHTML = "" engine.then (solution) -> expect(solution).to.eql '$title[margin-top]': null '$face-demo[intrinsic-width]': null '$face-demo[width]': null 'md': null 'md-sub': null done() it 'profile card', (done) -> container = document.createElement('div') container.id = 'profile-card-demo' window.$engine = engine = new GSS(container, index == 0) document.getElementById('fixtures').appendChild container container.innerHTML = DEMOS.PROFILE_CARD container.setAttribute('style', 'height: 1024px; width: 768px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> # phantom gives slightly different measurements roughAssert(solution['$follow[y]'], 540) roughAssert(solution['$follow[x]'], 329.5) roughAssert(solution['flex-gap'], 40) container.setAttribute('style', 'height: 768px; width: 1124px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> roughAssert(solution['$follow[x]'], 435, 25) unless window.callPhantom roughAssert(solution['$follow[y]'], 537) container.setAttribute('style', 'height: 1024px; width: 768px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> roughAssert(solution['flex-gap'], 40) roughAssert(solution['$follow[y]'], 544) roughAssert(solution['$follow[x]'], 320) container.setAttribute('style', 'height: 1280px; width: 768px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> roughAssert(solution['$follow[y]'], 668) #roughAssert(solution['$follow[x]'], 329.5) roughAssert(solution['flex-gap'], 158) container.setAttribute('style', 'height: 1024px; width: 768px; position: absolute; overflow: auto; left: 0; top: 0') engine.then (solution) -> roughAssert(solution['$follow[y]'], 540) roughAssert(solution['flex-gap'], 40) container.innerHTML = "" engine.then (solution) -> expect(engine.values).to.eql {} done() for type, j in ['with intrinsic condition', 'with linear condition'] do (type, j) -> expectation = window.atob && document.body.style.msTouchAction? && 544 || 480 describe type, -> it 'Adaptive aspect', (done) -> container = document.createElement('div') container.style.height = '640px' container.style.width = '640px' container.style.position = 'absolute' overflow = window.atob && 'auto' || 'hidden' container.style.overflow = overflow container.style.left = 0 container.style.top = 0 window.$engine = engine = new GSS(container, index == 0) document.getElementById('fixtures').appendChild container if j == 0 container.innerHTML = DEMOS.ADAPTIVE_ASPECT else container.innerHTML = DEMOS.ADAPTIVE_ASPECT_LINEAR engine.then (solution) -> expect(solution['$article[height]']).to.eql 600 expect(solution['$article[width]']).to.eql expectation expect(solution['$footer[height]']).to.eql 600 expect(solution['$footer[width]']).to.eql 72 expect(solution['$header[height]']).to.eql 600 expect(solution['$header[width]']).to.eql 72 expect(solution['article-gap']).to.eql 20 container.setAttribute('style', "height: 800px; width: 640px; position: absolute; overflow: #{overflow}; left: 0; top: 0") engine.then (solution) -> expect(solution['$article[height]'] > 1400).to.eql true expect(solution['article-gap']).to.eql 16 expect(solution['$article[width]']).to.eql 608 expect(solution['$footer[height]']).to.eql 72 expect(solution['$footer[width]']).to.eql 608 expect(solution['$header[height]']).to.eql 72 expect(solution['$header[width]']).to.eql 608 container.setAttribute('style', "height: 640px; width: 640px; position: absolute; overflow: #{overflow}; left: 0; top: 0") engine.then (solution) -> expect(solution['article-gap']).to.eql 20 expect(solution['$article[height]']).to.eql 600 expect(solution['$article[width]']).to.eql expectation expect(solution['$footer[height]']).to.eql 600 expect(solution['$footer[width]']).to.eql 72 expect(solution['$header[height]']).to.eql 600 expect(solution['$header[width]']).to.eql 72 container.setAttribute('style', "height: 800px; width: 640px; position: absolute; overflow: #{overflow}; left: 0; top: 0") engine.then (solution) -> expect(solution['$article[height]'] > 1400).to.eql true expect(solution['$article[width]']).to.eql 608 expect(solution['$footer[height]']).to.eql 72 expect(solution['$footer[width]']).to.eql 608 expect(solution['$header[height]']).to.eql 72 expect(solution['$header[width]']).to.eql 608 expect(solution['article-gap']).to.eql 16 container.setAttribute('style', "height: 800px; width: 600px; position: absolute; overflow: #{overflow}; left: 0; top: 0") engine.then (solution) -> expect(solution['$article[height]'] > 1400).to.eql true expect(solution['$article[width]']).to.eql 568 expect(solution['$footer[width]']).to.eql 568 expect(solution['$header[width]']).to.eql 568 engine.scope.innerHTML = "" engine.then -> expect(engine.values).to.eql {} done()
[ { "context": "tes\n\n ###\n Showup.js \n http://github.com/jonschlinkert/showup\n Jon Schlinkert\n ###\n showUp: (el", "end": 764, "score": 0.9883405566215515, "start": 751, "tag": "USERNAME", "value": "jonschlinkert" }, { "context": "js \n http://github.com/jons...
views/coffee/app/lib.coffee
cncolder/vcvs
0
_ = require 'underscore' # jQuery extend $?.fn.extend # CSS visibility helper. Just like .show() and .hide() but hold element position and function. visible: -> @css 'visibility', '' hidden: -> @css 'visibility', 'hidden' # Change bootstrap state state: (state) -> states = 'warning error success'.split /\s+/ @each -> el = $ @ if el.is 'input' prefix = 'has-' formStates = states.map (state) -> "#{prefix}#{state}" target = el.parents '.row' target.removeClass formStates.join ' ' target.addClass "#{prefix}#{state}" if state in states ### Showup.js http://github.com/jonschlinkert/showup Jon Schlinkert ### showUp: (el) -> target = $ @ previous = 0 calculateLayout = (e) -> current = $(e.target).scrollTop() if current < Math.max 30, previous # Use css3 transition is fast than jQuery animation. target.removeClass 'hide' else target.addClass 'hide' previous = current $(window).scroll _.debounce calculateLayout, 30 exports.TRANSITION_END = do -> browserEventName = webkit: 'webkitTransitionEnd' # Moz: 'transitionend' O: 'oTransitionEnd' ms: 'MSTransitionEnd' for prefix, eventName of browserEventName when document.body.style["#{prefix}Transition"]? return eventName 'transitionend' exports.ANIMATION_END = do -> browserEventName = webkit: 'webkitAnimationEnd' # Moz: 'animationend' O: 'oAnimationEnd' ms: 'MSAnimationEnd' for prefix, eventName of browserEventName when document.body.style["#{prefix}Animation"]? return eventName 'animationend' exports.FULLSCREEN = do -> for method in [ 'webkitIsFullScreen', 'mozFullScreen' ] when document[method]? return method 'fullscreen' exports.REQUEST_FULLSCREEN = do -> for method in [ 'webkitRequestFullscreen', 'mozRequestFullScreen' ] when document.body[method]? return method 'requestFullscreen' exports.FULLSCREEN_CHANGE = do -> for prefix in [ 'webkit', 'moz' ] when document["on#{prefix}fullscreenchange"] isnt undefined return "#{prefix}fullscreenchange" 'fullscreenchange' exports.EXIT_FULLSCREEN = do -> for method in [ 'webkitExitFullscreen', 'mozCancelFullScreen' ] when document[method]? return method 'exitFullscreen'
130579
_ = require 'underscore' # jQuery extend $?.fn.extend # CSS visibility helper. Just like .show() and .hide() but hold element position and function. visible: -> @css 'visibility', '' hidden: -> @css 'visibility', 'hidden' # Change bootstrap state state: (state) -> states = 'warning error success'.split /\s+/ @each -> el = $ @ if el.is 'input' prefix = 'has-' formStates = states.map (state) -> "#{prefix}#{state}" target = el.parents '.row' target.removeClass formStates.join ' ' target.addClass "#{prefix}#{state}" if state in states ### Showup.js http://github.com/jonschlinkert/showup <NAME> ### showUp: (el) -> target = $ @ previous = 0 calculateLayout = (e) -> current = $(e.target).scrollTop() if current < Math.max 30, previous # Use css3 transition is fast than jQuery animation. target.removeClass 'hide' else target.addClass 'hide' previous = current $(window).scroll _.debounce calculateLayout, 30 exports.TRANSITION_END = do -> browserEventName = webkit: 'webkitTransitionEnd' # Moz: 'transitionend' O: 'oTransitionEnd' ms: 'MSTransitionEnd' for prefix, eventName of browserEventName when document.body.style["#{prefix}Transition"]? return eventName 'transitionend' exports.ANIMATION_END = do -> browserEventName = webkit: 'webkitAnimationEnd' # Moz: 'animationend' O: 'oAnimationEnd' ms: 'MSAnimationEnd' for prefix, eventName of browserEventName when document.body.style["#{prefix}Animation"]? return eventName 'animationend' exports.FULLSCREEN = do -> for method in [ 'webkitIsFullScreen', 'mozFullScreen' ] when document[method]? return method 'fullscreen' exports.REQUEST_FULLSCREEN = do -> for method in [ 'webkitRequestFullscreen', 'mozRequestFullScreen' ] when document.body[method]? return method 'requestFullscreen' exports.FULLSCREEN_CHANGE = do -> for prefix in [ 'webkit', 'moz' ] when document["on#{prefix}fullscreenchange"] isnt undefined return "#{prefix}fullscreenchange" 'fullscreenchange' exports.EXIT_FULLSCREEN = do -> for method in [ 'webkitExitFullscreen', 'mozCancelFullScreen' ] when document[method]? return method 'exitFullscreen'
true
_ = require 'underscore' # jQuery extend $?.fn.extend # CSS visibility helper. Just like .show() and .hide() but hold element position and function. visible: -> @css 'visibility', '' hidden: -> @css 'visibility', 'hidden' # Change bootstrap state state: (state) -> states = 'warning error success'.split /\s+/ @each -> el = $ @ if el.is 'input' prefix = 'has-' formStates = states.map (state) -> "#{prefix}#{state}" target = el.parents '.row' target.removeClass formStates.join ' ' target.addClass "#{prefix}#{state}" if state in states ### Showup.js http://github.com/jonschlinkert/showup PI:NAME:<NAME>END_PI ### showUp: (el) -> target = $ @ previous = 0 calculateLayout = (e) -> current = $(e.target).scrollTop() if current < Math.max 30, previous # Use css3 transition is fast than jQuery animation. target.removeClass 'hide' else target.addClass 'hide' previous = current $(window).scroll _.debounce calculateLayout, 30 exports.TRANSITION_END = do -> browserEventName = webkit: 'webkitTransitionEnd' # Moz: 'transitionend' O: 'oTransitionEnd' ms: 'MSTransitionEnd' for prefix, eventName of browserEventName when document.body.style["#{prefix}Transition"]? return eventName 'transitionend' exports.ANIMATION_END = do -> browserEventName = webkit: 'webkitAnimationEnd' # Moz: 'animationend' O: 'oAnimationEnd' ms: 'MSAnimationEnd' for prefix, eventName of browserEventName when document.body.style["#{prefix}Animation"]? return eventName 'animationend' exports.FULLSCREEN = do -> for method in [ 'webkitIsFullScreen', 'mozFullScreen' ] when document[method]? return method 'fullscreen' exports.REQUEST_FULLSCREEN = do -> for method in [ 'webkitRequestFullscreen', 'mozRequestFullScreen' ] when document.body[method]? return method 'requestFullscreen' exports.FULLSCREEN_CHANGE = do -> for prefix in [ 'webkit', 'moz' ] when document["on#{prefix}fullscreenchange"] isnt undefined return "#{prefix}fullscreenchange" 'fullscreenchange' exports.EXIT_FULLSCREEN = do -> for method in [ 'webkitExitFullscreen', 'mozCancelFullScreen' ] when document[method]? return method 'exitFullscreen'
[ { "context": "# @author Liam Symonds\n# @version 1.0.0\n#\n# Handles the navigation of th", "end": 22, "score": 0.9998520016670227, "start": 10, "tag": "NAME", "value": "Liam Symonds" } ]
broadcastPanel/packages/core/assets/coffee/core-core.coffee
broadcastPanel/broadcastpanel
0
# @author Liam Symonds # @version 1.0.0 # # Handles the navigation of the application. $('.navigation > .header').on 'click', -> next = $(this).next() header = $(this) if ! next.is(':visible') $('.box').not(next).slideUp() next.hide().slideDown() else next.slideUp()
119394
# @author <NAME> # @version 1.0.0 # # Handles the navigation of the application. $('.navigation > .header').on 'click', -> next = $(this).next() header = $(this) if ! next.is(':visible') $('.box').not(next).slideUp() next.hide().slideDown() else next.slideUp()
true
# @author PI:NAME:<NAME>END_PI # @version 1.0.0 # # Handles the navigation of the application. $('.navigation > .header').on 'click', -> next = $(this).next() header = $(this) if ! next.is(':visible') $('.box').not(next).slideUp() next.hide().slideDown() else next.slideUp()
[ { "context": "@app.controller 'RegistrationController', [ '$scope', ", "end": 4, "score": 0.581998884677887, "start": 0, "tag": "EMAIL", "value": "@app" }, { "context": " $scope.email = user.email\n $scope.password = user.password\n $scope.password_confirm = user.password\n ...
app/assets/javascripts/angularjs/registration.js.coffee
kasuya89/newapp
0
@app.controller 'RegistrationController', [ '$scope', '$http', '$window', 'ipCookie', ($scope, $http, $window, ipCookie)-> $scope.errors = ipCookie('registerErrors') || {} ipCookie.remove('registerErrors', { path: '/' }) if user = ipCookie('register_users') $scope.name = user.name $scope.email = user.email $scope.password = user.password $scope.password_confirm = user.password $scope.code = user.code ipCookie.remove('register_users', {path: '/'}) $scope.submit = ()-> $http url: '/users' method: 'POST' params: 'user[name]': $scope.name 'user[email]': $scope.email 'user[password]': $scope.password 'code': $scope.code .success (res)-> if res.success $window.location.href = '/' else $scope.errors = res.errors .error (res, status)-> $scope.error_message = '网络错误, 请重试, 错误码为: ' + status $scope.email_validate = ()-> $http url: '/users/email_validate' method: 'POST' data: email: $scope.email .success (res)-> if ! res.success $scope.errors.email = res.message else delete $scope.errors.email $scope.password_confirm_validate = ()-> if $scope.password_confirm != $scope.password $scope.errors.password_confirm = '确认密码与原密码不一致' else delete $scope.errors.password_confirm $scope.submit_validate = ()-> Utils.is_empty($scope.errors) $scope.delete_error_on = (column)-> delete $scope.errors[column] ]
160553
<EMAIL>.controller 'RegistrationController', [ '$scope', '$http', '$window', 'ipCookie', ($scope, $http, $window, ipCookie)-> $scope.errors = ipCookie('registerErrors') || {} ipCookie.remove('registerErrors', { path: '/' }) if user = ipCookie('register_users') $scope.name = user.name $scope.email = user.email $scope.password = <PASSWORD> $scope.password_confirm = <PASSWORD> $scope.code = user.code ipCookie.remove('register_users', {path: '/'}) $scope.submit = ()-> $http url: '/users' method: 'POST' params: 'user[name]': $scope.name 'user[email]': $scope.email 'user[password]': <PASSWORD> 'code': $scope.code .success (res)-> if res.success $window.location.href = '/' else $scope.errors = res.errors .error (res, status)-> $scope.error_message = '网络错误, 请重试, 错误码为: ' + status $scope.email_validate = ()-> $http url: '/users/email_validate' method: 'POST' data: email: $scope.email .success (res)-> if ! res.success $scope.errors.email = res.message else delete $scope.errors.email $scope.password_confirm_validate = ()-> if $scope.password_confirm != $scope.password $scope.errors.password_confirm = '确认密码与原密码不一致' else delete $scope.errors.password_confirm $scope.submit_validate = ()-> Utils.is_empty($scope.errors) $scope.delete_error_on = (column)-> delete $scope.errors[column] ]
true
PI:EMAIL:<EMAIL>END_PI.controller 'RegistrationController', [ '$scope', '$http', '$window', 'ipCookie', ($scope, $http, $window, ipCookie)-> $scope.errors = ipCookie('registerErrors') || {} ipCookie.remove('registerErrors', { path: '/' }) if user = ipCookie('register_users') $scope.name = user.name $scope.email = user.email $scope.password = PI:PASSWORD:<PASSWORD>END_PI $scope.password_confirm = PI:PASSWORD:<PASSWORD>END_PI $scope.code = user.code ipCookie.remove('register_users', {path: '/'}) $scope.submit = ()-> $http url: '/users' method: 'POST' params: 'user[name]': $scope.name 'user[email]': $scope.email 'user[password]': PI:PASSWORD:<PASSWORD>END_PI 'code': $scope.code .success (res)-> if res.success $window.location.href = '/' else $scope.errors = res.errors .error (res, status)-> $scope.error_message = '网络错误, 请重试, 错误码为: ' + status $scope.email_validate = ()-> $http url: '/users/email_validate' method: 'POST' data: email: $scope.email .success (res)-> if ! res.success $scope.errors.email = res.message else delete $scope.errors.email $scope.password_confirm_validate = ()-> if $scope.password_confirm != $scope.password $scope.errors.password_confirm = '确认密码与原密码不一致' else delete $scope.errors.password_confirm $scope.submit_validate = ()-> Utils.is_empty($scope.errors) $scope.delete_error_on = (column)-> delete $scope.errors[column] ]
[ { "context": "ookup then @dns = require 'dns'\n @socketIdKey = \"$_id#{Math.round Math.random() * 10000}\"\n\n # Attach eve", "end": 571, "score": 0.9367189407348633, "start": 564, "tag": "KEY", "value": "\"$_id#{" }, { "context": "e 'dns'\n @socketIdKey = \"$_id#{Math.round M...
logger/base.coffee
knalli/honeypot-for-tcp-32764
15
util = require 'util' class BaseLogger lookup: false # Implement this methods doConnectLog: (socket) -> doTimeoutLog: (socket) -> doHostnameLog: (socket, domains) -> doEndLog: (socket) -> doErrorLog: (socket, error) -> doLog: (socket, message) -> # @param lookup - Do DNS lookups for every connect # @param redisPrefix - Use prefix for Redis DB Keys # @param redisSettings... - Settings for Redis constructor constructor: (options) -> @lookup = options?.lookup isnt false if @lookup then @dns = require 'dns' @socketIdKey = "$_id#{Math.round Math.random() * 10000}" # Attach event listeners to the serves' events. # @param server - Server Object created by net.createServer() bindServer: (server) -> util.log "Logger '#{@name}' binds to server..." server.on 'connection', (socket) => @connectLog(socket) socket.on 'end', @endLog.bind this, socket socket.on 'error', @errorLog.bind this, socket socket.on 'timeout', @timeoutLog.bind this, socket # Internal. Log start of a connection, store on socket object. connectLog: (socket) -> socket.timeStart = new Date() @doConnectLog(socket) @hostnameLog(socket) if @lookup # Internal. Log timeouts to the socket and calculate duration. timeoutLog: (socket) -> socket.duration = ((new Date()) - socket.timeStart) @doTimeoutLog(socket) @db.set "#{socket.dbKey}.duration", socket.duration @db.append "#{socket.dbKey}.lastlog", "\nSOCKET-TIMEOUT after #{socket.duration}ms." # Internal. If LogRedis was initializes with DNS lookup = yes, then do a DNS reverse # lookup and log it, asynchronously. hostnameLog: (socket) -> @dns.reverse socket.remoteAddress, (err, domains) => if err then return @log(socket, "Could not resolve #{socket.remoteAddress} to hostname.") @doHostnameLog(socket, domains) # Internal. Finish up logging this connection. Calculate duration. endLog: (socket) -> socket.duration = ((new Date()) - socket.timeStart) @doEndLog(socket) # Internal. Log errors on the socket. errorLog: (socket, error) -> @doErrorLog(socket, error) # Log messages for this socket. It has to be initialized by LogRedis which is usually done after # calling LogRedis.attachToServer(server). log: (socket, message) -> @doLog(socket, message) module.exports = BaseLogger
57429
util = require 'util' class BaseLogger lookup: false # Implement this methods doConnectLog: (socket) -> doTimeoutLog: (socket) -> doHostnameLog: (socket, domains) -> doEndLog: (socket) -> doErrorLog: (socket, error) -> doLog: (socket, message) -> # @param lookup - Do DNS lookups for every connect # @param redisPrefix - Use prefix for Redis DB Keys # @param redisSettings... - Settings for Redis constructor constructor: (options) -> @lookup = options?.lookup isnt false if @lookup then @dns = require 'dns' @socketIdKey = <KEY>Math.round Math.<KEY>() <KEY> <KEY> # Attach event listeners to the serves' events. # @param server - Server Object created by net.createServer() bindServer: (server) -> util.log "Logger '#{@name}' binds to server..." server.on 'connection', (socket) => @connectLog(socket) socket.on 'end', @endLog.bind this, socket socket.on 'error', @errorLog.bind this, socket socket.on 'timeout', @timeoutLog.bind this, socket # Internal. Log start of a connection, store on socket object. connectLog: (socket) -> socket.timeStart = new Date() @doConnectLog(socket) @hostnameLog(socket) if @lookup # Internal. Log timeouts to the socket and calculate duration. timeoutLog: (socket) -> socket.duration = ((new Date()) - socket.timeStart) @doTimeoutLog(socket) @db.set "#{socket.dbKey}.duration", socket.duration @db.append "#{socket.dbKey}.lastlog", "\nSOCKET-TIMEOUT after #{socket.duration}ms." # Internal. If LogRedis was initializes with DNS lookup = yes, then do a DNS reverse # lookup and log it, asynchronously. hostnameLog: (socket) -> @dns.reverse socket.remoteAddress, (err, domains) => if err then return @log(socket, "Could not resolve #{socket.remoteAddress} to hostname.") @doHostnameLog(socket, domains) # Internal. Finish up logging this connection. Calculate duration. endLog: (socket) -> socket.duration = ((new Date()) - socket.timeStart) @doEndLog(socket) # Internal. Log errors on the socket. errorLog: (socket, error) -> @doErrorLog(socket, error) # Log messages for this socket. It has to be initialized by LogRedis which is usually done after # calling LogRedis.attachToServer(server). log: (socket, message) -> @doLog(socket, message) module.exports = BaseLogger
true
util = require 'util' class BaseLogger lookup: false # Implement this methods doConnectLog: (socket) -> doTimeoutLog: (socket) -> doHostnameLog: (socket, domains) -> doEndLog: (socket) -> doErrorLog: (socket, error) -> doLog: (socket, message) -> # @param lookup - Do DNS lookups for every connect # @param redisPrefix - Use prefix for Redis DB Keys # @param redisSettings... - Settings for Redis constructor constructor: (options) -> @lookup = options?.lookup isnt false if @lookup then @dns = require 'dns' @socketIdKey = PI:KEY:<KEY>END_PIMath.round Math.PI:KEY:<KEY>END_PI() PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI # Attach event listeners to the serves' events. # @param server - Server Object created by net.createServer() bindServer: (server) -> util.log "Logger '#{@name}' binds to server..." server.on 'connection', (socket) => @connectLog(socket) socket.on 'end', @endLog.bind this, socket socket.on 'error', @errorLog.bind this, socket socket.on 'timeout', @timeoutLog.bind this, socket # Internal. Log start of a connection, store on socket object. connectLog: (socket) -> socket.timeStart = new Date() @doConnectLog(socket) @hostnameLog(socket) if @lookup # Internal. Log timeouts to the socket and calculate duration. timeoutLog: (socket) -> socket.duration = ((new Date()) - socket.timeStart) @doTimeoutLog(socket) @db.set "#{socket.dbKey}.duration", socket.duration @db.append "#{socket.dbKey}.lastlog", "\nSOCKET-TIMEOUT after #{socket.duration}ms." # Internal. If LogRedis was initializes with DNS lookup = yes, then do a DNS reverse # lookup and log it, asynchronously. hostnameLog: (socket) -> @dns.reverse socket.remoteAddress, (err, domains) => if err then return @log(socket, "Could not resolve #{socket.remoteAddress} to hostname.") @doHostnameLog(socket, domains) # Internal. Finish up logging this connection. Calculate duration. endLog: (socket) -> socket.duration = ((new Date()) - socket.timeStart) @doEndLog(socket) # Internal. Log errors on the socket. errorLog: (socket, error) -> @doErrorLog(socket, error) # Log messages for this socket. It has to be initialized by LogRedis which is usually done after # calling LogRedis.attachToServer(server). log: (socket, message) -> @doLog(socket, message) module.exports = BaseLogger
[ { "context": "ctors = [{\n rfc : 6070,\n case : 1, \n \tP : \"password\",\n \tS : \"salt\",\n \tc : 1,\n \tdkLen : 20,\n \tDK :", "end": 1007, "score": 0.9970797896385193, "start": 999, "tag": "PASSWORD", "value": "password" }, { "context": ": 6070,\n case : 1, \n \tP ...
test/pbkdf2-reference.iced
maxtaco/oneshallpass
120
#!/usr/bin/env node fs = require 'fs' {CryptoJS} = require 'cryptojs-1sp' derive = require '../src/lib/derive' check_vector = (CryptoJS, v, cb) -> opts = { keySize : v.dkLen / 4, iterations: v.c }; # Get the raw word array. raw_cjs = CryptoJS.PBKDF2(v.P, v.S, opts) v2o = new derive.V3 { get : () -> 0 }, CryptoJS.algo.SHA1 await v2o.test CryptoJS, v.P, v.S, v.c, defer raw_us # Convert to string, and also truncate after the first dkLen # bytes. Note it takes 2 hex-encoding character to encode a byte, # so double it up... [res_cjs, res_us] = (r.toString()[0...v.dkLen*2] for r in [ raw_cjs, raw_us]) res = true if res_cjs isnt v.DK console.log "XXX failure for case (with CryptoJS code) #{JSON.stringify v}" res = false if res_us isnt v.DK console.log "XXX failure for case (with our code) #{JSON.stringify v}" res = false cb res # Test vectors from http://tools.ietf.org/html/rfc6070 test_vectors = [{ rfc : 6070, case : 1, P : "password", S : "salt", c : 1, dkLen : 20, DK : "0c60c80f961f0e71f3a9b524af6012062fe037a6" },{ rfc : 6070, case : 2, P : "password", S : "salt", c : 2, dkLen : 20, DK : "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957" }, { rfc : 6070, case : 3, P : "password", S : "salt", c : 4096, dkLen : 20, DK : "4b007901b765489abead49d926f721d065a429c1" }, { rfc : 6070, case : 5, P : "passwordPASSWORDpassword", S : "saltSALTsaltSALTsaltSALTsaltSALTsalt", c : 4096, dkLen : 20, DK : "3d2eec4fe41c849b80c8d83662c0e44a8b291a96" }, { rfc : 6070, case : 6, P : "pass\0word", S : "sa\0lt", c : 4096, dkLen : 16, DK : "56fa6aa75548099dcc37d7f03425e0c3" } ] crazy_test_skip_for_now = { rfc : 6070, case : 4, P : "password", S : "salt", c : 16777216, dkLen : 20, DK : "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984" } rc = 0 for v,i in test_vectors await check_vector CryptoJS, v, defer res rc = 1 unless res process.exit rc
141715
#!/usr/bin/env node fs = require 'fs' {CryptoJS} = require 'cryptojs-1sp' derive = require '../src/lib/derive' check_vector = (CryptoJS, v, cb) -> opts = { keySize : v.dkLen / 4, iterations: v.c }; # Get the raw word array. raw_cjs = CryptoJS.PBKDF2(v.P, v.S, opts) v2o = new derive.V3 { get : () -> 0 }, CryptoJS.algo.SHA1 await v2o.test CryptoJS, v.P, v.S, v.c, defer raw_us # Convert to string, and also truncate after the first dkLen # bytes. Note it takes 2 hex-encoding character to encode a byte, # so double it up... [res_cjs, res_us] = (r.toString()[0...v.dkLen*2] for r in [ raw_cjs, raw_us]) res = true if res_cjs isnt v.DK console.log "XXX failure for case (with CryptoJS code) #{JSON.stringify v}" res = false if res_us isnt v.DK console.log "XXX failure for case (with our code) #{JSON.stringify v}" res = false cb res # Test vectors from http://tools.ietf.org/html/rfc6070 test_vectors = [{ rfc : 6070, case : 1, P : "<PASSWORD>", S : "<PASSWORD>", c : 1, dkLen : 20, DK : "0c60c80f961f0e71f3a9b524af6012062fe037a6" },{ rfc : 6070, case : 2, P : "<PASSWORD>", S : "<PASSWORD>", c : 2, dkLen : 20, DK : "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957" }, { rfc : 6070, case : 3, P : "<PASSWORD>", S : "<PASSWORD>", c : 4096, dkLen : 20, DK : "4b007901b765489abead49d926f721d065a429c1" }, { rfc : 6070, case : 5, P : "<PASSWORD>", S : "<PASSWORD>SALTsaltSALTsaltSALTsaltSALTsalt", c : 4096, dkLen : 20, DK : "3d2eec4fe41c849b80c8d83662c0e44a8b291a96" }, { rfc : 6070, case : 6, P : "<PASSWORD>", S : "sa\0lt", c : 4096, dkLen : 16, DK : "56fa6aa75548099dcc37d7f03425e0c3" } ] crazy_test_skip_for_now = { rfc : 6070, case : 4, P : "<PASSWORD>", S : "<PASSWORD>", c : 16777216, dkLen : 20, DK : "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984" } rc = 0 for v,i in test_vectors await check_vector CryptoJS, v, defer res rc = 1 unless res process.exit rc
true
#!/usr/bin/env node fs = require 'fs' {CryptoJS} = require 'cryptojs-1sp' derive = require '../src/lib/derive' check_vector = (CryptoJS, v, cb) -> opts = { keySize : v.dkLen / 4, iterations: v.c }; # Get the raw word array. raw_cjs = CryptoJS.PBKDF2(v.P, v.S, opts) v2o = new derive.V3 { get : () -> 0 }, CryptoJS.algo.SHA1 await v2o.test CryptoJS, v.P, v.S, v.c, defer raw_us # Convert to string, and also truncate after the first dkLen # bytes. Note it takes 2 hex-encoding character to encode a byte, # so double it up... [res_cjs, res_us] = (r.toString()[0...v.dkLen*2] for r in [ raw_cjs, raw_us]) res = true if res_cjs isnt v.DK console.log "XXX failure for case (with CryptoJS code) #{JSON.stringify v}" res = false if res_us isnt v.DK console.log "XXX failure for case (with our code) #{JSON.stringify v}" res = false cb res # Test vectors from http://tools.ietf.org/html/rfc6070 test_vectors = [{ rfc : 6070, case : 1, P : "PI:PASSWORD:<PASSWORD>END_PI", S : "PI:PASSWORD:<PASSWORD>END_PI", c : 1, dkLen : 20, DK : "0c60c80f961f0e71f3a9b524af6012062fe037a6" },{ rfc : 6070, case : 2, P : "PI:PASSWORD:<PASSWORD>END_PI", S : "PI:PASSWORD:<PASSWORD>END_PI", c : 2, dkLen : 20, DK : "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957" }, { rfc : 6070, case : 3, P : "PI:PASSWORD:<PASSWORD>END_PI", S : "PI:PASSWORD:<PASSWORD>END_PI", c : 4096, dkLen : 20, DK : "4b007901b765489abead49d926f721d065a429c1" }, { rfc : 6070, case : 5, P : "PI:PASSWORD:<PASSWORD>END_PI", S : "PI:PASSWORD:<PASSWORD>END_PISALTsaltSALTsaltSALTsaltSALTsalt", c : 4096, dkLen : 20, DK : "3d2eec4fe41c849b80c8d83662c0e44a8b291a96" }, { rfc : 6070, case : 6, P : "PI:PASSWORD:<PASSWORD>END_PI", S : "sa\0lt", c : 4096, dkLen : 16, DK : "56fa6aa75548099dcc37d7f03425e0c3" } ] crazy_test_skip_for_now = { rfc : 6070, case : 4, P : "PI:PASSWORD:<PASSWORD>END_PI", S : "PI:PASSWORD:<PASSWORD>END_PI", c : 16777216, dkLen : 20, DK : "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984" } rc = 0 for v,i in test_vectors await check_vector CryptoJS, v, defer res rc = 1 unless res process.exit rc
[ { "context": "nsureIndex({ manufacturer: 1, model: 1 })\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n@abstract\r\n###\r\nclass Prod", "end": 418, "score": 0.9998716115951538, "start": 406, "tag": "NAME", "value": "Nathan Klick" } ]
Workspace/QRef/NodeServer/src/schema/ProductSchema.coffee
qrefdev/qref
0
mongoose = require('mongoose') Schema = mongoose.Schema ObjectId = Schema.ObjectId ### Schema representing a saleable product. The product record is used in conjunction with the In-App Purchase Processes. @example MongoDB Collection db.products @example MongoDB Indexes db.products.ensureIndex({ name: 1 }, { unique: true }) db.products.ensureIndex({ manufacturer: 1, model: 1 }) @author Nathan Klick @copyright QRef 2012 @abstract ### class ProductSchemaInternal ### @property [String] (Required) A unique internal name for the product. Might possibly be a SKU or PN. ### name: type: String required: true ### @property [String] (Optional) A product description which will be visible on the product details screen. ### description: type: String required: false default: '' ### @property [Boolean] (Required) A true/false value indicating whether the product is published for consumer user. ### isPublished: type: Boolean required: true default: false ### @property [String] (Optional) An apple product code for the corresponding item in the iTunes store. ### appleProductIdentifier: type: String required: false ### @property [String] (Optional) A google product code for the corresponding item in the google play store. ### androidProductIdentifier: type: String required: false ### @property [Boolean] (Required) A true/false value indicating whether this product is available for apple devices. ### isAppleEnabled: type: Boolean required: true default: false ### @property [Boolean] (Required) A true/false value indicating whether this product is available for android devices. ### isAndroidEnabled: type: Boolean required: true default: false ### @property [Number] (Required) The suggested retail price for this product. Price may vary in iTunes and Google Play stores. ### suggestedRetailPrice: type: Number required: true default: 0 min: 0 max: 100.00 ### @property [String] (Required) An enumeration indicating general product category. Valid values are ['aviation', 'marine', 'navigation']. ### productCategory: type: String required: true enum: ['aviation', 'marine', 'navigation'] ### @property [String] (Required) An enumeration indicating the type of product. Valid values are ['checklist', 'manual', 'guide']. ### productType: type: String required: true enum: ['checklist', 'manual', 'guide'] ### @property [ObjectId] (Optional) An associated base checklist for aircraft products. This category represents the stock checklist that the user receives when purchasing the product. ### aircraftChecklist: type: ObjectId ref: 'aircraft.checklists' required: false default: null ### @property [Boolean] (Required) A true/false value indicating whether this product is a sample product which is included with the application at no charge. ### isSampleProduct: type: Boolean required: true default: false ### @property [String] (Optional) An string indicating which aircraft, marine, or navigation serial numbers are supported by this product. ### serialNumber: type: String required: false default: null ### @property [ObjectId] (Required) The manufacturer associated with this product. @see AircraftManufacturerSchemaInternal ### manufacturer: type: ObjectId ref: 'aircraft.manufacturers' required: true ### @property [ObjectId] (Required) The model associated with this product. @see AircraftModelSchemaInternal ### model: type: ObjectId ref: 'aircraft.models' required: true ### @property [String] (Optional) A server-based relative path to the cover artwork for this product. This path should be relative to the server root. ### coverImage: type: String required: false ### @property [String] (Optional) A server-based relative path to the icon for this product. This path should be relative to the server root. ### productIcon: type: String required: false ### @property [Boolean] For performing soft deletes ### isDeleted: type: Boolean required: true default: false ProductSchema = new Schema(new ProductSchemaInternal()) ProductSchema.index({ manufacturer: 1, model: 1 }) ProductSchema.index({ name: 1, }, { unique: true }) module.exports = ProductSchema
91578
mongoose = require('mongoose') Schema = mongoose.Schema ObjectId = Schema.ObjectId ### Schema representing a saleable product. The product record is used in conjunction with the In-App Purchase Processes. @example MongoDB Collection db.products @example MongoDB Indexes db.products.ensureIndex({ name: 1 }, { unique: true }) db.products.ensureIndex({ manufacturer: 1, model: 1 }) @author <NAME> @copyright QRef 2012 @abstract ### class ProductSchemaInternal ### @property [String] (Required) A unique internal name for the product. Might possibly be a SKU or PN. ### name: type: String required: true ### @property [String] (Optional) A product description which will be visible on the product details screen. ### description: type: String required: false default: '' ### @property [Boolean] (Required) A true/false value indicating whether the product is published for consumer user. ### isPublished: type: Boolean required: true default: false ### @property [String] (Optional) An apple product code for the corresponding item in the iTunes store. ### appleProductIdentifier: type: String required: false ### @property [String] (Optional) A google product code for the corresponding item in the google play store. ### androidProductIdentifier: type: String required: false ### @property [Boolean] (Required) A true/false value indicating whether this product is available for apple devices. ### isAppleEnabled: type: Boolean required: true default: false ### @property [Boolean] (Required) A true/false value indicating whether this product is available for android devices. ### isAndroidEnabled: type: Boolean required: true default: false ### @property [Number] (Required) The suggested retail price for this product. Price may vary in iTunes and Google Play stores. ### suggestedRetailPrice: type: Number required: true default: 0 min: 0 max: 100.00 ### @property [String] (Required) An enumeration indicating general product category. Valid values are ['aviation', 'marine', 'navigation']. ### productCategory: type: String required: true enum: ['aviation', 'marine', 'navigation'] ### @property [String] (Required) An enumeration indicating the type of product. Valid values are ['checklist', 'manual', 'guide']. ### productType: type: String required: true enum: ['checklist', 'manual', 'guide'] ### @property [ObjectId] (Optional) An associated base checklist for aircraft products. This category represents the stock checklist that the user receives when purchasing the product. ### aircraftChecklist: type: ObjectId ref: 'aircraft.checklists' required: false default: null ### @property [Boolean] (Required) A true/false value indicating whether this product is a sample product which is included with the application at no charge. ### isSampleProduct: type: Boolean required: true default: false ### @property [String] (Optional) An string indicating which aircraft, marine, or navigation serial numbers are supported by this product. ### serialNumber: type: String required: false default: null ### @property [ObjectId] (Required) The manufacturer associated with this product. @see AircraftManufacturerSchemaInternal ### manufacturer: type: ObjectId ref: 'aircraft.manufacturers' required: true ### @property [ObjectId] (Required) The model associated with this product. @see AircraftModelSchemaInternal ### model: type: ObjectId ref: 'aircraft.models' required: true ### @property [String] (Optional) A server-based relative path to the cover artwork for this product. This path should be relative to the server root. ### coverImage: type: String required: false ### @property [String] (Optional) A server-based relative path to the icon for this product. This path should be relative to the server root. ### productIcon: type: String required: false ### @property [Boolean] For performing soft deletes ### isDeleted: type: Boolean required: true default: false ProductSchema = new Schema(new ProductSchemaInternal()) ProductSchema.index({ manufacturer: 1, model: 1 }) ProductSchema.index({ name: 1, }, { unique: true }) module.exports = ProductSchema
true
mongoose = require('mongoose') Schema = mongoose.Schema ObjectId = Schema.ObjectId ### Schema representing a saleable product. The product record is used in conjunction with the In-App Purchase Processes. @example MongoDB Collection db.products @example MongoDB Indexes db.products.ensureIndex({ name: 1 }, { unique: true }) db.products.ensureIndex({ manufacturer: 1, model: 1 }) @author PI:NAME:<NAME>END_PI @copyright QRef 2012 @abstract ### class ProductSchemaInternal ### @property [String] (Required) A unique internal name for the product. Might possibly be a SKU or PN. ### name: type: String required: true ### @property [String] (Optional) A product description which will be visible on the product details screen. ### description: type: String required: false default: '' ### @property [Boolean] (Required) A true/false value indicating whether the product is published for consumer user. ### isPublished: type: Boolean required: true default: false ### @property [String] (Optional) An apple product code for the corresponding item in the iTunes store. ### appleProductIdentifier: type: String required: false ### @property [String] (Optional) A google product code for the corresponding item in the google play store. ### androidProductIdentifier: type: String required: false ### @property [Boolean] (Required) A true/false value indicating whether this product is available for apple devices. ### isAppleEnabled: type: Boolean required: true default: false ### @property [Boolean] (Required) A true/false value indicating whether this product is available for android devices. ### isAndroidEnabled: type: Boolean required: true default: false ### @property [Number] (Required) The suggested retail price for this product. Price may vary in iTunes and Google Play stores. ### suggestedRetailPrice: type: Number required: true default: 0 min: 0 max: 100.00 ### @property [String] (Required) An enumeration indicating general product category. Valid values are ['aviation', 'marine', 'navigation']. ### productCategory: type: String required: true enum: ['aviation', 'marine', 'navigation'] ### @property [String] (Required) An enumeration indicating the type of product. Valid values are ['checklist', 'manual', 'guide']. ### productType: type: String required: true enum: ['checklist', 'manual', 'guide'] ### @property [ObjectId] (Optional) An associated base checklist for aircraft products. This category represents the stock checklist that the user receives when purchasing the product. ### aircraftChecklist: type: ObjectId ref: 'aircraft.checklists' required: false default: null ### @property [Boolean] (Required) A true/false value indicating whether this product is a sample product which is included with the application at no charge. ### isSampleProduct: type: Boolean required: true default: false ### @property [String] (Optional) An string indicating which aircraft, marine, or navigation serial numbers are supported by this product. ### serialNumber: type: String required: false default: null ### @property [ObjectId] (Required) The manufacturer associated with this product. @see AircraftManufacturerSchemaInternal ### manufacturer: type: ObjectId ref: 'aircraft.manufacturers' required: true ### @property [ObjectId] (Required) The model associated with this product. @see AircraftModelSchemaInternal ### model: type: ObjectId ref: 'aircraft.models' required: true ### @property [String] (Optional) A server-based relative path to the cover artwork for this product. This path should be relative to the server root. ### coverImage: type: String required: false ### @property [String] (Optional) A server-based relative path to the icon for this product. This path should be relative to the server root. ### productIcon: type: String required: false ### @property [Boolean] For performing soft deletes ### isDeleted: type: Boolean required: true default: false ProductSchema = new Schema(new ProductSchemaInternal()) ProductSchema.index({ manufacturer: 1, model: 1 }) ProductSchema.index({ name: 1, }, { unique: true }) module.exports = ProductSchema
[ { "context": "Please re-create it manually. Please contact us at help@kobotoolbox.org so we can fix this bug!\"))}</em>\n </div>\n #", "end": 13706, "score": 0.9999254941940308, "start": 13686, "tag": "EMAIL", "value": "help@kobotoolbox.org" } ]
kobo-docker/.vols/static/kpi/xlform/src/view.row.templates.coffee
OpenOPx/kobotoolbox
0
module.exports = do -> _t = require('utils').t replaceSupportEmail = require('utils').replaceSupportEmail expandingSpacerHtml = """ <div class="survey__row__spacer row clearfix expanding-spacer-between-rows expanding-spacer-between-rows--depr"> <div tabIndex="0" class="js-expand-row-selector btn btn--addrow btn--block btn-xs btn-default add-row-btn" ><i class="fa fa-plus"></i></div> <div class="line">&nbsp;</div> </div> """ groupSettingsView = -> """ <section class="card__settings row-extras row-extras--depr"> <i class="card__settings-close fa fa-times js-toggle-card-settings"></i> <ul class="card__settings__tabs"> <li class="heading"><i class="fa fa-cog"></i> #{_t("Settings")}</li> <li data-card-settings-tab-id="all" class="card__settings__tabs__tab--active">#{_t("All group settings")}</li> <li data-card-settings-tab-id="skip-logic" class="">#{_t("Skip Logic")}</li> </ul> <div class="card__settings__content"> <div class="card__settings__fields card__settings__fields--active card__settings__fields--all"> </div> <div class="card__settings__fields card__settings__fields--skip-logic"></div> </div> </section> """ rowSettingsView = ()-> """ <section class="card__settings row-extras row-extras--depr"> <i class="card__settings-close fa fa-times js-toggle-card-settings"></i> <ul class="card__settings__tabs"> <li class="heading"><i class="fa fa-cog"></i> #{_t("Settings")}</li> <li data-card-settings-tab-id="question-options" class="card__settings__tabs__tab--active">#{_t("Question Options")}</li> <li data-card-settings-tab-id="skip-logic" class="">#{_t("Skip Logic")}</li> <li data-card-settings-tab-id="validation-criteria" class="">#{_t("Validation Criteria")}</li> <li data-card-settings-tab-id="response-type" class="card__settings__tab--response-type">#{_t("Response Type")}</li> </ul> <div class="card__settings__content"> <ul class="card__settings__fields card__settings__fields--active card__settings__fields--question-options"> </ul> <ul class="card__settings__fields card__settings__fields--skip-logic"> </ul> <ul class="card__settings__fields card__settings__fields--validation-criteria"> </ul> <ul class="card__settings__fields card__settings__fields--response-type"> </ul> </div> </section> """ xlfRowView = (surveyView) -> template = """ <div class="survey__row__item survey__row__item--question card js-select-row"> <div class="card__header"> <div class="card__header--shade"><span></span></div> <div class="card__indicator"> <div class="noop card__indicator__icon"><i class="fa fa-fw card__header-icon"></i></div> </div> <div class="card__text"> <input type="text" placeholder="#{_t("Question label is required")}" class="card__header-title js-card-label js-cancel-select-row js-cancel-sort"> <input type="text" placeholder="#{_t("Question hint")}" class="card__header-hint js-cancel-select-row js-cancel-sort"> </div> <div class="card__buttons"> <span class="card__buttons__button card__buttons__button--settings card__buttons__button--gray js-toggle-card-settings" data-button-name="settings"><i class="fa fa-cog"></i></span> <span class="card__buttons__button card__buttons__button--delete card__buttons__button--red js-delete-row" data-button-name="delete"><i class="fa fa-trash-o"></i></span> """ if surveyView.features.multipleQuestions template += """<span class="card__buttons__button card__buttons__button--copy card__buttons__button--blue js-clone-question" data-button-name="duplicate"><i class="fa fa-copy"></i></span> <span class="card__buttons__button card__buttons__button--add card__buttons__button--gray-green js-add-to-question-library" data-button-name="add-to-library"><i class="fa fa-folder-o"><i class="fa fa-plus"></i></i></span>""" return template + """ </div> </div> </div> #{expandingSpacerHtml} """ groupView = ()-> """ <div class="survey__row__item survey__row__item--group group card js-select-row"> <header class="group__header"> <i class="group__caret js-toggle-group-expansion fa fa-fw fa-caret-down"></i> <input type="text" class="card__header-title js-card-label js-cancel-select-row js-cancel-sort"> <div class="group__header__buttons"> <span class="group__header__buttons__button group__header__buttons__button--settings js-toggle-card-settings"><i class="fa fa-cog"></i></span> <span class="group__header__buttons__button group__header__buttons__button--delete js-delete-group"><i class="fa fa-trash-o"></i></span> </div> </header> <ul class="group__rows"> </ul> </div> #{expandingSpacerHtml} """ koboMatrixView = () -> template = """ <div class="survey__row__item survey__row__item--question card js-select-row"> <div class="card__header"> <div class="card__header--shade"><span></span></div> <div class="card__indicator"> <div class="noop card__indicator__icon"><i class="fa fa-fw card__header-icon fa-table"></i></div> </div> <div class="card__text"> <input type="text" placeholder="#{_t("Question label is required")}" class="card__header-title js-card-label js-cancel-select-row js-cancel-sort"> </div> <div class="card__buttons"> <span class="card__buttons__button card__buttons__button--settings card__buttons__button--gray js-toggle-card-settings" data-button-name="settings"><i class="fa fa-cog"></i></span> <span class="card__buttons__button card__buttons__button--delete card__buttons__button--red js-delete-row" data-button-name="delete"><i class="fa fa-trash-o"></i></span> </div> </div> <p class="kobomatrix-warning">#{_t("Note: The Matrix question type only works in Enketo web forms using the 'grid' style.")}</p> <div class="card__kobomatrix"> """ return template + """ </div> </div> #{expandingSpacerHtml} """ scoreView = (template_args={})-> fillers = [] cols = [] for col in template_args.score_choices fillers.push """<td class="scorecell__radio"><input type="radio" disabled="disabled"></td>""" autoname_class = "" autoname_attr = "" if col.autoname autoname_class = "scorecell__name--automatic" autoname_attr = """data-automatic-name="#{col.autoname}" """ namecell = """ <p class="scorecell__name #{autoname_class}" #{autoname_attr} contenteditable="true" title="Option value">#{col.name or ''}</p> """ cols.push """ <th class="scorecell__col" data-cid="#{col.cid}"> <span class="scorecell__label" contenteditable="true">#{col.label}</span><button class="scorecell__delete js-delete-scorecol">&times;</button> #{namecell} </th> """ thead_html = cols.join('') fillers = fillers.join('') tbody_html = for row in template_args.score_rows autoname_attr = "" autoname_class = "" if row.autoname autoname_class = "scorelabel__name--automatic" autoname_attr = """data-automatic-name="#{row.autoname}" """ scorelabel__name = """ <span class="scorelabel__name #{autoname_class}" #{autoname_attr} contenteditable="true" title="#{_t("Row name")}">#{row.name or ''}</span> """ """ <tr data-row-cid="#{row.cid}"> <td class="scorelabel"> <span class="scorelabel__edit" contenteditable="true">#{row.label}</span> <button class="scorerow__delete js-delete-scorerow">&times;</button> <br> #{scorelabel__name} </td> #{fillers} </tr> """ table_html = """ <table class="score_preview__table"> <thead> <th class="scorecell--empty"></th> #{thead_html} <th class="scorecell--add"><span>+</span></th> </thead> <tbody> #{tbody_html.join('')} </tbody> <tfoot> <tr> <td class="scorerow--add"><button>+</button></td> </tr> </tfoot> </table> """ """ <div class="score_preview"> #{table_html} </div> """ rankView = (s, template_args={})-> rank_levels_lis = for item in template_args.rank_levels autoclass = "" autoattr = "" autoattr = """data-automatic-name="#{item.automatic}" """ if item.set_automatic autoclass = "rank_items__name--automatic" """ <li class="rank_items__level" data-cid="#{item.cid}"> <span class="rank_items__level__label">#{item.label}</span><button class="rankcell__delete js-delete-rankcell">&times;</button> <br> <span class="rank_items__name #{autoclass}" #{autoattr}>#{item.name or ''}</span> </li> """ rank_rows_lis = for item in template_args.rank_rows autoclass = "" autoattr = "" autoattr = """data-automatic-name="#{item.automatic}" """ if item.set_automatic autoclass = "rank_items__name--automatic" """ <li class="rank_items__item" data-cid="#{item.cid}"> <span class="rank_items__item__label">#{item.label}</span><button class="rankcell__delete js-delete-rankcell">&times;</button> <br> <span class="rank_items__name #{autoclass}" #{autoattr}>#{item.name or ''}</span> </li> """ rank_constraint_message_html = """ <li class="rank_items__constraint_wrap"> <p class="rank_items__constraint_explanation"> #{_t("A constraint message to be read in case of error:")} </p> <p class="rank_items__constraint_message"> #{template_args.rank_constraint_msg} </p> </li> """ rank_constraint_message_li = """ #{rank_constraint_message_html} """ """ <div class="rank_preview clearfix"> <ol class="rank__rows"> #{rank_rows_lis.join('')} <li class="rank_items__add rank_items__add--item"><button>+</button></li> </ol> <ul class="rank__levels"> #{rank_levels_lis.join('')} <li class="rank_items__add rank_items__add--level"><button>+</button></li> #{rank_constraint_message_li} </ul> </div> """ mandatorySettingSelector = (uniqueName, currentValue) -> if currentValue is 'true' or currentValue is 'false' modifier = currentValue else modifier = 'custom' """ <div class="card__settings__fields__field"> <label>#{_t('Mandatory response')}:</label> <span class="settings__input"> <div class="radio"> <label class="radio__row mandatory-setting__row mandatory-setting__row--true"> <input class="radio__input js-mandatory-setting-radio" type="radio" name="#{uniqueName}" value="true" #{if modifier is 'true' then 'checked' else ''} > <span class="radio__label">#{_t('Yes')}</span> </label> <label class="radio__row mandatory-setting__row mandatory-setting__row--false"> <input class="radio__input js-mandatory-setting-radio" type="radio" name="#{uniqueName}" value="false" #{if modifier is 'false' then 'checked' else ''} > <span class="radio__label">#{_t('No')}</span> </label> <label class="radio__row mandatory-setting__row mandatory-setting__row--custom"> <input class="radio__input js-mandatory-setting-radio" type="radio" name="#{uniqueName}" value="custom" #{if modifier is 'custom' then 'checked' else ''} > <span class="radio__label">#{_t('Custom logic')}</span> <label class="text-box text-box--on-white"> <input type="text" class="text-box__input js-mandatory-setting-custom-text" value="#{currentValue}" placeholder="#{_t('Mandatory when this formula is true')}" > </label> </label> </div> </span> </div> """ paramsSettingsField = -> """ <div class="card__settings__fields__field params-view__settings-wrapper"> <label>#{_t('Parameters')}:</label> <span class="settings__input"> <div class="params-view"></div> </span> </div> """ paramsSimple = -> """ <div class="params-view__simple-wrapper"> <div class="params-view"></div> </div> """ selectQuestionExpansion = -> """ <div class="card--selectquestion__expansion row__multioptions js-cancel-sort"> <div class="list-view"> <ul></ul> </div> </div> """ expandChoiceList = ()-> """ <span class="card__buttons__multioptions js-toggle-row-multioptions js-cancel-select-row"><i class='right-and-down-caret' /></span> """ rowErrorView = (atts)-> """ <div class="card card--error"> #{_t("Row could not be displayed:")} <pre>#{atts}</pre> <em>#{replaceSupportEmail(_t("This question could not be imported. Please re-create it manually. Please contact us at help@kobotoolbox.org so we can fix this bug!"))}</em> </div> #{expandingSpacerHtml} """ xlfRowView: xlfRowView expandChoiceList: expandChoiceList mandatorySettingSelector: mandatorySettingSelector paramsSettingsField: paramsSettingsField paramsSimple: paramsSimple selectQuestionExpansion: selectQuestionExpansion groupView: groupView rowErrorView: rowErrorView koboMatrixView: koboMatrixView scoreView: scoreView rankView: rankView groupSettingsView: groupSettingsView rowSettingsView: rowSettingsView
199799
module.exports = do -> _t = require('utils').t replaceSupportEmail = require('utils').replaceSupportEmail expandingSpacerHtml = """ <div class="survey__row__spacer row clearfix expanding-spacer-between-rows expanding-spacer-between-rows--depr"> <div tabIndex="0" class="js-expand-row-selector btn btn--addrow btn--block btn-xs btn-default add-row-btn" ><i class="fa fa-plus"></i></div> <div class="line">&nbsp;</div> </div> """ groupSettingsView = -> """ <section class="card__settings row-extras row-extras--depr"> <i class="card__settings-close fa fa-times js-toggle-card-settings"></i> <ul class="card__settings__tabs"> <li class="heading"><i class="fa fa-cog"></i> #{_t("Settings")}</li> <li data-card-settings-tab-id="all" class="card__settings__tabs__tab--active">#{_t("All group settings")}</li> <li data-card-settings-tab-id="skip-logic" class="">#{_t("Skip Logic")}</li> </ul> <div class="card__settings__content"> <div class="card__settings__fields card__settings__fields--active card__settings__fields--all"> </div> <div class="card__settings__fields card__settings__fields--skip-logic"></div> </div> </section> """ rowSettingsView = ()-> """ <section class="card__settings row-extras row-extras--depr"> <i class="card__settings-close fa fa-times js-toggle-card-settings"></i> <ul class="card__settings__tabs"> <li class="heading"><i class="fa fa-cog"></i> #{_t("Settings")}</li> <li data-card-settings-tab-id="question-options" class="card__settings__tabs__tab--active">#{_t("Question Options")}</li> <li data-card-settings-tab-id="skip-logic" class="">#{_t("Skip Logic")}</li> <li data-card-settings-tab-id="validation-criteria" class="">#{_t("Validation Criteria")}</li> <li data-card-settings-tab-id="response-type" class="card__settings__tab--response-type">#{_t("Response Type")}</li> </ul> <div class="card__settings__content"> <ul class="card__settings__fields card__settings__fields--active card__settings__fields--question-options"> </ul> <ul class="card__settings__fields card__settings__fields--skip-logic"> </ul> <ul class="card__settings__fields card__settings__fields--validation-criteria"> </ul> <ul class="card__settings__fields card__settings__fields--response-type"> </ul> </div> </section> """ xlfRowView = (surveyView) -> template = """ <div class="survey__row__item survey__row__item--question card js-select-row"> <div class="card__header"> <div class="card__header--shade"><span></span></div> <div class="card__indicator"> <div class="noop card__indicator__icon"><i class="fa fa-fw card__header-icon"></i></div> </div> <div class="card__text"> <input type="text" placeholder="#{_t("Question label is required")}" class="card__header-title js-card-label js-cancel-select-row js-cancel-sort"> <input type="text" placeholder="#{_t("Question hint")}" class="card__header-hint js-cancel-select-row js-cancel-sort"> </div> <div class="card__buttons"> <span class="card__buttons__button card__buttons__button--settings card__buttons__button--gray js-toggle-card-settings" data-button-name="settings"><i class="fa fa-cog"></i></span> <span class="card__buttons__button card__buttons__button--delete card__buttons__button--red js-delete-row" data-button-name="delete"><i class="fa fa-trash-o"></i></span> """ if surveyView.features.multipleQuestions template += """<span class="card__buttons__button card__buttons__button--copy card__buttons__button--blue js-clone-question" data-button-name="duplicate"><i class="fa fa-copy"></i></span> <span class="card__buttons__button card__buttons__button--add card__buttons__button--gray-green js-add-to-question-library" data-button-name="add-to-library"><i class="fa fa-folder-o"><i class="fa fa-plus"></i></i></span>""" return template + """ </div> </div> </div> #{expandingSpacerHtml} """ groupView = ()-> """ <div class="survey__row__item survey__row__item--group group card js-select-row"> <header class="group__header"> <i class="group__caret js-toggle-group-expansion fa fa-fw fa-caret-down"></i> <input type="text" class="card__header-title js-card-label js-cancel-select-row js-cancel-sort"> <div class="group__header__buttons"> <span class="group__header__buttons__button group__header__buttons__button--settings js-toggle-card-settings"><i class="fa fa-cog"></i></span> <span class="group__header__buttons__button group__header__buttons__button--delete js-delete-group"><i class="fa fa-trash-o"></i></span> </div> </header> <ul class="group__rows"> </ul> </div> #{expandingSpacerHtml} """ koboMatrixView = () -> template = """ <div class="survey__row__item survey__row__item--question card js-select-row"> <div class="card__header"> <div class="card__header--shade"><span></span></div> <div class="card__indicator"> <div class="noop card__indicator__icon"><i class="fa fa-fw card__header-icon fa-table"></i></div> </div> <div class="card__text"> <input type="text" placeholder="#{_t("Question label is required")}" class="card__header-title js-card-label js-cancel-select-row js-cancel-sort"> </div> <div class="card__buttons"> <span class="card__buttons__button card__buttons__button--settings card__buttons__button--gray js-toggle-card-settings" data-button-name="settings"><i class="fa fa-cog"></i></span> <span class="card__buttons__button card__buttons__button--delete card__buttons__button--red js-delete-row" data-button-name="delete"><i class="fa fa-trash-o"></i></span> </div> </div> <p class="kobomatrix-warning">#{_t("Note: The Matrix question type only works in Enketo web forms using the 'grid' style.")}</p> <div class="card__kobomatrix"> """ return template + """ </div> </div> #{expandingSpacerHtml} """ scoreView = (template_args={})-> fillers = [] cols = [] for col in template_args.score_choices fillers.push """<td class="scorecell__radio"><input type="radio" disabled="disabled"></td>""" autoname_class = "" autoname_attr = "" if col.autoname autoname_class = "scorecell__name--automatic" autoname_attr = """data-automatic-name="#{col.autoname}" """ namecell = """ <p class="scorecell__name #{autoname_class}" #{autoname_attr} contenteditable="true" title="Option value">#{col.name or ''}</p> """ cols.push """ <th class="scorecell__col" data-cid="#{col.cid}"> <span class="scorecell__label" contenteditable="true">#{col.label}</span><button class="scorecell__delete js-delete-scorecol">&times;</button> #{namecell} </th> """ thead_html = cols.join('') fillers = fillers.join('') tbody_html = for row in template_args.score_rows autoname_attr = "" autoname_class = "" if row.autoname autoname_class = "scorelabel__name--automatic" autoname_attr = """data-automatic-name="#{row.autoname}" """ scorelabel__name = """ <span class="scorelabel__name #{autoname_class}" #{autoname_attr} contenteditable="true" title="#{_t("Row name")}">#{row.name or ''}</span> """ """ <tr data-row-cid="#{row.cid}"> <td class="scorelabel"> <span class="scorelabel__edit" contenteditable="true">#{row.label}</span> <button class="scorerow__delete js-delete-scorerow">&times;</button> <br> #{scorelabel__name} </td> #{fillers} </tr> """ table_html = """ <table class="score_preview__table"> <thead> <th class="scorecell--empty"></th> #{thead_html} <th class="scorecell--add"><span>+</span></th> </thead> <tbody> #{tbody_html.join('')} </tbody> <tfoot> <tr> <td class="scorerow--add"><button>+</button></td> </tr> </tfoot> </table> """ """ <div class="score_preview"> #{table_html} </div> """ rankView = (s, template_args={})-> rank_levels_lis = for item in template_args.rank_levels autoclass = "" autoattr = "" autoattr = """data-automatic-name="#{item.automatic}" """ if item.set_automatic autoclass = "rank_items__name--automatic" """ <li class="rank_items__level" data-cid="#{item.cid}"> <span class="rank_items__level__label">#{item.label}</span><button class="rankcell__delete js-delete-rankcell">&times;</button> <br> <span class="rank_items__name #{autoclass}" #{autoattr}>#{item.name or ''}</span> </li> """ rank_rows_lis = for item in template_args.rank_rows autoclass = "" autoattr = "" autoattr = """data-automatic-name="#{item.automatic}" """ if item.set_automatic autoclass = "rank_items__name--automatic" """ <li class="rank_items__item" data-cid="#{item.cid}"> <span class="rank_items__item__label">#{item.label}</span><button class="rankcell__delete js-delete-rankcell">&times;</button> <br> <span class="rank_items__name #{autoclass}" #{autoattr}>#{item.name or ''}</span> </li> """ rank_constraint_message_html = """ <li class="rank_items__constraint_wrap"> <p class="rank_items__constraint_explanation"> #{_t("A constraint message to be read in case of error:")} </p> <p class="rank_items__constraint_message"> #{template_args.rank_constraint_msg} </p> </li> """ rank_constraint_message_li = """ #{rank_constraint_message_html} """ """ <div class="rank_preview clearfix"> <ol class="rank__rows"> #{rank_rows_lis.join('')} <li class="rank_items__add rank_items__add--item"><button>+</button></li> </ol> <ul class="rank__levels"> #{rank_levels_lis.join('')} <li class="rank_items__add rank_items__add--level"><button>+</button></li> #{rank_constraint_message_li} </ul> </div> """ mandatorySettingSelector = (uniqueName, currentValue) -> if currentValue is 'true' or currentValue is 'false' modifier = currentValue else modifier = 'custom' """ <div class="card__settings__fields__field"> <label>#{_t('Mandatory response')}:</label> <span class="settings__input"> <div class="radio"> <label class="radio__row mandatory-setting__row mandatory-setting__row--true"> <input class="radio__input js-mandatory-setting-radio" type="radio" name="#{uniqueName}" value="true" #{if modifier is 'true' then 'checked' else ''} > <span class="radio__label">#{_t('Yes')}</span> </label> <label class="radio__row mandatory-setting__row mandatory-setting__row--false"> <input class="radio__input js-mandatory-setting-radio" type="radio" name="#{uniqueName}" value="false" #{if modifier is 'false' then 'checked' else ''} > <span class="radio__label">#{_t('No')}</span> </label> <label class="radio__row mandatory-setting__row mandatory-setting__row--custom"> <input class="radio__input js-mandatory-setting-radio" type="radio" name="#{uniqueName}" value="custom" #{if modifier is 'custom' then 'checked' else ''} > <span class="radio__label">#{_t('Custom logic')}</span> <label class="text-box text-box--on-white"> <input type="text" class="text-box__input js-mandatory-setting-custom-text" value="#{currentValue}" placeholder="#{_t('Mandatory when this formula is true')}" > </label> </label> </div> </span> </div> """ paramsSettingsField = -> """ <div class="card__settings__fields__field params-view__settings-wrapper"> <label>#{_t('Parameters')}:</label> <span class="settings__input"> <div class="params-view"></div> </span> </div> """ paramsSimple = -> """ <div class="params-view__simple-wrapper"> <div class="params-view"></div> </div> """ selectQuestionExpansion = -> """ <div class="card--selectquestion__expansion row__multioptions js-cancel-sort"> <div class="list-view"> <ul></ul> </div> </div> """ expandChoiceList = ()-> """ <span class="card__buttons__multioptions js-toggle-row-multioptions js-cancel-select-row"><i class='right-and-down-caret' /></span> """ rowErrorView = (atts)-> """ <div class="card card--error"> #{_t("Row could not be displayed:")} <pre>#{atts}</pre> <em>#{replaceSupportEmail(_t("This question could not be imported. Please re-create it manually. Please contact us at <EMAIL> so we can fix this bug!"))}</em> </div> #{expandingSpacerHtml} """ xlfRowView: xlfRowView expandChoiceList: expandChoiceList mandatorySettingSelector: mandatorySettingSelector paramsSettingsField: paramsSettingsField paramsSimple: paramsSimple selectQuestionExpansion: selectQuestionExpansion groupView: groupView rowErrorView: rowErrorView koboMatrixView: koboMatrixView scoreView: scoreView rankView: rankView groupSettingsView: groupSettingsView rowSettingsView: rowSettingsView
true
module.exports = do -> _t = require('utils').t replaceSupportEmail = require('utils').replaceSupportEmail expandingSpacerHtml = """ <div class="survey__row__spacer row clearfix expanding-spacer-between-rows expanding-spacer-between-rows--depr"> <div tabIndex="0" class="js-expand-row-selector btn btn--addrow btn--block btn-xs btn-default add-row-btn" ><i class="fa fa-plus"></i></div> <div class="line">&nbsp;</div> </div> """ groupSettingsView = -> """ <section class="card__settings row-extras row-extras--depr"> <i class="card__settings-close fa fa-times js-toggle-card-settings"></i> <ul class="card__settings__tabs"> <li class="heading"><i class="fa fa-cog"></i> #{_t("Settings")}</li> <li data-card-settings-tab-id="all" class="card__settings__tabs__tab--active">#{_t("All group settings")}</li> <li data-card-settings-tab-id="skip-logic" class="">#{_t("Skip Logic")}</li> </ul> <div class="card__settings__content"> <div class="card__settings__fields card__settings__fields--active card__settings__fields--all"> </div> <div class="card__settings__fields card__settings__fields--skip-logic"></div> </div> </section> """ rowSettingsView = ()-> """ <section class="card__settings row-extras row-extras--depr"> <i class="card__settings-close fa fa-times js-toggle-card-settings"></i> <ul class="card__settings__tabs"> <li class="heading"><i class="fa fa-cog"></i> #{_t("Settings")}</li> <li data-card-settings-tab-id="question-options" class="card__settings__tabs__tab--active">#{_t("Question Options")}</li> <li data-card-settings-tab-id="skip-logic" class="">#{_t("Skip Logic")}</li> <li data-card-settings-tab-id="validation-criteria" class="">#{_t("Validation Criteria")}</li> <li data-card-settings-tab-id="response-type" class="card__settings__tab--response-type">#{_t("Response Type")}</li> </ul> <div class="card__settings__content"> <ul class="card__settings__fields card__settings__fields--active card__settings__fields--question-options"> </ul> <ul class="card__settings__fields card__settings__fields--skip-logic"> </ul> <ul class="card__settings__fields card__settings__fields--validation-criteria"> </ul> <ul class="card__settings__fields card__settings__fields--response-type"> </ul> </div> </section> """ xlfRowView = (surveyView) -> template = """ <div class="survey__row__item survey__row__item--question card js-select-row"> <div class="card__header"> <div class="card__header--shade"><span></span></div> <div class="card__indicator"> <div class="noop card__indicator__icon"><i class="fa fa-fw card__header-icon"></i></div> </div> <div class="card__text"> <input type="text" placeholder="#{_t("Question label is required")}" class="card__header-title js-card-label js-cancel-select-row js-cancel-sort"> <input type="text" placeholder="#{_t("Question hint")}" class="card__header-hint js-cancel-select-row js-cancel-sort"> </div> <div class="card__buttons"> <span class="card__buttons__button card__buttons__button--settings card__buttons__button--gray js-toggle-card-settings" data-button-name="settings"><i class="fa fa-cog"></i></span> <span class="card__buttons__button card__buttons__button--delete card__buttons__button--red js-delete-row" data-button-name="delete"><i class="fa fa-trash-o"></i></span> """ if surveyView.features.multipleQuestions template += """<span class="card__buttons__button card__buttons__button--copy card__buttons__button--blue js-clone-question" data-button-name="duplicate"><i class="fa fa-copy"></i></span> <span class="card__buttons__button card__buttons__button--add card__buttons__button--gray-green js-add-to-question-library" data-button-name="add-to-library"><i class="fa fa-folder-o"><i class="fa fa-plus"></i></i></span>""" return template + """ </div> </div> </div> #{expandingSpacerHtml} """ groupView = ()-> """ <div class="survey__row__item survey__row__item--group group card js-select-row"> <header class="group__header"> <i class="group__caret js-toggle-group-expansion fa fa-fw fa-caret-down"></i> <input type="text" class="card__header-title js-card-label js-cancel-select-row js-cancel-sort"> <div class="group__header__buttons"> <span class="group__header__buttons__button group__header__buttons__button--settings js-toggle-card-settings"><i class="fa fa-cog"></i></span> <span class="group__header__buttons__button group__header__buttons__button--delete js-delete-group"><i class="fa fa-trash-o"></i></span> </div> </header> <ul class="group__rows"> </ul> </div> #{expandingSpacerHtml} """ koboMatrixView = () -> template = """ <div class="survey__row__item survey__row__item--question card js-select-row"> <div class="card__header"> <div class="card__header--shade"><span></span></div> <div class="card__indicator"> <div class="noop card__indicator__icon"><i class="fa fa-fw card__header-icon fa-table"></i></div> </div> <div class="card__text"> <input type="text" placeholder="#{_t("Question label is required")}" class="card__header-title js-card-label js-cancel-select-row js-cancel-sort"> </div> <div class="card__buttons"> <span class="card__buttons__button card__buttons__button--settings card__buttons__button--gray js-toggle-card-settings" data-button-name="settings"><i class="fa fa-cog"></i></span> <span class="card__buttons__button card__buttons__button--delete card__buttons__button--red js-delete-row" data-button-name="delete"><i class="fa fa-trash-o"></i></span> </div> </div> <p class="kobomatrix-warning">#{_t("Note: The Matrix question type only works in Enketo web forms using the 'grid' style.")}</p> <div class="card__kobomatrix"> """ return template + """ </div> </div> #{expandingSpacerHtml} """ scoreView = (template_args={})-> fillers = [] cols = [] for col in template_args.score_choices fillers.push """<td class="scorecell__radio"><input type="radio" disabled="disabled"></td>""" autoname_class = "" autoname_attr = "" if col.autoname autoname_class = "scorecell__name--automatic" autoname_attr = """data-automatic-name="#{col.autoname}" """ namecell = """ <p class="scorecell__name #{autoname_class}" #{autoname_attr} contenteditable="true" title="Option value">#{col.name or ''}</p> """ cols.push """ <th class="scorecell__col" data-cid="#{col.cid}"> <span class="scorecell__label" contenteditable="true">#{col.label}</span><button class="scorecell__delete js-delete-scorecol">&times;</button> #{namecell} </th> """ thead_html = cols.join('') fillers = fillers.join('') tbody_html = for row in template_args.score_rows autoname_attr = "" autoname_class = "" if row.autoname autoname_class = "scorelabel__name--automatic" autoname_attr = """data-automatic-name="#{row.autoname}" """ scorelabel__name = """ <span class="scorelabel__name #{autoname_class}" #{autoname_attr} contenteditable="true" title="#{_t("Row name")}">#{row.name or ''}</span> """ """ <tr data-row-cid="#{row.cid}"> <td class="scorelabel"> <span class="scorelabel__edit" contenteditable="true">#{row.label}</span> <button class="scorerow__delete js-delete-scorerow">&times;</button> <br> #{scorelabel__name} </td> #{fillers} </tr> """ table_html = """ <table class="score_preview__table"> <thead> <th class="scorecell--empty"></th> #{thead_html} <th class="scorecell--add"><span>+</span></th> </thead> <tbody> #{tbody_html.join('')} </tbody> <tfoot> <tr> <td class="scorerow--add"><button>+</button></td> </tr> </tfoot> </table> """ """ <div class="score_preview"> #{table_html} </div> """ rankView = (s, template_args={})-> rank_levels_lis = for item in template_args.rank_levels autoclass = "" autoattr = "" autoattr = """data-automatic-name="#{item.automatic}" """ if item.set_automatic autoclass = "rank_items__name--automatic" """ <li class="rank_items__level" data-cid="#{item.cid}"> <span class="rank_items__level__label">#{item.label}</span><button class="rankcell__delete js-delete-rankcell">&times;</button> <br> <span class="rank_items__name #{autoclass}" #{autoattr}>#{item.name or ''}</span> </li> """ rank_rows_lis = for item in template_args.rank_rows autoclass = "" autoattr = "" autoattr = """data-automatic-name="#{item.automatic}" """ if item.set_automatic autoclass = "rank_items__name--automatic" """ <li class="rank_items__item" data-cid="#{item.cid}"> <span class="rank_items__item__label">#{item.label}</span><button class="rankcell__delete js-delete-rankcell">&times;</button> <br> <span class="rank_items__name #{autoclass}" #{autoattr}>#{item.name or ''}</span> </li> """ rank_constraint_message_html = """ <li class="rank_items__constraint_wrap"> <p class="rank_items__constraint_explanation"> #{_t("A constraint message to be read in case of error:")} </p> <p class="rank_items__constraint_message"> #{template_args.rank_constraint_msg} </p> </li> """ rank_constraint_message_li = """ #{rank_constraint_message_html} """ """ <div class="rank_preview clearfix"> <ol class="rank__rows"> #{rank_rows_lis.join('')} <li class="rank_items__add rank_items__add--item"><button>+</button></li> </ol> <ul class="rank__levels"> #{rank_levels_lis.join('')} <li class="rank_items__add rank_items__add--level"><button>+</button></li> #{rank_constraint_message_li} </ul> </div> """ mandatorySettingSelector = (uniqueName, currentValue) -> if currentValue is 'true' or currentValue is 'false' modifier = currentValue else modifier = 'custom' """ <div class="card__settings__fields__field"> <label>#{_t('Mandatory response')}:</label> <span class="settings__input"> <div class="radio"> <label class="radio__row mandatory-setting__row mandatory-setting__row--true"> <input class="radio__input js-mandatory-setting-radio" type="radio" name="#{uniqueName}" value="true" #{if modifier is 'true' then 'checked' else ''} > <span class="radio__label">#{_t('Yes')}</span> </label> <label class="radio__row mandatory-setting__row mandatory-setting__row--false"> <input class="radio__input js-mandatory-setting-radio" type="radio" name="#{uniqueName}" value="false" #{if modifier is 'false' then 'checked' else ''} > <span class="radio__label">#{_t('No')}</span> </label> <label class="radio__row mandatory-setting__row mandatory-setting__row--custom"> <input class="radio__input js-mandatory-setting-radio" type="radio" name="#{uniqueName}" value="custom" #{if modifier is 'custom' then 'checked' else ''} > <span class="radio__label">#{_t('Custom logic')}</span> <label class="text-box text-box--on-white"> <input type="text" class="text-box__input js-mandatory-setting-custom-text" value="#{currentValue}" placeholder="#{_t('Mandatory when this formula is true')}" > </label> </label> </div> </span> </div> """ paramsSettingsField = -> """ <div class="card__settings__fields__field params-view__settings-wrapper"> <label>#{_t('Parameters')}:</label> <span class="settings__input"> <div class="params-view"></div> </span> </div> """ paramsSimple = -> """ <div class="params-view__simple-wrapper"> <div class="params-view"></div> </div> """ selectQuestionExpansion = -> """ <div class="card--selectquestion__expansion row__multioptions js-cancel-sort"> <div class="list-view"> <ul></ul> </div> </div> """ expandChoiceList = ()-> """ <span class="card__buttons__multioptions js-toggle-row-multioptions js-cancel-select-row"><i class='right-and-down-caret' /></span> """ rowErrorView = (atts)-> """ <div class="card card--error"> #{_t("Row could not be displayed:")} <pre>#{atts}</pre> <em>#{replaceSupportEmail(_t("This question could not be imported. Please re-create it manually. Please contact us at PI:EMAIL:<EMAIL>END_PI so we can fix this bug!"))}</em> </div> #{expandingSpacerHtml} """ xlfRowView: xlfRowView expandChoiceList: expandChoiceList mandatorySettingSelector: mandatorySettingSelector paramsSettingsField: paramsSettingsField paramsSimple: paramsSimple selectQuestionExpansion: selectQuestionExpansion groupView: groupView rowErrorView: rowErrorView koboMatrixView: koboMatrixView scoreView: scoreView rankView: rankView groupSettingsView: groupSettingsView rowSettingsView: rowSettingsView
[ { "context": "env.REDIS_PORT, process.env.REDIS_HOST, auth_pass: process.env.REDIS_PASSWORD\n client.unref()\n\n @configurat", "end": 711, "score": 0.8405070900917053, "start": 700, "tag": "PASSWORD", "value": "process.env" } ]
nanocyte-engine-in-a-vat.coffee
octoblu/nanocyte-engine-in-a-vat
0
fs = require 'fs' {PassThrough} = require 'stream' _ = require 'lodash' redis = require 'redis' debug = require('debug')('nanocyte-engine-in-a-vat') Router = require '@octoblu/nanocyte-engine-simple' ConfigurationGenerator = require 'nanocyte-configuration-generator' ConfigurationSaver = require 'nanocyte-configuration-saver-redis' getVatNodeAssembler = require './get-vat-node-assembler' AddNodeInfoStream = require './add-node-info-stream' class NanocyteEngineInAVat constructor: (options) -> {@flowName, @flowData} = options @instanceId = 'engine-in-a-vat' @triggers = @findTriggers() client = redis.createClient process.env.REDIS_PORT, process.env.REDIS_HOST, auth_pass: process.env.REDIS_PASSWORD client.unref() @configurationGenerator = new ConfigurationGenerator {} @configurationSaver = new ConfigurationSaver client initialize: (callback=->) => @configurationGenerator.configure flowData: @flowData, userData: {}, (error, configuration) => return console.error "config generator had an error!", error if error? debug 'configured' @configuration = configuration @configurationSaver.save flowId: @flowName, instanceId: @instanceId, flowData: configuration, (error, result)=> return console.error "config saver had an error!", error if error? debug 'saved' callback(null, configuration) triggerByName: ({name, message}) => trigger = @triggers[name] throw new Error "Can't find a trigger named '#{name}'" unless trigger? @messageRouter trigger.id, message messageRouter: (nodeId, message) => outputStream = new AddNodeInfoStream flowData: @flowData, nanocyteConfig: @configuration envelope = metadata: fromNodeId: nodeId flowId: @flowName instanceId: @instanceId message: message @setupRouter outputStream, (error, router) => router.message(envelope) outputStream setupRouter: (outputStream, callback) => router = new Router @flowName, 'engine-in-a-vat', NodeAssembler: getVatNodeAssembler(outputStream) router.initialize => callback null, router outputStream findTriggers: => _.indexBy _.filter(@flowData.nodes, type: 'operation:trigger'), 'name' module.exports = NanocyteEngineInAVat
214909
fs = require 'fs' {PassThrough} = require 'stream' _ = require 'lodash' redis = require 'redis' debug = require('debug')('nanocyte-engine-in-a-vat') Router = require '@octoblu/nanocyte-engine-simple' ConfigurationGenerator = require 'nanocyte-configuration-generator' ConfigurationSaver = require 'nanocyte-configuration-saver-redis' getVatNodeAssembler = require './get-vat-node-assembler' AddNodeInfoStream = require './add-node-info-stream' class NanocyteEngineInAVat constructor: (options) -> {@flowName, @flowData} = options @instanceId = 'engine-in-a-vat' @triggers = @findTriggers() client = redis.createClient process.env.REDIS_PORT, process.env.REDIS_HOST, auth_pass: <PASSWORD>.REDIS_PASSWORD client.unref() @configurationGenerator = new ConfigurationGenerator {} @configurationSaver = new ConfigurationSaver client initialize: (callback=->) => @configurationGenerator.configure flowData: @flowData, userData: {}, (error, configuration) => return console.error "config generator had an error!", error if error? debug 'configured' @configuration = configuration @configurationSaver.save flowId: @flowName, instanceId: @instanceId, flowData: configuration, (error, result)=> return console.error "config saver had an error!", error if error? debug 'saved' callback(null, configuration) triggerByName: ({name, message}) => trigger = @triggers[name] throw new Error "Can't find a trigger named '#{name}'" unless trigger? @messageRouter trigger.id, message messageRouter: (nodeId, message) => outputStream = new AddNodeInfoStream flowData: @flowData, nanocyteConfig: @configuration envelope = metadata: fromNodeId: nodeId flowId: @flowName instanceId: @instanceId message: message @setupRouter outputStream, (error, router) => router.message(envelope) outputStream setupRouter: (outputStream, callback) => router = new Router @flowName, 'engine-in-a-vat', NodeAssembler: getVatNodeAssembler(outputStream) router.initialize => callback null, router outputStream findTriggers: => _.indexBy _.filter(@flowData.nodes, type: 'operation:trigger'), 'name' module.exports = NanocyteEngineInAVat
true
fs = require 'fs' {PassThrough} = require 'stream' _ = require 'lodash' redis = require 'redis' debug = require('debug')('nanocyte-engine-in-a-vat') Router = require '@octoblu/nanocyte-engine-simple' ConfigurationGenerator = require 'nanocyte-configuration-generator' ConfigurationSaver = require 'nanocyte-configuration-saver-redis' getVatNodeAssembler = require './get-vat-node-assembler' AddNodeInfoStream = require './add-node-info-stream' class NanocyteEngineInAVat constructor: (options) -> {@flowName, @flowData} = options @instanceId = 'engine-in-a-vat' @triggers = @findTriggers() client = redis.createClient process.env.REDIS_PORT, process.env.REDIS_HOST, auth_pass: PI:PASSWORD:<PASSWORD>END_PI.REDIS_PASSWORD client.unref() @configurationGenerator = new ConfigurationGenerator {} @configurationSaver = new ConfigurationSaver client initialize: (callback=->) => @configurationGenerator.configure flowData: @flowData, userData: {}, (error, configuration) => return console.error "config generator had an error!", error if error? debug 'configured' @configuration = configuration @configurationSaver.save flowId: @flowName, instanceId: @instanceId, flowData: configuration, (error, result)=> return console.error "config saver had an error!", error if error? debug 'saved' callback(null, configuration) triggerByName: ({name, message}) => trigger = @triggers[name] throw new Error "Can't find a trigger named '#{name}'" unless trigger? @messageRouter trigger.id, message messageRouter: (nodeId, message) => outputStream = new AddNodeInfoStream flowData: @flowData, nanocyteConfig: @configuration envelope = metadata: fromNodeId: nodeId flowId: @flowName instanceId: @instanceId message: message @setupRouter outputStream, (error, router) => router.message(envelope) outputStream setupRouter: (outputStream, callback) => router = new Router @flowName, 'engine-in-a-vat', NodeAssembler: getVatNodeAssembler(outputStream) router.initialize => callback null, router outputStream findTriggers: => _.indexBy _.filter(@flowData.nodes, type: 'operation:trigger'), 'name' module.exports = NanocyteEngineInAVat
[ { "context": "080'\n\tdefaults:\n\t\theaders:\n\t\t\t'X-Authorization': '12345'\n\t\tfields:\n\t\t\t'_csrf_token': '12345'\n\t\tparams:\n\t\t", "end": 194, "score": 0.8499467968940735, "start": 189, "tag": "PASSWORD", "value": "12345" }, { "context": "horization': '12345'\n\t\tfields...
test/nodejs/restie.test.coffee
vadimdemedes/restie
5
# Setting up Restie if not window? Restie = require '../../' expect = require 'expect.js' Restie.set urls: base: 'http://localhost:8080' defaults: headers: 'X-Authorization': '12345' fields: '_csrf_token': '12345' params: '_csrf_token': '12345' Post = Restie.define 'Post', wrapFields: no primaryKey: 'id' # Tests describe 'Restie', -> describe 'CRUD', -> it 'should fetch all posts', (done) -> Post.all (err, posts) -> expect(posts.length).to.be(0) do done it 'should create post, slow method', (done) -> post = new Post post.title = 'New post' post.body = 'Content' post.save -> Post.all (err, posts) -> expect(posts.length).to.be(1) do done it 'should create post, faster method', (done) -> post = new Post title: 'New post', body: 'Content' post.save -> Post.all (err, posts) -> expect(posts.length).to.be(2) do done it 'should create post, fastest method', (done) -> Post.create title: 'New post', body: 'Content', (err, post) -> Post.all (err, posts) -> expect(posts.length).to.be(3) do done it 'should find post', (done) -> Post.find_by_id 1, (err, post) -> expect(post.title).to.be('New post') do done it 'should update post', (done) -> Post.find_by_id 1, (err, post) -> post.title = 'New title' post.save -> Post.find_by_id 1, (err, post) -> expect(post.title).to.be('New title') do done it 'should remove post', (done) -> Post.find_by_id 1, (err, post) -> post.remove -> Post.all (err, posts) -> expect(posts.length).to.be(2) do done
215491
# Setting up Restie if not window? Restie = require '../../' expect = require 'expect.js' Restie.set urls: base: 'http://localhost:8080' defaults: headers: 'X-Authorization': '<PASSWORD>' fields: '_csrf_token': '<PASSWORD>' params: '_csrf_token': '<PASSWORD>' Post = Restie.define 'Post', wrapFields: no primaryKey: 'id' # Tests describe 'Restie', -> describe 'CRUD', -> it 'should fetch all posts', (done) -> Post.all (err, posts) -> expect(posts.length).to.be(0) do done it 'should create post, slow method', (done) -> post = new Post post.title = 'New post' post.body = 'Content' post.save -> Post.all (err, posts) -> expect(posts.length).to.be(1) do done it 'should create post, faster method', (done) -> post = new Post title: 'New post', body: 'Content' post.save -> Post.all (err, posts) -> expect(posts.length).to.be(2) do done it 'should create post, fastest method', (done) -> Post.create title: 'New post', body: 'Content', (err, post) -> Post.all (err, posts) -> expect(posts.length).to.be(3) do done it 'should find post', (done) -> Post.find_by_id 1, (err, post) -> expect(post.title).to.be('New post') do done it 'should update post', (done) -> Post.find_by_id 1, (err, post) -> post.title = 'New title' post.save -> Post.find_by_id 1, (err, post) -> expect(post.title).to.be('New title') do done it 'should remove post', (done) -> Post.find_by_id 1, (err, post) -> post.remove -> Post.all (err, posts) -> expect(posts.length).to.be(2) do done
true
# Setting up Restie if not window? Restie = require '../../' expect = require 'expect.js' Restie.set urls: base: 'http://localhost:8080' defaults: headers: 'X-Authorization': 'PI:PASSWORD:<PASSWORD>END_PI' fields: '_csrf_token': 'PI:PASSWORD:<PASSWORD>END_PI' params: '_csrf_token': 'PI:PASSWORD:<PASSWORD>END_PI' Post = Restie.define 'Post', wrapFields: no primaryKey: 'id' # Tests describe 'Restie', -> describe 'CRUD', -> it 'should fetch all posts', (done) -> Post.all (err, posts) -> expect(posts.length).to.be(0) do done it 'should create post, slow method', (done) -> post = new Post post.title = 'New post' post.body = 'Content' post.save -> Post.all (err, posts) -> expect(posts.length).to.be(1) do done it 'should create post, faster method', (done) -> post = new Post title: 'New post', body: 'Content' post.save -> Post.all (err, posts) -> expect(posts.length).to.be(2) do done it 'should create post, fastest method', (done) -> Post.create title: 'New post', body: 'Content', (err, post) -> Post.all (err, posts) -> expect(posts.length).to.be(3) do done it 'should find post', (done) -> Post.find_by_id 1, (err, post) -> expect(post.title).to.be('New post') do done it 'should update post', (done) -> Post.find_by_id 1, (err, post) -> post.title = 'New title' post.save -> Post.find_by_id 1, (err, post) -> expect(post.title).to.be('New title') do done it 'should remove post', (done) -> Post.find_by_id 1, (err, post) -> post.remove -> Post.all (err, posts) -> expect(posts.length).to.be(2) do done
[ { "context": "\": \"Fh8xVqod2MQ1mocfI4S4KpRL6D98\",\n\t\t\t# \"key\": \"gogopher.jpg\"\n\t\t\t# }\n\t\t\tinfo = $.parseJSON info\n\t\t\tdomain = up", "end": 1887, "score": 0.9993619918823242, "start": 1875, "tag": "KEY", "value": "gogopher.jpg" } ]
public/src/common/uploader/index.coffee
yuanzm/Live-Chat
56
### 调用方法 behindUploader = new Uploader { domain: "http://7xj0sp.com1.z0.glb.clouddn.com/" # bucket 域名,下载资源时用到,**必需** browse_button: 'negative-file', # 上传选择的点选按钮,**必需** container: 'negative-wrapper', # 上传选择的点选按钮,**必需** }, { FileUploaded: (up, file, info)-> info = $.parseJSON info domain = up.getOption('domain') $("#negative-wrapper").find(".content-img").removeClass("hidden").find("img").attr("src", domain + info.key) $("#negative-wrapper").find(".img-border").addClass("hidden") } 构造函数的第一个参数对象包含了用来覆盖默认参数中除了init之外的各项属性的值 第二个参数对象包含了用来覆盖默认参数中init对象内方法的函数 未被指定的属性将以默认参数中的值进行传递 ### ### 默认参数 ### _defaultConfig = runtimes: 'html5,flash,html4', # 上传模式,依次退化 browse_button: 'click-file', # 上传选择的点选按钮,**必需** uptoken_url: '/uptoken', # Ajax请求upToken的Url,**强烈建议设置**(服务端提供) domain: "http://7te9k1.com1.z0.glb.clouddn.com/" # bucket 域名,下载资源时用到,**必需** container: 'container', # 上传区域DOM ID,默认是browser_button的父元素, max_file_size: '5mb', # 最大文件体积限制 flash_swf_url: '/lib/plupload/Moxie.swf', # 引入flash,相对路径 max_retries: 3, # 上传失败最大重试次数 dragdrop: false, # 关闭可拖曳上传 drop_element: 'container', # 拖曳上传区域元素的ID,拖曳文件或文件夹后可触发上传 chunk_size: '4mb', # 分块上传时,每片的体积 auto_start: true, # 选择文件后自动上传,若关闭需要自己绑定事件触发上传, unique_names: true, save_key: true, statusTip: '.image-upload-tips' # 显示图片上传进度的标签的选择器 init: { 'Error': (up, err, errTip)-> console.log errTip # 上传出错时,处理相关的事情 'BeforeUpload': (up, file)-> $(@getOption().statusTip).text('准备上传图片') # console.log up # 每个文件上传前,处理相关的事情 'UploadProgress': (up, file)-> $(@getOption().statusTip).text('正在上传图片') 'FileUploaded': (up, file, info)-> # 每个文件上传成功后,处理相关的事情 # 其中 info 是文件上传成功后,服务端返回的json,形式如 # { # "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98", # "key": "gogopher.jpg" # } info = $.parseJSON info domain = up.getOption('domain') 'UploadComplete': ()-> # console.log "UploadComplete" $(@getOption().statusTip).text('图片上传成功') # 队列文件处理完毕后,处理相关的事情 } class Uploader constructor: (options, handlers)-> config = $.extend {}, _defaultConfig, options for name, callback of handlers config.init[name] = callback uploader = Qiniu.uploader config module.exports = Uploader
10433
### 调用方法 behindUploader = new Uploader { domain: "http://7xj0sp.com1.z0.glb.clouddn.com/" # bucket 域名,下载资源时用到,**必需** browse_button: 'negative-file', # 上传选择的点选按钮,**必需** container: 'negative-wrapper', # 上传选择的点选按钮,**必需** }, { FileUploaded: (up, file, info)-> info = $.parseJSON info domain = up.getOption('domain') $("#negative-wrapper").find(".content-img").removeClass("hidden").find("img").attr("src", domain + info.key) $("#negative-wrapper").find(".img-border").addClass("hidden") } 构造函数的第一个参数对象包含了用来覆盖默认参数中除了init之外的各项属性的值 第二个参数对象包含了用来覆盖默认参数中init对象内方法的函数 未被指定的属性将以默认参数中的值进行传递 ### ### 默认参数 ### _defaultConfig = runtimes: 'html5,flash,html4', # 上传模式,依次退化 browse_button: 'click-file', # 上传选择的点选按钮,**必需** uptoken_url: '/uptoken', # Ajax请求upToken的Url,**强烈建议设置**(服务端提供) domain: "http://7te9k1.com1.z0.glb.clouddn.com/" # bucket 域名,下载资源时用到,**必需** container: 'container', # 上传区域DOM ID,默认是browser_button的父元素, max_file_size: '5mb', # 最大文件体积限制 flash_swf_url: '/lib/plupload/Moxie.swf', # 引入flash,相对路径 max_retries: 3, # 上传失败最大重试次数 dragdrop: false, # 关闭可拖曳上传 drop_element: 'container', # 拖曳上传区域元素的ID,拖曳文件或文件夹后可触发上传 chunk_size: '4mb', # 分块上传时,每片的体积 auto_start: true, # 选择文件后自动上传,若关闭需要自己绑定事件触发上传, unique_names: true, save_key: true, statusTip: '.image-upload-tips' # 显示图片上传进度的标签的选择器 init: { 'Error': (up, err, errTip)-> console.log errTip # 上传出错时,处理相关的事情 'BeforeUpload': (up, file)-> $(@getOption().statusTip).text('准备上传图片') # console.log up # 每个文件上传前,处理相关的事情 'UploadProgress': (up, file)-> $(@getOption().statusTip).text('正在上传图片') 'FileUploaded': (up, file, info)-> # 每个文件上传成功后,处理相关的事情 # 其中 info 是文件上传成功后,服务端返回的json,形式如 # { # "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98", # "key": "<KEY>" # } info = $.parseJSON info domain = up.getOption('domain') 'UploadComplete': ()-> # console.log "UploadComplete" $(@getOption().statusTip).text('图片上传成功') # 队列文件处理完毕后,处理相关的事情 } class Uploader constructor: (options, handlers)-> config = $.extend {}, _defaultConfig, options for name, callback of handlers config.init[name] = callback uploader = Qiniu.uploader config module.exports = Uploader
true
### 调用方法 behindUploader = new Uploader { domain: "http://7xj0sp.com1.z0.glb.clouddn.com/" # bucket 域名,下载资源时用到,**必需** browse_button: 'negative-file', # 上传选择的点选按钮,**必需** container: 'negative-wrapper', # 上传选择的点选按钮,**必需** }, { FileUploaded: (up, file, info)-> info = $.parseJSON info domain = up.getOption('domain') $("#negative-wrapper").find(".content-img").removeClass("hidden").find("img").attr("src", domain + info.key) $("#negative-wrapper").find(".img-border").addClass("hidden") } 构造函数的第一个参数对象包含了用来覆盖默认参数中除了init之外的各项属性的值 第二个参数对象包含了用来覆盖默认参数中init对象内方法的函数 未被指定的属性将以默认参数中的值进行传递 ### ### 默认参数 ### _defaultConfig = runtimes: 'html5,flash,html4', # 上传模式,依次退化 browse_button: 'click-file', # 上传选择的点选按钮,**必需** uptoken_url: '/uptoken', # Ajax请求upToken的Url,**强烈建议设置**(服务端提供) domain: "http://7te9k1.com1.z0.glb.clouddn.com/" # bucket 域名,下载资源时用到,**必需** container: 'container', # 上传区域DOM ID,默认是browser_button的父元素, max_file_size: '5mb', # 最大文件体积限制 flash_swf_url: '/lib/plupload/Moxie.swf', # 引入flash,相对路径 max_retries: 3, # 上传失败最大重试次数 dragdrop: false, # 关闭可拖曳上传 drop_element: 'container', # 拖曳上传区域元素的ID,拖曳文件或文件夹后可触发上传 chunk_size: '4mb', # 分块上传时,每片的体积 auto_start: true, # 选择文件后自动上传,若关闭需要自己绑定事件触发上传, unique_names: true, save_key: true, statusTip: '.image-upload-tips' # 显示图片上传进度的标签的选择器 init: { 'Error': (up, err, errTip)-> console.log errTip # 上传出错时,处理相关的事情 'BeforeUpload': (up, file)-> $(@getOption().statusTip).text('准备上传图片') # console.log up # 每个文件上传前,处理相关的事情 'UploadProgress': (up, file)-> $(@getOption().statusTip).text('正在上传图片') 'FileUploaded': (up, file, info)-> # 每个文件上传成功后,处理相关的事情 # 其中 info 是文件上传成功后,服务端返回的json,形式如 # { # "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98", # "key": "PI:KEY:<KEY>END_PI" # } info = $.parseJSON info domain = up.getOption('domain') 'UploadComplete': ()-> # console.log "UploadComplete" $(@getOption().statusTip).text('图片上传成功') # 队列文件处理完毕后,处理相关的事情 } class Uploader constructor: (options, handlers)-> config = $.extend {}, _defaultConfig, options for name, callback of handlers config.init[name] = callback uploader = Qiniu.uploader config module.exports = Uploader
[ { "context": " process.env.HUBOT_BITBUCKET_AUTH_USER\n password: process.env.HUBOT_BITBUCKET_AUTH_PASS\n\nall_repos = process.env.HUBOT_BI", "end": 126, "score": 0.9035999774932861, "start": 105, "tag": "PASSWORD", "value": "process.env.HUBOT_BIT" }, { "context": "_USER\n password:...
src/libs/bitbucket.coffee
joaofraga/hubot-bitbucket-pullrequests
1
timeago = require 'timeago' credentials = username: process.env.HUBOT_BITBUCKET_AUTH_USER password: process.env.HUBOT_BITBUCKET_AUTH_PASS all_repos = process.env.HUBOT_BITBUCKET_REPOSITORIES.split(",") class BitBucket constructor: (credentials, repos = "") -> bitBucket = require 'sand-bucket' @client = bitBucket.createClient(credentials) @repositories = repos summary: (msg, repo) -> _repositories = if repo? then [repo] else @repositories for repository in _repositories @getRepository repository, (err, repo) -> # Repository logic comes here # TODO: think some way to easily load PRs and show on screen repo.pullRequests().getAll (err, pullRequests) -> pullRequestsSize = pullRequests.values.length message = ":coffee: *#{repo.owner}/#{repo.slug}* | [#{pullRequestsSize}] _pull requests_\n" if pullRequestsSize > 0 for pullRequest in pullRequests.values message += "> ##{pullRequest.id}\n" message += "> #{pullRequest.title}\n" message += "> by #{pullRequest.author.username} _#{timeago(new Date(pullRequest.created_on))}_\n" message += "> #{pullRequest.links.self.href}\n\n" else message += "> :clap: :clap: :clap: :clap: :clap: :clap: :clap: \n\n" msg.send message getRepository: (repository, cb) -> owner = repository.split('/')[0] slug = repository.split('/')[1] @client.getRepository {slug: slug, owner: owner}, (err, repo) -> cb(err, repo) module.exports = new BitBucket(credentials, all_repos)
81940
timeago = require 'timeago' credentials = username: process.env.HUBOT_BITBUCKET_AUTH_USER password: <PASSWORD>BUCKET_AUTH_<PASSWORD> all_repos = process.env.HUBOT_BITBUCKET_REPOSITORIES.split(",") class BitBucket constructor: (credentials, repos = "") -> bitBucket = require 'sand-bucket' @client = bitBucket.createClient(credentials) @repositories = repos summary: (msg, repo) -> _repositories = if repo? then [repo] else @repositories for repository in _repositories @getRepository repository, (err, repo) -> # Repository logic comes here # TODO: think some way to easily load PRs and show on screen repo.pullRequests().getAll (err, pullRequests) -> pullRequestsSize = pullRequests.values.length message = ":coffee: *#{repo.owner}/#{repo.slug}* | [#{pullRequestsSize}] _pull requests_\n" if pullRequestsSize > 0 for pullRequest in pullRequests.values message += "> ##{pullRequest.id}\n" message += "> #{pullRequest.title}\n" message += "> by #{pullRequest.author.username} _#{timeago(new Date(pullRequest.created_on))}_\n" message += "> #{pullRequest.links.self.href}\n\n" else message += "> :clap: :clap: :clap: :clap: :clap: :clap: :clap: \n\n" msg.send message getRepository: (repository, cb) -> owner = repository.split('/')[0] slug = repository.split('/')[1] @client.getRepository {slug: slug, owner: owner}, (err, repo) -> cb(err, repo) module.exports = new BitBucket(credentials, all_repos)
true
timeago = require 'timeago' credentials = username: process.env.HUBOT_BITBUCKET_AUTH_USER password: PI:PASSWORD:<PASSWORD>END_PIBUCKET_AUTH_PI:PASSWORD:<PASSWORD>END_PI all_repos = process.env.HUBOT_BITBUCKET_REPOSITORIES.split(",") class BitBucket constructor: (credentials, repos = "") -> bitBucket = require 'sand-bucket' @client = bitBucket.createClient(credentials) @repositories = repos summary: (msg, repo) -> _repositories = if repo? then [repo] else @repositories for repository in _repositories @getRepository repository, (err, repo) -> # Repository logic comes here # TODO: think some way to easily load PRs and show on screen repo.pullRequests().getAll (err, pullRequests) -> pullRequestsSize = pullRequests.values.length message = ":coffee: *#{repo.owner}/#{repo.slug}* | [#{pullRequestsSize}] _pull requests_\n" if pullRequestsSize > 0 for pullRequest in pullRequests.values message += "> ##{pullRequest.id}\n" message += "> #{pullRequest.title}\n" message += "> by #{pullRequest.author.username} _#{timeago(new Date(pullRequest.created_on))}_\n" message += "> #{pullRequest.links.self.href}\n\n" else message += "> :clap: :clap: :clap: :clap: :clap: :clap: :clap: \n\n" msg.send message getRepository: (repository, cb) -> owner = repository.split('/')[0] slug = repository.split('/')[1] @client.getRepository {slug: slug, owner: owner}, (err, repo) -> cb(err, repo) module.exports = new BitBucket(credentials, all_repos)
[ { "context": " checkbox: not 0\n file: not 0\n password: not 0\n image: not 0\n i.pseudos[n] = lt(n)\n ", "end": 91977, "score": 0.9922990202903748, "start": 91972, "tag": "PASSWORD", "value": "not 0" } ]
lib/generators/app/templates/coffeescript/assets/vendor/jquery-1.9.1.min.coffee
technicolorenvy/rendr-cli
1
#! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license # ((e, t) -> M = (e) -> t = e.length n = b.type(e) (if b.isWindow(e) then not 1 else (if 1 is e.nodeType and t then not 0 else "array" is n or "function" isnt n and (0 is t or "number" is typeof t and t > 0 and t - 1 of e))) F = (e) -> t = _[e] = {} b.each(e.match(w) or [], (e, n) -> t[n] = not 0 ) t P = (e, n, r, i) -> if b.acceptData(e) o = undefined a = undefined s = b.expando u = "string" is typeof n l = e.nodeType p = (if l then b.cache else e) f = (if l then e[s] else e[s] and s) if f and p[f] and (i or p[f].data) or not u or r isnt t f or ((if l then e[s] = f = c.pop() or b.guid++ else f = s)) p[f] or (p[f] = {} l or (p[f].toJSON = b.noop) ) ("object" is typeof n or "function" is typeof n) and ((if i then p[f] = b.extend(p[f], n) else p[f].data = b.extend(p[f].data, n))) o = p[f] i or (o.data or (o.data = {}) o = o.data ) r isnt t and (o[b.camelCase(n)] = r) (if u then (a = o[n] null is a and (a = o[b.camelCase(n)]) ) else a = o) a R = (e, t, n) -> if b.acceptData(e) r = undefined i = undefined o = undefined a = e.nodeType s = (if a then b.cache else e) u = (if a then e[b.expando] else b.expando) if s[u] if t and (o = (if n then s[u] else s[u].data)) (if b.isArray(t) then t = t.concat(b.map(t, b.camelCase)) else (if t of o then t = [t] else (t = b.camelCase(t) t = (if t of o then [t] else t.split(" ")) ))) r = 0 i = t.length while i > r delete o[t[r]] r++ return unless ((if n then $ else b.isEmptyObject))(o) (n or (delete s[u].data $(s[u]) )) and ((if a then b.cleanData([e], not 0) else (if b.support.deleteExpando or s isnt s.window then delete s[u] else s[u] = null))) W = (e, n, r) -> if r is t and 1 is e.nodeType i = "data-" + n.replace(B, "-$1").toLowerCase() if r = e.getAttribute(i) "string" is typeof r try r = (if "true" is r then not 0 else (if "false" is r then not 1 else (if "null" is r then null else (if +r + "" is r then +r else (if O.test(r) then b.parseJSON(r) else r))))) b.data e, n, r else r = t r $ = (e) -> t = undefined for t of e return not 1 if ("data" isnt t or not b.isEmptyObject(e[t])) and "toJSON" isnt t not 0 it = -> not 0 ot = -> not 1 pt = (e, t) -> loop e = e[t] break unless e and 1 isnt e.nodeType e ft = (e, t, n) -> if t = t or 0 b.isFunction(t) return b.grep(e, (e, r) -> i = !!t.call(e, r, e) i is n ) if t.nodeType return b.grep(e, (e) -> e is t is n ) if "string" is typeof t r = b.grep(e, (e) -> 1 is e.nodeType ) return b.filter(t, r, not n) if ut.test(t) t = b.filter(t, r) b.grep e, (e) -> b.inArray(e, t) >= 0 is n dt = (e) -> t = ht.split("|") n = e.createDocumentFragment() n.createElement t.pop() while t.length if n.createElement n Lt = (e, t) -> e.getElementsByTagName(t)[0] or e.appendChild(e.ownerDocument.createElement(t)) Ht = (e) -> t = e.getAttributeNode("type") e.type = (t and t.specified) + "/" + e.type e qt = (e) -> t = Et.exec(e.type) (if t then e.type = t[1] else e.removeAttribute("type")) e Mt = (e, t) -> n = undefined r = 0 while null isnt (n = e[r]) b._data n, "globalEval", not t or b._data(t[r], "globalEval") r++ _t = (e, t) -> if 1 is t.nodeType and b.hasData(e) n = undefined r = undefined i = undefined o = b._data(e) a = b._data(t, o) s = o.events if s delete a.handle a.events = {} for n of s r = 0 i = s[n].length while i > r b.event.add t, n, s[n][r] r++ a.data and (a.data = b.extend({}, a.data)) Ft = (e, t) -> n = undefined r = undefined i = undefined if 1 is t.nodeType if n = t.nodeName.toLowerCase() not b.support.noCloneEvent and t[b.expando] i = b._data(t) for r of i.events b.removeEvent t, r, i.handle t.removeAttribute b.expando (if "script" is n and t.text isnt e.text then (Ht(t).text = e.text qt(t) ) else (if "object" is n then (t.parentNode and (t.outerHTML = e.outerHTML) b.support.html5Clone and e.innerHTML and not b.trim(t.innerHTML) and (t.innerHTML = e.innerHTML) ) else (if "input" is n and Nt.test(e.type) then (t.defaultChecked = t.checked = e.checked t.value isnt e.value and (t.value = e.value) ) else (if "option" is n then t.defaultSelected = t.selected = e.defaultSelected else ("input" is n or "textarea" is n) and (t.defaultValue = e.defaultValue))))) Ot = (e, n) -> r = undefined o = undefined a = 0 s = (if typeof e.getElementsByTagName isnt i then e.getElementsByTagName(n or "*") else (if typeof e.querySelectorAll isnt i then e.querySelectorAll(n or "*") else t)) unless s s = [] r = e.childNodes or e while null isnt (o = r[a]) (if not n or b.nodeName(o, n) then s.push(o) else b.merge(s, Ot(o, n))) a++ (if n is t or n and b.nodeName(e, n) then b.merge([e], s) else s) Bt = (e) -> Nt.test(e.type) and (e.defaultChecked = e.checked) tn = (e, t) -> return t if t of e n = t.charAt(0).toUpperCase() + t.slice(1) r = t i = en.length while i-- return t if t = en[i] + n t of e r nn = (e, t) -> e = t or e "none" is b.css(e, "display") or not b.contains(e.ownerDocument, e) rn = (e, t) -> n = undefined r = undefined i = undefined o = [] a = 0 s = e.length while s > a r = e[a] r.style and (o[a] = b._data(r, "olddisplay") n = r.style.display (if t then (o[a] or "none" isnt n or (r.style.display = "") "" is r.style.display and nn(r) and (o[a] = b._data(r, "olddisplay", un(r.nodeName))) ) else o[a] or (i = nn(r) (n and "none" isnt n or not i) and b._data(r, "olddisplay", (if i then n else b.css(r, "display"))) )) ) a++ a = 0 while s > a r = e[a] r.style and (t and "none" isnt r.style.display and "" isnt r.style.display or (r.style.display = (if t then o[a] or "" else "none"))) a++ e on = (e, t, n) -> r = Vt.exec(t) (if r then Math.max(0, r[1] - (n or 0)) + (r[2] or "px") else t) an = (e, t, n, r, i) -> o = (if n is ((if r then "border" else "content")) then 4 else (if "width" is t then 1 else 0)) a = 0 while 4 > o "margin" is n and (a += b.css(e, n + Zt[o], not 0, i)) (if r then ("content" is n and (a -= b.css(e, "padding" + Zt[o], not 0, i)) "margin" isnt n and (a -= b.css(e, "border" + Zt[o] + "Width", not 0, i)) ) else (a += b.css(e, "padding" + Zt[o], not 0, i) "padding" isnt n and (a += b.css(e, "border" + Zt[o] + "Width", not 0, i)) )) o += 2 a sn = (e, t, n) -> r = not 0 i = (if "width" is t then e.offsetWidth else e.offsetHeight) o = Rt(e) a = b.support.boxSizing and "border-box" is b.css(e, "boxSizing", not 1, o) if 0 >= i or null is i return i if i = Wt(e, t, o) (0 > i or null is i) and (i = e.style[t]) Yt.test(i) r = a and (b.support.boxSizingReliable or i is e.style[t]) i = parseFloat(i) or 0 i + an(e, t, n or ((if a then "border" else "content")), r, o) + "px" un = (e) -> t = o n = Gt[e] n or (n = ln(e, t) "none" isnt n and n or (Pt = (Pt or b("<iframe frameborder='0' width='0' height='0'/>").css("cssText", "display:block !important")).appendTo(t.documentElement) t = (Pt[0].contentWindow or Pt[0].contentDocument).document t.write("<!doctype html><html><body>") t.close() n = ln(e, t) Pt.detach() ) Gt[e] = n ) n ln = (e, t) -> n = b(t.createElement(e)).appendTo(t.body) r = b.css(n[0], "display") n.remove() r gn = (e, t, n, r) -> i = undefined if b.isArray(t) b.each t, (t, i) -> (if n or pn.test(e) then r(e, i) else gn(e + "[" + ((if "object" is typeof i then t else "")) + "]", i, n, r)) else if n or "object" isnt b.type(t) r e, t else for i of t gn e + "[" + i + "]", t[i], n, r Hn = (e) -> (t, n) -> "string" isnt typeof t and (n = t t = "*" ) r = undefined i = 0 o = t.toLowerCase().match(w) or [] if b.isFunction(n) while r = o[i++] (if "+" is r[0] then (r = r.slice(1) or "*" (e[r] = e[r] or []).unshift(n) ) else (e[r] = e[r] or []).push(n)) qn = (e, n, r, i) -> s = (u) -> l = undefined o[u] = not 0 b.each(e[u] or [], (e, u) -> c = u(n, r, i) (if "string" isnt typeof c or a or o[c] then (if a then not (l = c) else t) else (n.dataTypes.unshift(c) s(c) not 1 )) ) l o = {} a = e is jn s(n.dataTypes[0]) or not o["*"] and s("*") Mn = (e, n) -> r = undefined i = undefined o = b.ajaxSettings.flatOptions or {} for i of n n[i] isnt t and (((if o[i] then e else r or (r = {})))[i] = n[i]) r and b.extend(not 0, e, r) e _n = (e, n, r) -> i = undefined o = undefined a = undefined s = undefined u = e.contents l = e.dataTypes c = e.responseFields for s of c s of r and (n[c[s]] = r[s]) while "*" is l[0] l.shift() o is t and (o = e.mimeType or n.getResponseHeader("Content-Type")) if o for s of u if u[s] and u[s].test(o) l.unshift s break unless l[0] of r for s of r if not l[0] or e.converters[s + " " + l[0]] a = s break i or (i = s) a = a or i (if a then (a isnt l[0] and l.unshift(a) r[a] ) else t) Fn = (e, t) -> n = undefined r = undefined i = undefined o = undefined a = {} s = 0 u = e.dataTypes.slice() l = u[0] if e.dataFilter and (t = e.dataFilter(t, e.dataType)) u[1] for i of e.converters a[i.toLowerCase()] = e.converters[i] while r = u[++s] if "*" isnt r if "*" isnt l and l isnt r if i = a[l + " " + r] or a["* " + r] not i for n of a if o = n.split(" ") o[1] is r and (i = a[l + " " + o[0]] or a["* " + o[0]]) (if i is not 0 then i = a[n] else a[n] isnt not 0 and (r = o[0] u.splice(s--, 0, r) )) break if i isnt not 0 if i and e["throws"] t = i(t) else try t = i(t) catch c return ( state: "parsererror" error: (if i then c else "No conversion from " + l + " to " + r) ) l = r state: "success" data: t In = -> try return new e.XMLHttpRequest zn = -> try return new e.ActiveXObject("Microsoft.XMLHTTP") Kn = -> setTimeout(-> Xn = t ) Xn = b.now() Zn = (e, t) -> b.each t, (t, n) -> r = (Qn[t] or []).concat(Qn["*"]) i = 0 o = r.length while o > i return if r[i].call(e, t, n) i++ er = (e, t, n) -> r = undefined i = undefined o = 0 a = Gn.length s = b.Deferred().always(-> delete u.elem ) u = -> return not 1 if i t = Xn or Kn() n = Math.max(0, l.startTime + l.duration - t) r = n / l.duration or 0 o = 1 - r a = 0 u = l.tweens.length while u > a l.tweens[a].run o a++ s.notifyWith(e, [l, o, n]) (if 1 > o and u then n else (s.resolveWith(e, [l]) not 1 )) l = s.promise( elem: e props: b.extend({}, t) opts: b.extend(not 0, specialEasing: {} , n) originalProperties: t originalOptions: n startTime: Xn or Kn() duration: n.duration tweens: [] createTween: (t, n) -> r = b.Tween(e, l.opts, t, n, l.opts.specialEasing[t] or l.opts.easing) l.tweens.push(r) r stop: (t) -> n = 0 r = (if t then l.tweens.length else 0) return this if i i = not 0 while r > n l.tweens[n].run 1 n++ (if t then s.resolveWith(e, [l, t]) else s.rejectWith(e, [l, t])) this ) c = l.props tr(c, l.opts.specialEasing) while a > o return r if r = Gn[o].call(l, e, c, l.opts) o++ Zn(l, c) b.isFunction(l.opts.start) and l.opts.start.call(e, l) b.fx.timer(b.extend(u, elem: e anim: l queue: l.opts.queue )) l.progress(l.opts.progress).done(l.opts.done, l.opts.complete).fail(l.opts.fail).always(l.opts.always) tr = (e, t) -> n = undefined r = undefined i = undefined o = undefined a = undefined for i of e if r = b.camelCase(i) o = t[r] n = e[i] b.isArray(n) and (o = n[1] n = e[i] = n[0] ) i isnt r and (e[r] = n delete e[i] ) a = b.cssHooks[r] a and "expand" of a n = a.expand(n) delete e[r] for i of n i of e or (e[i] = n[i] t[i] = o ) else t[r] = o nr = (e, t, n) -> r = undefined i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = undefined f = this d = e.style h = {} g = [] m = e.nodeType and nn(e) n.queue or (c = b._queueHooks(e, "fx") null is c.unqueued and (c.unqueued = 0 p = c.empty.fire c.empty.fire = -> c.unqueued or p() ) c.unqueued++ f.always(-> f.always -> c.unqueued-- b.queue(e, "fx").length or c.empty.fire() ) ) 1 is e.nodeType and ("height" of t or "width" of t) and (n.overflow = [d.overflow, d.overflowX, d.overflowY] "inline" is b.css(e, "display") and "none" is b.css(e, "float") and ((if b.support.inlineBlockNeedsLayout and "inline" isnt un(e.nodeName) then d.zoom = 1 else d.display = "inline-block")) ) n.overflow and (d.overflow = "hidden" b.support.shrinkWrapBlocks or f.always(-> d.overflow = n.overflow[0] d.overflowX = n.overflow[1] d.overflowY = n.overflow[2] ) ) for i of t if a = t[i] Vn.exec(a) continue if delete t[i] u = u or "toggle" is a a is ((if m then "hide" else "show")) g.push i if o = g.length s = b._data(e, "fxshow") or b._data(e, "fxshow", {}) "hidden" of s and (m = s.hidden) u and (s.hidden = not m) (if m then b(e).show() else f.done(-> b(e).hide() )) f.done(-> t = undefined b._removeData e, "fxshow" for t of h b.style e, t, h[t] ) i = 0 while o > i r = g[i] l = f.createTween(r, (if m then s[r] else 0)) h[r] = s[r] or b.style(e, r) r of s or (s[r] = l.start m and (l.end = l.start l.start = (if "width" is r or "height" is r then 1 else 0) ) ) i++ rr = (e, t, n, r, i) -> new rr::init(e, t, n, r, i) ir = (e, t) -> n = undefined r = height: e i = 0 t = (if t then 1 else 0) while 4 > i n = Zt[i] r["margin" + n] = r["padding" + n] = e i += 2 - t t and (r.opacity = r.width = e) r or = (e) -> (if b.isWindow(e) then e else (if 9 is e.nodeType then e.defaultView or e.parentWindow else not 1)) n = undefined r = undefined i = typeof t o = e.document a = e.location s = e.jQuery u = e.$ l = {} c = [] p = "1.9.1" f = c.concat d = c.push h = c.slice g = c.indexOf m = l.toString y = l.hasOwnProperty v = p.trim b = (e, t) -> new b.fn.init(e, t, r) x = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source w = /\S+/g T = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g N = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/ C = /^<(\w+)\s*\/?>(?:<\/\1>|)$/ k = /^[\],:{}\s]*$/ E = /(?:^|:|,)(?:\s*\[)+/g S = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g A = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g j = /^-ms-/ D = /-([\da-z])/g L = (e, t) -> t.toUpperCase() H = (e) -> (o.addEventListener or "load" is e.type or "complete" is o.readyState) and (q() b.ready() ) q = -> (if o.addEventListener then (o.removeEventListener("DOMContentLoaded", H, not 1) e.removeEventListener("load", H, not 1) ) else (o.detachEvent("onreadystatechange", H) e.detachEvent("onload", H) )) b.fn = b:: = jquery: p constructor: b init: (e, n, r) -> i = undefined a = undefined return this unless e if "string" is typeof e return (if not n or n.jquery then (n or r).find(e) else @constructor(n).find(e)) if i = (if "<" is e.charAt(0) and ">" is e.charAt(e.length - 1) and e.length >= 3 then [null, e, null] else N.exec(e)) not i or not i[1] and n if i[1] if n = (if n instanceof b then n[0] else n) b.merge(this, b.parseHTML(i[1], (if n and n.nodeType then n.ownerDocument or n else o), not 0)) C.test(i[1]) and b.isPlainObject(n) for i of n (if b.isFunction(this[i]) then this[i](n[i]) else @attr(i, n[i])) return this if a = o.getElementById(i[2]) a and a.parentNode return r.find(e) if a.id isnt i[2] @length = 1 this[0] = a return @context = o @selector = e this (if e.nodeType then (@context = this[0] = e @length = 1 this ) else (if b.isFunction(e) then r.ready(e) else (e.selector isnt t and (@selector = e.selector @context = e.context ) b.makeArray(e, this) ))) selector: "" length: 0 size: -> @length toArray: -> h.call this get: (e) -> (if null is e then @toArray() else (if 0 > e then this[@length + e] else this[e])) pushStack: (e) -> t = b.merge(@constructor(), e) t.prevObject = this t.context = @context t each: (e, t) -> b.each this, e, t ready: (e) -> b.ready.promise().done(e) this slice: -> @pushStack h.apply(this, arguments_) first: -> @eq 0 last: -> @eq -1 eq: (e) -> t = @length n = +e + ((if 0 > e then t else 0)) @pushStack (if n >= 0 and t > n then [this[n]] else []) map: (e) -> @pushStack b.map(this, (t, n) -> e.call t, n, t ) end: -> @prevObject or @constructor(null) push: d sort: [].sort splice: [].splice b.fn.init:: = b.fn b.extend = b.fn.extend = -> e = undefined n = undefined r = undefined i = undefined o = undefined a = undefined s = arguments_[0] or {} u = 1 l = arguments_.length c = not 1 "boolean" is typeof s and (c = s s = arguments_[1] or {} u = 2 ) "object" is typeof s or b.isFunction(s) or (s = {}) l is u and (s = this --u ) while l > u unless null is (o = arguments_[u]) for i of o e = s[i] r = o[i] s isnt r and ((if c and r and (b.isPlainObject(r) or (n = b.isArray(r))) then ((if n then (n = not 1 a = (if e and b.isArray(e) then e else []) ) else a = (if e and b.isPlainObject(e) then e else {})) s[i] = b.extend(c, a, r) ) else r isnt t and (s[i] = r))) u++ s b.extend( noConflict: (t) -> e.$ is b and (e.$ = u) t and e.jQuery is b and (e.jQuery = s) b isReady: not 1 readyWait: 1 holdReady: (e) -> (if e then b.readyWait++ else b.ready(not 0)) ready: (e) -> if (if e is not 0 then not --b.readyWait else not b.isReady) return setTimeout(b.ready) unless o.body b.isReady = not 0 e isnt not 0 and --b.readyWait > 0 or (n.resolveWith(o, [b]) b.fn.trigger and b(o).trigger("ready").off("ready") ) isFunction: (e) -> "function" is b.type(e) isArray: Array.isArray or (e) -> "array" is b.type(e) isWindow: (e) -> null isnt e and e is e.window isNumeric: (e) -> not isNaN(parseFloat(e)) and isFinite(e) type: (e) -> (if null is e then e + "" else (if "object" is typeof e or "function" is typeof e then l[m.call(e)] or "object" else typeof e)) isPlainObject: (e) -> return not 1 if not e or "object" isnt b.type(e) or e.nodeType or b.isWindow(e) try return not 1 if e.constructor and not y.call(e, "constructor") and not y.call(e.constructor::, "isPrototypeOf") catch n return not 1 r = undefined for r of e r is t or y.call(e, r) isEmptyObject: (e) -> t = undefined for t of e return not 1 not 0 error: (e) -> throw Error(e) parseHTML: (e, t, n) -> return null if not e or "string" isnt typeof e "boolean" is typeof t and (n = t t = not 1 ) t = t or o r = C.exec(e) i = not n and [] (if r then [t.createElement(r[1])] else (r = b.buildFragment([e], t, i) i and b(i).remove() b.merge([], r.childNodes) )) parseJSON: (n) -> (if e.JSON and e.JSON.parse then e.JSON.parse(n) else (if null is n then n else (if "string" is typeof n and (n = b.trim(n) n and k.test(n.replace(S, "@").replace(A, "]").replace(E, "")) ) then Function("return " + n)() else (b.error("Invalid JSON: " + n) t )))) parseXML: (n) -> r = undefined i = undefined return null if not n or "string" isnt typeof n try (if e.DOMParser then (i = new DOMParser r = i.parseFromString(n, "text/xml") ) else (r = new ActiveXObject("Microsoft.XMLDOM") r.async = "false" r.loadXML(n) )) catch o r = t r and r.documentElement and not r.getElementsByTagName("parsererror").length or b.error("Invalid XML: " + n) r noop: -> globalEval: (t) -> t and b.trim(t) and (e.execScript or (t) -> e.eval.call e, t )(t) camelCase: (e) -> e.replace(j, "ms-").replace D, L nodeName: (e, t) -> e.nodeName and e.nodeName.toLowerCase() is t.toLowerCase() each: (e, t, n) -> r = undefined i = 0 o = e.length a = M(e) if n if a while o > i break if r = t.apply(e[i], n) r is not 1 i++ else for i of e break if r = t.apply(e[i], n) r is not 1 else if a while o > i break if r = t.call(e[i], i, e[i]) r is not 1 i++ else for i of e break if r = t.call(e[i], i, e[i]) r is not 1 e trim: (if v and not v.call(" ") then (e) -> (if null is e then "" else v.call(e)) else (e) -> (if null is e then "" else (e + "").replace(T, "")) ) makeArray: (e, t) -> n = t or [] null isnt e and ((if M(Object(e)) then b.merge(n, (if "string" is typeof e then [e] else e)) else d.call(n, e))) n inArray: (e, t, n) -> r = undefined if t return g.call(t, e, n) if g r = t.length n = (if n then (if 0 > n then Math.max(0, r + n) else n) else 0) while r > n return n if n of t and t[n] is e n++ -1 merge: (e, n) -> r = n.length i = e.length o = 0 if "number" is typeof r while r > o e[i++] = n[o] o++ else e[i++] = n[o++] while n[o] isnt t e.length = i e grep: (e, t, n) -> r = undefined i = [] o = 0 a = e.length n = !!n while a > o r = !!t(e[o], o) n isnt r and i.push(e[o]) o++ i map: (e, t, n) -> r = undefined i = 0 o = e.length a = M(e) s = [] if a while o > i r = t(e[i], i, n) null isnt r and (s[s.length] = r) i++ else for i of e r = t(e[i], i, n) null isnt r and (s[s.length] = r) f.apply [], s guid: 1 proxy: (e, n) -> r = undefined i = undefined o = undefined "string" is typeof n and (o = e[n] n = e e = o ) (if b.isFunction(e) then (r = h.call(arguments_, 2) i = -> e.apply n or this, r.concat(h.call(arguments_)) i.guid = e.guid = e.guid or b.guid++ i ) else t) access: (e, n, r, i, o, a, s) -> u = 0 l = e.length c = null is r if "object" is b.type(r) o = not 0 for u of r b.access e, n, u, r[u], not 0, a, s else if i isnt t and (o = not 0 b.isFunction(i) or (s = not 0) c and ((if s then (n.call(e, i) n = null ) else (c = n n = (e, t, n) -> c.call b(e), n ))) n ) while l > u n e[u], r, (if s then i else i.call(e[u], u, n(e[u], r))) u++ (if o then e else (if c then n.call(e) else (if l then n(e[0], r) else a))) now: -> (new Date).getTime() ) b.ready.promise = (t) -> unless n if n = b.Deferred() "complete" is o.readyState setTimeout b.ready else unless o.addEventListener o.attachEvent("onreadystatechange", H) e.attachEvent("onload", H) r = not 1 try r = null is e.frameElement and o.documentElement r and r.doScroll and a = -> unless b.isReady try r.doScroll "left" catch e return setTimeout(a, 50) q() b.ready() () n.promise t b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), (e, t) -> l["[object " + t + "]"] = t.toLowerCase() ) r = b(o) _ = {} b.Callbacks = (e) -> e = (if "string" is typeof e then _[e] or F(e) else b.extend({}, e)) n = undefined r = undefined i = undefined o = undefined a = undefined s = undefined u = [] l = not e.once and [] c = (t) -> r = e.memory and t i = not 0 a = s or 0 s = 0 o = u.length n = not 0 while u and o > a if u[a].apply(t[0], t[1]) is not 1 and e.stopOnFalse r = not 1 break a++ n = not 1 u and ((if l then l.length and c(l.shift()) else (if r then u = [] else p.disable()))) p = add: -> if u t = u.length (i = (t) -> b.each t, (t, n) -> r = b.type(n) (if "function" is r then e.unique and p.has(n) or u.push(n) else n and n.length and "string" isnt r and i(n)) )(arguments_) (if n then o = u.length else r and (s = t c(r) )) this remove: -> u and b.each(arguments_, (e, t) -> r = undefined while (r = b.inArray(t, u, r)) > -1 u.splice(r, 1) n and (o >= r and o-- a >= r and a-- ) ) this has: (e) -> (if e then b.inArray(e, u) > -1 else not (not u or not u.length)) empty: -> u = [] this disable: -> u = l = r = t this disabled: -> not u lock: -> l = t r or p.disable() this locked: -> not l fireWith: (e, t) -> t = t or [] t = [e, (if t.slice then t.slice() else t)] not u or i and not l or ((if n then l.push(t) else c(t))) this fire: -> p.fireWith(this, arguments_) this fired: -> !!i p b.extend( Deferred: (e) -> t = [["resolve", "done", b.Callbacks("once memory"), "resolved"], ["reject", "fail", b.Callbacks("once memory"), "rejected"], ["notify", "progress", b.Callbacks("memory")]] n = "pending" r = state: -> n always: -> i.done(arguments_).fail(arguments_) this then: -> e = arguments_ b.Deferred((n) -> b.each(t, (t, o) -> a = o[0] s = b.isFunction(e[t]) and e[t] i[o[1]] -> e = s and s.apply(this, arguments_) (if e and b.isFunction(e.promise) then e.promise().done(n.resolve).fail(n.reject).progress(n.notify) else n[a + "With"]((if this is r then n.promise() else this), (if s then [e] else arguments_))) ) e = null ).promise() promise: (e) -> (if null isnt e then b.extend(e, r) else r) i = {} r.pipe = r.then b.each(t, (e, o) -> a = o[2] s = o[3] r[o[1]] = a.add s and a.add(-> n = s , t[1 ^ e][2].disable, t[2][2].lock) i[o[0]] = -> i[o[0] + "With"]((if this is i then r else this), arguments_) this i[o[0] + "With"] = a.fireWith ) r.promise(i) e and e.call(i, i) i when: (e) -> t = 0 n = h.call(arguments_) r = n.length i = (if 1 isnt r or e and b.isFunction(e.promise) then r else 0) o = (if 1 is i then e else b.Deferred()) a = (e, t, n) -> (r) -> t[e] = this n[e] = (if arguments_.length > 1 then h.call(arguments_) else r) (if n is s then o.notifyWith(t, n) else --i or o.resolveWith(t, n)) s = undefined u = undefined l = undefined if r > 1 s = Array(r) u = Array(r) l = Array(r) while r > t (if n[t] and b.isFunction(n[t].promise) then n[t].promise().done(a(t, l, n)).fail(o.reject).progress(a(t, u, s)) else --i) t++ i or o.resolveWith(l, n) o.promise() ) b.support = -> t = undefined n = undefined r = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = undefined f = undefined d = o.createElement("div") return {} if d.setAttribute("className", "t") d.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>" n = d.getElementsByTagName("*") r = d.getElementsByTagName("a")[0] not n or not r or not n.length s = o.createElement("select") l = s.appendChild(o.createElement("option")) a = d.getElementsByTagName("input")[0] r.style.cssText = "top:1px;float:left;opacity:.5" t = getSetAttribute: "t" isnt d.className leadingWhitespace: 3 is d.firstChild.nodeType tbody: not d.getElementsByTagName("tbody").length htmlSerialize: !!d.getElementsByTagName("link").length style: /top/.test(r.getAttribute("style")) hrefNormalized: "/a" is r.getAttribute("href") opacity: /^0.5/.test(r.style.opacity) cssFloat: !!r.style.cssFloat checkOn: !!a.value optSelected: l.selected enctype: !!o.createElement("form").enctype html5Clone: "<:nav></:nav>" isnt o.createElement("nav").cloneNode(not 0).outerHTML boxModel: "CSS1Compat" is o.compatMode deleteExpando: not 0 noCloneEvent: not 0 inlineBlockNeedsLayout: not 1 shrinkWrapBlocks: not 1 reliableMarginRight: not 0 boxSizingReliable: not 0 pixelPosition: not 1 a.checked = not 0 t.noCloneChecked = a.cloneNode(not 0).checked s.disabled = not 0 t.optDisabled = not l.disabled try delete d.test catch h t.deleteExpando = not 1 a = o.createElement("input") a.setAttribute("value", "") t.input = "" is a.getAttribute("value") a.value = "t" a.setAttribute("type", "radio") t.radioValue = "t" is a.value a.setAttribute("checked", "t") a.setAttribute("name", "t") u = o.createDocumentFragment() u.appendChild(a) t.appendChecked = a.checked t.checkClone = u.cloneNode(not 0).cloneNode(not 0).lastChild.checked d.attachEvent and (d.attachEvent("onclick", -> t.noCloneEvent = not 1 ) d.cloneNode(not 0).click() ) for f of submit: not 0 change: not 0 focusin: not 0 d.setAttribute(c = "on" + f, "t") t[f + "Bubbles"] = c of e or d.attributes[c].expando is not 1 d.style.backgroundClip = "content-box" d.cloneNode(not 0).style.backgroundClip = "" t.clearCloneStyle = "content-box" is d.style.backgroundClip b(-> n = undefined r = undefined a = undefined s = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;" u = o.getElementsByTagName("body")[0] u and (n = o.createElement("div") n.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px" u.appendChild(n).appendChild(d) d.innerHTML = "<table><tr><td></td><td>t</td></tr></table>" a = d.getElementsByTagName("td") a[0].style.cssText = "padding:0;margin:0;border:0;display:none" p = 0 is a[0].offsetHeight a[0].style.display = "" a[1].style.display = "none" t.reliableHiddenOffsets = p and 0 is a[0].offsetHeight d.innerHTML = "" d.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;" t.boxSizing = 4 is d.offsetWidth t.doesNotIncludeMarginInBodyOffset = 1 isnt u.offsetTop e.getComputedStyle and (t.pixelPosition = "1%" isnt (e.getComputedStyle(d, null) or {}).top t.boxSizingReliable = "4px" is (e.getComputedStyle(d, null) or width: "4px").width r = d.appendChild(o.createElement("div")) r.style.cssText = d.style.cssText = s r.style.marginRight = r.style.width = "0" d.style.width = "1px" t.reliableMarginRight = not parseFloat((e.getComputedStyle(r, null) or {}).marginRight) ) typeof d.style.zoom isnt i and (d.innerHTML = "" d.style.cssText = s + "width:1px;padding:1px;display:inline;zoom:1" t.inlineBlockNeedsLayout = 3 is d.offsetWidth d.style.display = "block" d.innerHTML = "<div></div>" d.firstChild.style.width = "5px" t.shrinkWrapBlocks = 3 isnt d.offsetWidth t.inlineBlockNeedsLayout and (u.style.zoom = 1) ) u.removeChild(n) n = d = a = r = null ) ) n = s = u = l = r = a = null t () O = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/ B = /([A-Z])/g b.extend( cache: {} expando: "jQuery" + (p + Math.random()).replace(/\D/g, "") noData: embed: not 0 object: "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" applet: not 0 hasData: (e) -> e = (if e.nodeType then b.cache[e[b.expando]] else e[b.expando]) !!e and not $(e) data: (e, t, n) -> P e, t, n removeData: (e, t) -> R e, t _data: (e, t, n) -> P e, t, n, not 0 _removeData: (e, t) -> R e, t, not 0 acceptData: (e) -> return not 1 if e.nodeType and 1 isnt e.nodeType and 9 isnt e.nodeType t = e.nodeName and b.noData[e.nodeName.toLowerCase()] not t or t isnt not 0 and e.getAttribute("classid") is t ) b.fn.extend( data: (e, n) -> r = undefined i = undefined o = this[0] a = 0 s = null if e is t if @length and (s = b.data(o) 1 is o.nodeType and not b._data(o, "parsedAttrs") ) r = o.attributes while r.length > a i = r[a].name i.indexOf("data-") or (i = b.camelCase(i.slice(5)) W(o, i, s[i]) ) a++ b._data o, "parsedAttrs", not 0 return s (if "object" is typeof e then @each(-> b.data this, e ) else b.access(this, (n) -> (if n is t then (if o then W(o, e, b.data(o, e)) else null) else (@each(-> b.data this, e, n ) t )) , null, n, arguments_.length > 1, null, not 0)) removeData: (e) -> @each -> b.removeData this, e ) b.extend( queue: (e, n, r) -> i = undefined (if e then (n = (n or "fx") + "queue" i = b._data(e, n) r and ((if not i or b.isArray(r) then i = b._data(e, n, b.makeArray(r)) else i.push(r))) i or [] ) else t) dequeue: (e, t) -> t = t or "fx" n = b.queue(e, t) r = n.length i = n.shift() o = b._queueHooks(e, t) a = -> b.dequeue e, t "inprogress" is i and (i = n.shift() r-- ) o.cur = i i and ("fx" is t and n.unshift("inprogress") delete o.stop i.call(e, a, o) ) not r and o and o.empty.fire() _queueHooks: (e, t) -> n = t + "queueHooks" b._data(e, n) or b._data(e, n, empty: b.Callbacks("once memory").add(-> b._removeData(e, t + "queue") b._removeData(e, n) ) ) ) b.fn.extend( queue: (e, n) -> r = 2 "string" isnt typeof e and (n = e e = "fx" r-- ) (if r > arguments_.length then b.queue(this[0], e) else (if n is t then this else @each(-> t = b.queue(this, e, n) b._queueHooks(this, e) "fx" is e and "inprogress" isnt t[0] and b.dequeue(this, e) ))) dequeue: (e) -> @each -> b.dequeue this, e delay: (e, t) -> e = (if b.fx then b.fx.speeds[e] or e else e) t = t or "fx" @queue(t, (t, n) -> r = setTimeout(t, e) n.stop = -> clearTimeout r ) clearQueue: (e) -> @queue e or "fx", [] promise: (e, n) -> r = undefined i = 1 o = b.Deferred() a = this s = @length u = -> --i or o.resolveWith(a, [a]) "string" isnt typeof e and (n = e e = t ) e = e or "fx" while s-- r = b._data(a[s], e + "queueHooks") r and r.empty and (i++ r.empty.add(u) ) u() o.promise(n) ) I = undefined z = undefined X = /[\t\r\n]/g U = /\r/g V = /^(?:input|select|textarea|button|object)$/i Y = /^(?:a|area)$/i J = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i G = /^(?:checked|selected)$/i Q = b.support.getSetAttribute K = b.support.input b.fn.extend( attr: (e, t) -> b.access this, b.attr, e, t, arguments_.length > 1 removeAttr: (e) -> @each -> b.removeAttr this, e prop: (e, t) -> b.access this, b.prop, e, t, arguments_.length > 1 removeProp: (e) -> e = b.propFix[e] or e @each(-> try this[e] = t delete this[e] ) addClass: (e) -> t = undefined n = undefined r = undefined i = undefined o = undefined a = 0 s = @length u = "string" is typeof e and e if b.isFunction(e) return @each((t) -> b(this).addClass e.call(this, t, @className) ) if u t = (e or "").match(w) or [] while s > a if n = this[a] r = 1 is n.nodeType and ((if n.className then (" " + n.className + " ").replace(X, " ") else " ")) o = 0 0 > r.indexOf(" " + i + " ") and (r += i + " ") while i = t[o++] n.className = b.trim(r) a++ this removeClass: (e) -> t = undefined n = undefined r = undefined i = undefined o = undefined a = 0 s = @length u = 0 is arguments_.length or "string" is typeof e and e if b.isFunction(e) return @each((t) -> b(this).removeClass e.call(this, t, @className) ) if u t = (e or "").match(w) or [] while s > a if n = this[a] r = 1 is n.nodeType and ((if n.className then (" " + n.className + " ").replace(X, " ") else "")) o = 0 r = r.replace(" " + i + " ", " ") while r.indexOf(" " + i + " ") >= 0 while i = t[o++] n.className = (if e then b.trim(r) else "") a++ this toggleClass: (e, t) -> n = typeof e r = "boolean" is typeof t (if b.isFunction(e) then @each((n) -> b(this).toggleClass e.call(this, n, @className, t), t ) else @each(-> if "string" is n o = undefined a = 0 s = b(this) u = t l = e.match(w) or [] while o = l[a++] u = (if r then u else not s.hasClass(o)) s[(if u then "addClass" else "removeClass")](o) else (n is i or "boolean" is n) and (@className and b._data(this, "__className__", @className) @className = (if @className or e is not 1 then "" else b._data(this, "__className__") or "") ) )) hasClass: (e) -> t = " " + e + " " n = 0 r = @length while r > n return not 0 if 1 is this[n].nodeType and (" " + this[n].className + " ").replace(X, " ").indexOf(t) >= 0 n++ not 1 val: (e) -> n = undefined r = undefined i = undefined o = this[0] if arguments_.length return i = b.isFunction(e) @each((n) -> o = undefined a = b(this) 1 is @nodeType and (o = (if i then e.call(this, n, a.val()) else e) (if null is o then o = "" else (if "number" is typeof o then o += "" else b.isArray(o) and (o = b.map(o, (e) -> (if null is e then "" else e + "") )))) r = b.valHooks[@type] or b.valHooks[@nodeName.toLowerCase()] r and "set" of r and r.set(this, o, "value") isnt t or (@value = o) ) ) if o r = b.valHooks[o.type] or b.valHooks[o.nodeName.toLowerCase()] (if r and "get" of r and (n = r.get(o, "value")) isnt t then n else (n = o.value (if "string" is typeof n then n.replace(U, "") else (if null is n then "" else n)) )) ) b.extend( valHooks: option: get: (e) -> t = e.attributes.value (if not t or t.specified then e.value else e.text) select: get: (e) -> t = undefined n = undefined r = e.options i = e.selectedIndex o = "select-one" is e.type or 0 > i a = (if o then null else []) s = (if o then i + 1 else r.length) u = (if 0 > i then s else (if o then i else 0)) while s > u if n = r[u] not (not n.selected and u isnt i or ((if b.support.optDisabled then n.disabled else null isnt n.getAttribute("disabled"))) or n.parentNode.disabled and b.nodeName(n.parentNode, "optgroup")) return t if t = b(n).val() o a.push t u++ a set: (e, t) -> n = b.makeArray(t) b(e).find("option").each(-> @selected = b.inArray(b(this).val(), n) >= 0 ) n.length or (e.selectedIndex = -1) n attr: (e, n, r) -> o = undefined a = undefined s = undefined u = e.nodeType if e and 3 isnt u and 8 isnt u and 2 isnt u (if typeof e.getAttribute is i then b.prop(e, n, r) else (a = 1 isnt u or not b.isXMLDoc(e) a and (n = n.toLowerCase() o = b.attrHooks[n] or ((if J.test(n) then z else I)) ) (if r is t then (if o and a and "get" of o and null isnt (s = o.get(e, n)) then s else (typeof e.getAttribute isnt i and (s = e.getAttribute(n)) (if null is s then t else s) )) else (if null isnt r then (if o and a and "set" of o and (s = o.set(e, r, n)) isnt t then s else (e.setAttribute(n, r + "") r )) else (b.removeAttr(e, n) t ))) )) removeAttr: (e, t) -> n = undefined r = undefined i = 0 o = t and t.match(w) if o and 1 is e.nodeType while n = o[i++] r = b.propFix[n] or n (if J.test(n) then (if not Q and G.test(n) then e[b.camelCase("default-" + n)] = e[r] = not 1 else e[r] = not 1) else b.attr(e, n, "")) e.removeAttribute((if Q then n else r)) attrHooks: type: set: (e, t) -> if not b.support.radioValue and "radio" is t and b.nodeName(e, "input") n = e.value e.setAttribute("type", t) n and (e.value = n) t propFix: tabindex: "tabIndex" readonly: "readOnly" for: "htmlFor" class: "className" maxlength: "maxLength" cellspacing: "cellSpacing" cellpadding: "cellPadding" rowspan: "rowSpan" colspan: "colSpan" usemap: "useMap" frameborder: "frameBorder" contenteditable: "contentEditable" prop: (e, n, r) -> i = undefined o = undefined a = undefined s = e.nodeType if e and 3 isnt s and 8 isnt s and 2 isnt s a = 1 isnt s or not b.isXMLDoc(e) a and (n = b.propFix[n] or n o = b.propHooks[n] ) (if r isnt t then (if o and "set" of o and (i = o.set(e, r, n)) isnt t then i else e[n] = r) else (if o and "get" of o and null isnt (i = o.get(e, n)) then i else e[n])) propHooks: tabIndex: get: (e) -> n = e.getAttributeNode("tabindex") (if n and n.specified then parseInt(n.value, 10) else (if V.test(e.nodeName) or Y.test(e.nodeName) and e.href then 0 else t)) ) z = get: (e, n) -> r = b.prop(e, n) i = "boolean" is typeof r and e.getAttribute(n) o = (if "boolean" is typeof r then (if K and Q then null isnt i else (if G.test(n) then e[b.camelCase("default-" + n)] else !!i)) else e.getAttributeNode(n)) (if o and o.value isnt not 1 then n.toLowerCase() else t) set: (e, t, n) -> (if t is not 1 then b.removeAttr(e, n) else (if K and Q or not G.test(n) then e.setAttribute(not Q and b.propFix[n] or n, n) else e[b.camelCase("default-" + n)] = e[n] = not 0)) n K and Q or (b.attrHooks.value = get: (e, n) -> r = e.getAttributeNode(n) (if b.nodeName(e, "input") then e.defaultValue else (if r and r.specified then r.value else t)) set: (e, n, r) -> (if b.nodeName(e, "input") then (e.defaultValue = n t ) else I and I.set(e, n, r)) ) Q or (I = b.valHooks.button = get: (e, n) -> r = e.getAttributeNode(n) (if r and ((if "id" is n or "name" is n or "coords" is n then "" isnt r.value else r.specified)) then r.value else t) set: (e, n, r) -> i = e.getAttributeNode(r) i or e.setAttributeNode(i = e.ownerDocument.createAttribute(r)) i.value = n += "" (if "value" is r or n is e.getAttribute(r) then n else t) b.attrHooks.contenteditable = get: I.get set: (e, t, n) -> I.set e, (if "" is t then not 1 else t), n b.each(["width", "height"], (e, n) -> b.attrHooks[n] = b.extend(b.attrHooks[n], set: (e, r) -> (if "" is r then (e.setAttribute(n, "auto") r ) else t) ) ) ) b.support.hrefNormalized or (b.each(["href", "src", "width", "height"], (e, n) -> b.attrHooks[n] = b.extend(b.attrHooks[n], get: (e) -> r = e.getAttribute(n, 2) (if null is r then t else r) ) ) b.each(["href", "src"], (e, t) -> b.propHooks[t] = get: (e) -> e.getAttribute t, 4 ) ) b.support.style or (b.attrHooks.style = get: (e) -> e.style.cssText or t set: (e, t) -> e.style.cssText = t + "" ) b.support.optSelected or (b.propHooks.selected = b.extend(b.propHooks.selected, get: (e) -> t = e.parentNode t and (t.selectedIndex t.parentNode and t.parentNode.selectedIndex ) null )) b.support.enctype or (b.propFix.enctype = "encoding") b.support.checkOn or b.each(["radio", "checkbox"], -> b.valHooks[this] = get: (e) -> (if null is e.getAttribute("value") then "on" else e.value) ) b.each(["radio", "checkbox"], -> b.valHooks[this] = b.extend(b.valHooks[this], set: (e, n) -> (if b.isArray(n) then e.checked = b.inArray(b(e).val(), n) >= 0 else t) ) ) Z = /^(?:input|select|textarea)$/i et = /^key/ tt = /^(?:mouse|contextmenu)|click/ nt = /^(?:focusinfocus|focusoutblur)$/ rt = /^([^.]*)(?:\.(.+)|)$/ b.event = global: {} add: (e, n, r, o, a) -> s = undefined u = undefined l = undefined c = undefined p = undefined f = undefined d = undefined h = undefined g = undefined m = undefined y = undefined v = b._data(e) if v r.handler and (c = r r = c.handler a = c.selector ) r.guid or (r.guid = b.guid++) (u = v.events) or (u = v.events = {}) (f = v.handle) or (f = v.handle = (e) -> (if typeof b is i or e and b.event.triggered is e.type then t else b.event.dispatch.apply(f.elem, arguments_)) f.elem = e ) n = (n or "").match(w) or [""] l = n.length while l-- s = rt.exec(n[l]) or [] g = y = s[1] m = (s[2] or "").split(".").sort() p = b.event.special[g] or {} g = ((if a then p.delegateType else p.bindType)) or g p = b.event.special[g] or {} d = b.extend( type: g origType: y data: o handler: r guid: r.guid selector: a needsContext: a and b.expr.match.needsContext.test(a) namespace: m.join(".") , c) (h = u[g]) or (h = u[g] = [] h.delegateCount = 0 p.setup and p.setup.call(e, o, m, f) isnt not 1 or ((if e.addEventListener then e.addEventListener(g, f, not 1) else e.attachEvent and e.attachEvent("on" + g, f))) ) p.add and (p.add.call(e, d) d.handler.guid or (d.handler.guid = r.guid) ) (if a then h.splice(h.delegateCount++, 0, d) else h.push(d)) b.event.global[g] = not 0 e = null remove: (e, t, n, r, i) -> o = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = undefined f = undefined d = undefined h = undefined g = undefined m = b.hasData(e) and b._data(e) if m and (c = m.events) t = (t or "").match(w) or [""] l = t.length while l-- if s = rt.exec(t[l]) or [] d = g = s[1] h = (s[2] or "").split(".").sort() d p = b.event.special[d] or {} d = ((if r then p.delegateType else p.bindType)) or d f = c[d] or [] s = s[2] and RegExp("(^|\\.)" + h.join("\\.(?:.*\\.|)") + "(\\.|$)") u = o = f.length while o-- a = f[o] not i and g isnt a.origType or n and n.guid isnt a.guid or s and not s.test(a.namespace) or r and r isnt a.selector and ("**" isnt r or not a.selector) or (f.splice(o, 1) a.selector and f.delegateCount-- p.remove and p.remove.call(e, a) ) u and not f.length and (p.teardown and p.teardown.call(e, h, m.handle) isnt not 1 or b.removeEvent(e, d, m.handle) delete c[d] ) else for d of c b.event.remove e, d + t[l], n, r, not 0 b.isEmptyObject(c) and (delete m.handle b._removeData(e, "events") ) trigger: (n, r, i, a) -> s = undefined u = undefined l = undefined c = undefined p = undefined f = undefined d = undefined h = [i or o] g = (if y.call(n, "type") then n.type else n) m = (if y.call(n, "namespace") then n.namespace.split(".") else []) if l = f = i = i or o 3 isnt i.nodeType and 8 isnt i.nodeType and not nt.test(g + b.event.triggered) and (g.indexOf(".") >= 0 and (m = g.split(".") g = m.shift() m.sort() ) u = 0 > g.indexOf(":") and "on" + g n = (if n[b.expando] then n else new b.Event(g, "object" is typeof n and n)) n.isTrigger = not 0 n.namespace = m.join(".") n.namespace_re = (if n.namespace then RegExp("(^|\\.)" + m.join("\\.(?:.*\\.|)") + "(\\.|$)") else null) n.result = t n.target or (n.target = i) r = (if null is r then [n] else b.makeArray(r, [n])) p = b.event.special[g] or {} a or not p.trigger or p.trigger.apply(i, r) isnt not 1 ) if not a and not p.noBubble and not b.isWindow(i) c = p.delegateType or g nt.test(c + g) or (l = l.parentNode) while l h.push(l) f = l l = l.parentNode f is (i.ownerDocument or o) and h.push(f.defaultView or f.parentWindow or e) d = 0 while (l = h[d++]) and not n.isPropagationStopped() n.type = (if d > 1 then c else p.bindType or g) s = (b._data(l, "events") or {})[n.type] and b._data(l, "handle") s and s.apply(l, r) s = u and l[u] s and b.acceptData(l) and s.apply and s.apply(l, r) is not 1 and n.preventDefault() if n.type = g not (a or n.isDefaultPrevented() or p._default and p._default.apply(i.ownerDocument, r) isnt not 1 or "click" is g and b.nodeName(i, "a") or not b.acceptData(i) or not u or not i[g] or b.isWindow(i)) f = i[u] f and (i[u] = null) b.event.triggered = g try i[g]() b.event.triggered = t f and (i[u] = f) n.result dispatch: (e) -> e = b.event.fix(e) n = undefined r = undefined i = undefined o = undefined a = undefined s = [] u = h.call(arguments_) l = (b._data(this, "events") or {})[e.type] or [] c = b.event.special[e.type] or {} if u[0] = e e.delegateTarget = this not c.preDispatch or c.preDispatch.call(this, e) isnt not 1 s = b.event.handlers.call(this, e, l) n = 0 while (o = s[n++]) and not e.isPropagationStopped() e.currentTarget = o.elem a = 0 while (i = o.handlers[a++]) and not e.isImmediatePropagationStopped() (not e.namespace_re or e.namespace_re.test(i.namespace)) and (e.handleObj = i e.data = i.data r = ((b.event.special[i.origType] or {}).handle or i.handler).apply(o.elem, u) r isnt t and (e.result = r) is not 1 and (e.preventDefault() e.stopPropagation() ) ) c.postDispatch and c.postDispatch.call(this, e) e.result handlers: (e, n) -> r = undefined i = undefined o = undefined a = undefined s = [] u = n.delegateCount l = e.target if u and l.nodeType and (not e.button or "click" isnt e.type) while l isnt this if 1 is l.nodeType and (l.disabled isnt not 0 or "click" isnt e.type) o = [] a = 0 while u > a i = n[a] r = i.selector + " " o[r] is t and (o[r] = (if i.needsContext then b(r, this).index(l) >= 0 else b.find(r, this, null, [l]).length)) o[r] and o.push(i) a++ o.length and s.push( elem: l handlers: o ) l = l.parentNode or this n.length > u and s.push( elem: this handlers: n.slice(u) ) s fix: (e) -> return e if e[b.expando] t = undefined n = undefined r = undefined i = e.type a = e s = @fixHooks[i] s or (@fixHooks[i] = s = (if tt.test(i) then @mouseHooks else (if et.test(i) then @keyHooks else {}))) r = (if s.props then @props.concat(s.props) else @props) e = new b.Event(a) t = r.length while t-- n = r[t] e[n] = a[n] e.target or (e.target = a.srcElement or o) 3 is e.target.nodeType and (e.target = e.target.parentNode) e.metaKey = !!e.metaKey (if s.filter then s.filter(e, a) else e) props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" ") fixHooks: {} keyHooks: props: "char charCode key keyCode".split(" ") filter: (e, t) -> null is e.which and (e.which = (if null isnt t.charCode then t.charCode else t.keyCode)) e mouseHooks: props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" ") filter: (e, n) -> r = undefined i = undefined a = undefined s = n.button u = n.fromElement null is e.pageX and null isnt n.clientX and (i = e.target.ownerDocument or o a = i.documentElement r = i.body e.pageX = n.clientX + (a and a.scrollLeft or r and r.scrollLeft or 0) - (a and a.clientLeft or r and r.clientLeft or 0) e.pageY = n.clientY + (a and a.scrollTop or r and r.scrollTop or 0) - (a and a.clientTop or r and r.clientTop or 0) ) not e.relatedTarget and u and (e.relatedTarget = (if u is e.target then n.toElement else u)) e.which or s is t or (e.which = (if 1 & s then 1 else (if 2 & s then 3 else (if 4 & s then 2 else 0)))) e special: load: noBubble: not 0 click: trigger: -> (if b.nodeName(this, "input") and "checkbox" is @type and @click then (@click() not 1 ) else t) focus: trigger: -> if this isnt o.activeElement and @focus try return @focus() not 1 delegateType: "focusin" blur: trigger: -> (if this is o.activeElement and @blur then (@blur() not 1 ) else t) delegateType: "focusout" beforeunload: postDispatch: (e) -> e.result isnt t and (e.originalEvent.returnValue = e.result) simulate: (e, t, n, r) -> i = b.extend(new b.Event, n, type: e isSimulated: not 0 originalEvent: {} ) (if r then b.event.trigger(i, null, t) else b.event.dispatch.call(t, i)) i.isDefaultPrevented() and n.preventDefault() b.removeEvent = (if o.removeEventListener then (e, t, n) -> e.removeEventListener and e.removeEventListener(t, n, not 1) else (e, t, n) -> r = "on" + t e.detachEvent and (typeof e[r] is i and (e[r] = null) e.detachEvent(r, n) ) ) b.Event = (e, n) -> (if this instanceof b.Event then ((if e and e.type then (@originalEvent = e @type = e.type @isDefaultPrevented = (if e.defaultPrevented or e.returnValue is not 1 or e.getPreventDefault and e.getPreventDefault() then it else ot) ) else @type = e) n and b.extend(this, n) @timeStamp = e and e.timeStamp or b.now() this[b.expando] = not 0 t ) else new b.Event(e, n)) b.Event:: = isDefaultPrevented: ot isPropagationStopped: ot isImmediatePropagationStopped: ot preventDefault: -> e = @originalEvent @isDefaultPrevented = it e and ((if e.preventDefault then e.preventDefault() else e.returnValue = not 1)) stopPropagation: -> e = @originalEvent @isPropagationStopped = it e and (e.stopPropagation and e.stopPropagation() e.cancelBubble = not 0 ) stopImmediatePropagation: -> @isImmediatePropagationStopped = it @stopPropagation() b.each( mouseenter: "mouseover" mouseleave: "mouseout" , (e, t) -> b.event.special[e] = delegateType: t bindType: t handle: (e) -> n = undefined r = this i = e.relatedTarget o = e.handleObj (not i or i isnt r and not b.contains(r, i)) and (e.type = o.origType n = o.handler.apply(this, arguments_) e.type = t ) n ) b.support.submitBubbles or (b.event.special.submit = setup: -> (if b.nodeName(this, "form") then not 1 else (b.event.add(this, "click._submit keypress._submit", (e) -> n = e.target r = (if b.nodeName(n, "input") or b.nodeName(n, "button") then n.form else t) r and not b._data(r, "submitBubbles") and (b.event.add(r, "submit._submit", (e) -> e._submit_bubble = not 0 ) b._data(r, "submitBubbles", not 0) ) ) t )) postDispatch: (e) -> e._submit_bubble and (delete e._submit_bubble @parentNode and not e.isTrigger and b.event.simulate("submit", @parentNode, e, not 0) ) teardown: -> (if b.nodeName(this, "form") then not 1 else (b.event.remove(this, "._submit") t )) ) b.support.changeBubbles or (b.event.special.change = setup: -> (if Z.test(@nodeName) then (("checkbox" is @type or "radio" is @type) and (b.event.add(this, "propertychange._change", (e) -> "checked" is e.originalEvent.propertyName and (@_just_changed = not 0) ) b.event.add(this, "click._change", (e) -> @_just_changed and not e.isTrigger and (@_just_changed = not 1) b.event.simulate("change", this, e, not 0) ) ) not 1 ) else (b.event.add(this, "beforeactivate._change", (e) -> t = e.target Z.test(t.nodeName) and not b._data(t, "changeBubbles") and (b.event.add(t, "change._change", (e) -> not @parentNode or e.isSimulated or e.isTrigger or b.event.simulate("change", @parentNode, e, not 0) ) b._data(t, "changeBubbles", not 0) ) ) t )) handle: (e) -> n = e.target (if this isnt n or e.isSimulated or e.isTrigger or "radio" isnt n.type and "checkbox" isnt n.type then e.handleObj.handler.apply(this, arguments_) else t) teardown: -> b.event.remove(this, "._change") not Z.test(@nodeName) ) b.support.focusinBubbles or b.each( focus: "focusin" blur: "focusout" , (e, t) -> n = 0 r = (e) -> b.event.simulate t, e.target, b.event.fix(e), not 0 b.event.special[t] = setup: -> 0 is n++ and o.addEventListener(e, r, not 0) teardown: -> 0 is --n and o.removeEventListener(e, r, not 0) ) b.fn.extend( on: (e, n, r, i, o) -> a = undefined s = undefined if "object" is typeof e "string" isnt typeof n and (r = r or n n = t ) for a of e @on a, n, r, e[a], o return this if (if null is r and null is i then (i = n r = n = t ) else null is i and ((if "string" is typeof n then (i = r r = t ) else (i = r r = n n = t )))) i is not 1 i = ot else return this unless i 1 is o and (s = i i = (e) -> b().off(e) s.apply(this, arguments_) i.guid = s.guid or (s.guid = b.guid++) ) @each(-> b.event.add this, e, i, r, n ) one: (e, t, n, r) -> @on e, t, n, r, 1 off: (e, n, r) -> i = undefined o = undefined if e and e.preventDefault and e.handleObj return i = e.handleObj b(e.delegateTarget).off((if i.namespace then i.origType + "." + i.namespace else i.origType), i.selector, i.handler) this if "object" is typeof e for o of e @off o, n, e[o] return this (n is not 1 or "function" is typeof n) and (r = n n = t ) r is not 1 and (r = ot) @each(-> b.event.remove this, e, r, n ) bind: (e, t, n) -> @on e, null, t, n unbind: (e, t) -> @off e, null, t delegate: (e, t, n, r) -> @on t, e, n, r undelegate: (e, t, n) -> (if 1 is arguments_.length then @off(e, "**") else @off(t, e or "**", n)) trigger: (e, t) -> @each -> b.event.trigger e, t, this triggerHandler: (e, n) -> r = this[0] (if r then b.event.trigger(e, n, r, not 0) else t) ) (e, t) -> rt = (e) -> Y.test e + "" it = -> e = undefined t = [] e = (n, r) -> t.push(n += " ") > i.cacheLength and delete e[t.shift()] e[n] = r ot = (e) -> e[x] = not 0 e at = (e) -> t = p.createElement("div") try return e(t) catch n return not 1 finally t = null st = (e, t, n, r) -> i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined f = undefined g = undefined m = undefined v = undefined return n if ((if t then t.ownerDocument or t else w)) isnt p and c(t) t = t or p n = n or [] not e or "string" isnt typeof e return [] if 1 isnt (s = t.nodeType) and 9 isnt s if not d and not r if i = J.exec(e) if a = i[1] if 9 is s return n if o = t.getElementById(a) not o or not o.parentNode if o.id is a return n.push(o) n else if t.ownerDocument and (o = t.ownerDocument.getElementById(a)) and y(t, o) and o.id is a return n.push(o) n else if i[2] return H.apply(n, q.call(t.getElementsByTagName(e), 0)) n if (a = i[3]) and T.getByClassName and t.getElementsByClassName return H.apply(n, q.call(t.getElementsByClassName(a), 0)) n if T.qsa and not h.test(e) if f = not 0 g = x m = t v = 9 is s and e 1 is s and "object" isnt t.nodeName.toLowerCase() l = ft(e) (if (f = t.getAttribute("id")) then g = f.replace(K, "\\$&") else t.setAttribute("id", g)) g = "[id='" + g + "'] " u = l.length l[u] = g + dt(l[u]) while u-- m = V.test(e) and t.parentNode or t v = l.join(",") if v try return H.apply(n, q.call(m.querySelectorAll(v), 0)) n finally f or t.removeAttribute("id") wt e.replace(W, "$1"), t, n, r ut = (e, t) -> n = t and e r = n and (~t.sourceIndex or j) - (~e.sourceIndex or j) return r if r return -1 if n is t while n = n.nextSibling if n (if e then 1 else -1) lt = (e) -> (t) -> n = t.nodeName.toLowerCase() "input" is n and t.type is e ct = (e) -> (t) -> n = t.nodeName.toLowerCase() ("input" is n or "button" is n) and t.type is e pt = (e) -> ot (t) -> t = +t ot((n, r) -> i = undefined o = e([], n.length, t) a = o.length n[i = o[a]] and (n[i] = not (r[i] = n[i])) while a-- ) ft = (e, t) -> n = undefined r = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = E[e + " "] return (if t then 0 else c.slice(0)) if c s = e u = [] l = i.preFilter while s (not n or (r = $.exec(s))) and (r and (s = s.slice(r[0].length) or s) u.push(o = []) ) n = not 1 (r = I.exec(s)) and (n = r.shift() o.push( value: n type: r[0].replace(W, " ") ) s = s.slice(n.length) ) for a of i.filter not (r = U[a].exec(s)) or l[a] and not (r = l[a](r)) or (n = r.shift() o.push( value: n type: a matches: r ) s = s.slice(n.length) ) break unless n (if t then s.length else (if s then st.error(e) else E(e, u).slice(0))) dt = (e) -> t = 0 n = e.length r = "" while n > t r += e[t].value t++ r ht = (e, t, n) -> i = t.dir o = n and "parentNode" is i a = C++ (if t.first then (t, n, r) -> return e(t, n, r) if 1 is t.nodeType or o while t = t[i] else (t, n, s) -> u = undefined l = undefined c = undefined p = N + " " + a if s return not 0 if (1 is t.nodeType or o) and e(t, n, s) while t = t[i] else while t = t[i] if 1 is t.nodeType or o if c = t[x] or (t[x] = {}) (l = c[i]) and l[0] is p return u is not 0 if (u = l[1]) is not 0 or u is r else return not 0 if l = c[i] = [p] l[1] = e(t, n, s) or r l[1] is not 0 ) gt = (e) -> (if e.length > 1 then (t, n, r) -> i = e.length return not 1 unless e[i](t, n, r) while i-- not 0 else e[0]) mt = (e, t, n, r, i) -> o = undefined a = [] s = 0 u = e.length l = null isnt t while u > s (o = e[s]) and (not n or n(o, r, i)) and (a.push(o) l and t.push(s) ) s++ a yt = (e, t, n, r, i, o) -> r and not r[x] and (r = yt(r)) i and not i[x] and (i = yt(i, o)) ot((o, a, s, u) -> l = undefined c = undefined p = undefined f = [] d = [] h = a.length g = o or xt(t or "*", (if s.nodeType then [s] else s), []) m = (if not e or not o and t then g else mt(g, f, e, s, u)) y = (if n then (if i or ((if o then e else h or r)) then [] else a) else m) if n and n(m, y, s, u) r l = mt(y, d) r(l, [], s, u) c = l.length (p = l[c]) and (y[d[c]] = not (m[d[c]] = p)) while c-- if o if i or e if i l = [] c = y.length (p = y[c]) and l.push(m[c] = p) while c-- i null, y = [], l, u c = y.length (p = y[c]) and (l = (if i then M.call(o, p) else f[c])) > -1 and (o[l] = not (a[l] = p)) while c-- else y = mt((if y is a then y.splice(h, y.length) else y)) (if i then i(null, a, y, u) else H.apply(a, y)) ) vt = (e) -> t = undefined n = undefined r = undefined o = e.length a = i.relative[e[0].type] s = a or i.relative[" "] u = (if a then 1 else 0) c = ht((e) -> e is t , s, not 0) p = ht((e) -> M.call(t, e) > -1 , s, not 0) f = [(e, n, r) -> not a and (r or n isnt l) or ((if (t = n).nodeType then c(e, n, r) else p(e, n, r))) ] while o > u unless n = i.relative[e[u].type] if n = i.filter[e[u].type].apply(null, e[u].matches) n[x] r = ++u while o > r break if i.relative[e[r].type] r++ return yt(u > 1 and gt(f), u > 1 and dt(e.slice(0, u - 1)).replace(W, "$1"), n, r > u and vt(e.slice(u, r)), o > r and vt(e = e.slice(r)), o > r and dt(e)) f.push n u++ gt f bt = (e, t) -> n = 0 o = t.length > 0 a = e.length > 0 s = (s, u, c, f, d) -> h = undefined g = undefined m = undefined y = [] v = 0 b = "0" x = s and [] w = null isnt d T = l C = s or a and i.find.TAG("*", d and u.parentNode or u) k = N += (if null is T then 1 else Math.random() or .1) w and (l = u isnt p and u r = n ) while null isnt (h = C[b]) if a and h g = 0 while m = e[g++] if m(h, u, c) f.push h break w and (N = k r = ++n ) o and ((h = not m and h) and v-- s and x.push(h) ) b++ if v += b o and b isnt v g = 0 m x, y, u, c while m = t[g++] if s x[b] or y[b] or (y[b] = L.call(f)) while b-- if v > 0 y = mt(y) H.apply(f, y) w and not s and y.length > 0 and v + t.length > 1 and st.uniqueSort(f) w and (N = k l = T ) x (if o then ot(s) else s) xt = (e, t, n) -> r = 0 i = t.length while i > r st e, t[r], n r++ n wt = (e, t, n, r) -> o = undefined a = undefined u = undefined l = undefined c = undefined p = ft(e) if not r and 1 is p.length if a = p[0] = p[0].slice(0) a.length > 2 and "ID" is (u = a[0]).type and 9 is t.nodeType and not d and i.relative[a[1].type] return n if t = i.find.ID(u.matches[0].replace(et, tt), t)[0] not t e = e.slice(a.shift().value.length) o = (if U.needsContext.test(e) then 0 else a.length) while o-- break if u = a[o] i.relative[l = u.type] if (c = i.find[l]) and (r = c(u.matches[0].replace(et, tt), V.test(a[0].type) and t.parentNode or t)) if a.splice(o, 1) e = r.length and dt(a) not e return H.apply(n, q.call(r, 0)) n break s(e, p)(r, t, d, n, V.test(e)) n Tt = -> n = undefined r = undefined i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = undefined f = undefined d = undefined h = undefined g = undefined m = undefined y = undefined v = undefined x = "sizzle" + -new Date w = e.document T = {} N = 0 C = 0 k = it() E = it() S = it() A = typeof t j = 1 << 31 D = [] L = D.pop H = D.push q = D.slice M = D.indexOf or (e) -> t = 0 n = @length while n > t return t if this[t] is e t++ -1 _ = "[\\x20\\t\\r\\n\\f]" F = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+" O = F.replace("w", "w#") B = "([*^$|!~]?=)" P = "\\[" + _ + "*(" + F + ")" + _ + "*(?:" + B + _ + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + O + ")|)|)" + _ + "*\\]" R = ":(" + F + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + P.replace(3, 8) + ")*)|.*)\\)|)" W = RegExp("^" + _ + "+|((?:^|[^\\\\])(?:\\\\.)*)" + _ + "+$", "g") $ = RegExp("^" + _ + "*," + _ + "*") I = RegExp("^" + _ + "*([\\x20\\t\\r\\n\\f>+~])" + _ + "*") z = RegExp(R) X = RegExp("^" + O + "$") U = ID: RegExp("^#(" + F + ")") CLASS: RegExp("^\\.(" + F + ")") NAME: RegExp("^\\[name=['\"]?(" + F + ")['\"]?\\]") TAG: RegExp("^(" + F.replace("w", "w*") + ")") ATTR: RegExp("^" + P) PSEUDO: RegExp("^" + R) CHILD: RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + _ + "*(even|odd|(([+-]|)(\\d*)n|)" + _ + "*(?:([+-]|)" + _ + "*(\\d+)|))" + _ + "*\\)|)", "i") needsContext: RegExp("^" + _ + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + _ + "*((?:-\\d)?\\d*)" + _ + "*\\)|)(?=[^-]|$)", "i") V = /[\x20\t\r\n\f]*[+~]/ Y = /^[^{]+\{\s*\[native code/ J = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/ G = /^(?:input|select|textarea|button)$/i Q = /^h\d$/i K = /'|\\/g Z = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g et = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g tt = (e, t) -> n = "0x" + t - 65536 (if n isnt n then t else (if 0 > n then String.fromCharCode(n + 65536) else String.fromCharCode(55296 | n >> 10, 56320 | 1023 & n))) try q.call(w.documentElement.childNodes, 0)[0].nodeType catch nt q = (e) -> t = undefined n = [] n.push t while t = this[e++] n a = st.isXML = (e) -> t = e and (e.ownerDocument or e).documentElement (if t then "HTML" isnt t.nodeName else not 1) c = st.setDocument = (e) -> n = (if e then e.ownerDocument or e else w) (if n isnt p and 9 is n.nodeType and n.documentElement then (p = n f = n.documentElement d = a(n) T.tagNameNoComments = at((e) -> e.appendChild(n.createComment("")) not e.getElementsByTagName("*").length ) T.attributes = at((e) -> e.innerHTML = "<select></select>" t = typeof e.lastChild.getAttribute("multiple") "boolean" isnt t and "string" isnt t ) T.getByClassName = at((e) -> e.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>" (if e.getElementsByClassName and e.getElementsByClassName("e").length then (e.lastChild.className = "e" 2 is e.getElementsByClassName("e").length ) else not 1) ) T.getByName = at((e) -> e.id = x + 0 e.innerHTML = "<a name='" + x + "'></a><div name='" + x + "'></div>" f.insertBefore(e, f.firstChild) t = n.getElementsByName and n.getElementsByName(x).length is 2 + n.getElementsByName(x + 0).length T.getIdNotName = not n.getElementById(x) f.removeChild(e) t ) i.attrHandle = (if at((e) -> e.innerHTML = "<a href='#'></a>" e.firstChild and typeof e.firstChild.getAttribute isnt A and "#" is e.firstChild.getAttribute("href") ) then {} else href: (e) -> e.getAttribute "href", 2 type: (e) -> e.getAttribute "type" ) (if T.getIdNotName then (i.find.ID = (e, t) -> if typeof t.getElementById isnt A and not d n = t.getElementById(e) (if n and n.parentNode then [n] else []) i.filter.ID = (e) -> t = e.replace(et, tt) (e) -> e.getAttribute("id") is t ) else (i.find.ID = (e, n) -> if typeof n.getElementById isnt A and not d r = n.getElementById(e) (if r then (if r.id is e or typeof r.getAttributeNode isnt A and r.getAttributeNode("id").value is e then [r] else t) else []) i.filter.ID = (e) -> t = e.replace(et, tt) (e) -> n = typeof e.getAttributeNode isnt A and e.getAttributeNode("id") n and n.value is t )) i.find.TAG = (if T.tagNameNoComments then (e, n) -> (if typeof n.getElementsByTagName isnt A then n.getElementsByTagName(e) else t) else (e, t) -> n = undefined r = [] i = 0 o = t.getElementsByTagName(e) if "*" is e 1 is n.nodeType and r.push(n) while n = o[i++] return r o ) i.find.NAME = T.getByName and (e, n) -> (if typeof n.getElementsByName isnt A then n.getElementsByName(name) else t) i.find.CLASS = T.getByClassName and (e, n) -> (if typeof n.getElementsByClassName is A or d then t else n.getElementsByClassName(e)) g = [] h = [":focus"] (T.qsa = rt(n.querySelectorAll)) and (at((e) -> e.innerHTML = "<select><option selected=''></option></select>" e.querySelectorAll("[selected]").length or h.push("\\[" + _ + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)") e.querySelectorAll(":checked").length or h.push(":checked") ) at((e) -> e.innerHTML = "<input type='hidden' i=''/>" e.querySelectorAll("[i^='']").length and h.push("[*^$]=" + _ + "*(?:\"\"|'')") e.querySelectorAll(":enabled").length or h.push(":enabled", ":disabled") e.querySelectorAll("*,:x") h.push(",.*:") ) ) (T.matchesSelector = rt(m = f.matchesSelector or f.mozMatchesSelector or f.webkitMatchesSelector or f.oMatchesSelector or f.msMatchesSelector)) and at((e) -> T.disconnectedMatch = m.call(e, "div") m.call(e, "[s!='']:x") g.push("!=", R) ) h = RegExp(h.join("|")) g = RegExp(g.join("|")) y = (if rt(f.contains) or f.compareDocumentPosition then (e, t) -> n = (if 9 is e.nodeType then e.documentElement else e) r = t and t.parentNode e is r or not (not r or 1 isnt r.nodeType or not ((if n.contains then n.contains(r) else e.compareDocumentPosition and 16 & e.compareDocumentPosition(r)))) else (e, t) -> return not 0 if t is e while t = t.parentNode if t not 1 ) v = (if f.compareDocumentPosition then (e, t) -> r = undefined (if e is t then (u = not 0 0 ) else (if (r = t.compareDocumentPosition and e.compareDocumentPosition and e.compareDocumentPosition(t)) then (if 1 & r or e.parentNode and 11 is e.parentNode.nodeType then (if e is n or y(w, e) then -1 else (if t is n or y(w, t) then 1 else 0)) else (if 4 & r then -1 else 1)) else (if e.compareDocumentPosition then -1 else 1))) else (e, t) -> r = undefined i = 0 o = e.parentNode a = t.parentNode s = [e] l = [t] if e is t return u = not 0 0 return (if e is n then -1 else (if t is n then 1 else (if o then -1 else (if a then 1 else 0)))) if not o or not a return ut(e, t) if o is a r = e s.unshift r while r = r.parentNode r = t l.unshift r while r = r.parentNode i++ while s[i] is l[i] (if i then ut(s[i], l[i]) else (if s[i] is w then -1 else (if l[i] is w then 1 else 0))) ) u = not 1 [0, 0].sort(v) T.detectDuplicates = u p ) else p) st.matches = (e, t) -> st e, null, null, t st.matchesSelector = (e, t) -> if (e.ownerDocument or e) isnt p and c(e) t = t.replace(Z, "='$1']") not (not T.matchesSelector or d or g and g.test(t) or h.test(t)) try n = m.call(e, t) return n if n or T.disconnectedMatch or e.document and 11 isnt e.document.nodeType st(t, p, null, [e]).length > 0 st.contains = (e, t) -> (e.ownerDocument or e) isnt p and c(e) y(e, t) st.attr = (e, t) -> n = undefined (e.ownerDocument or e) isnt p and c(e) d or (t = t.toLowerCase()) (if (n = i.attrHandle[t]) then n(e) else (if d or T.attributes then e.getAttribute(t) else (if ((n = e.getAttributeNode(t)) or e.getAttribute(t)) and e[t] is not 0 then t else (if n and n.specified then n.value else null)))) st.error = (e) -> throw Error("Syntax error, unrecognized expression: " + e) st.uniqueSort = (e) -> t = undefined n = [] r = 1 i = 0 if u = not T.detectDuplicates e.sort(v) u while t = e[r] t is e[r - 1] and (i = n.push(r)) r++ e.splice n[i], 1 while i-- e o = st.getText = (e) -> t = undefined n = "" r = 0 i = e.nodeType if i if 1 is i or 9 is i or 11 is i return e.textContent if "string" is typeof e.textContent e = e.firstChild while e n += o(e) e = e.nextSibling else return e.nodeValue if 3 is i or 4 is i else while t = e[r] n += o(t) r++ n i = st.selectors = cacheLength: 50 createPseudo: ot match: U find: {} relative: ">": dir: "parentNode" first: not 0 " ": dir: "parentNode" "+": dir: "previousSibling" first: not 0 "~": dir: "previousSibling" preFilter: ATTR: (e) -> e[1] = e[1].replace(et, tt) e[3] = (e[4] or e[5] or "").replace(et, tt) "~=" is e[2] and (e[3] = " " + e[3] + " ") e.slice(0, 4) CHILD: (e) -> e[1] = e[1].toLowerCase() (if "nth" is e[1].slice(0, 3) then (e[3] or st.error(e[0]) e[4] = +((if e[4] then e[5] + (e[6] or 1) else 2 * ("even" is e[3] or "odd" is e[3]))) e[5] = +(e[7] + e[8] or "odd" is e[3]) ) else e[3] and st.error(e[0])) e PSEUDO: (e) -> t = undefined n = not e[5] and e[2] (if U.CHILD.test(e[0]) then null else ((if e[4] then e[2] = e[4] else n and z.test(n) and (t = ft(n, not 0)) and (t = n.indexOf(")", n.length - t) - n.length) and (e[0] = e[0].slice(0, t) e[2] = n.slice(0, t) )) e.slice(0, 3) )) filter: TAG: (e) -> (if "*" is e then -> not 0 else (e = e.replace(et, tt).toLowerCase() (t) -> t.nodeName and t.nodeName.toLowerCase() is e )) CLASS: (e) -> t = k[e + " "] t or (t = RegExp("(^|" + _ + ")" + e + "(" + _ + "|$)")) and k(e, (e) -> t.test e.className or typeof e.getAttribute isnt A and e.getAttribute("class") or "" ) ATTR: (e, t, n) -> (r) -> i = st.attr(r, e) (if null is i then "!=" is t else (if t then (i += "" (if "=" is t then i is n else (if "!=" is t then i isnt n else (if "^=" is t then n and 0 is i.indexOf(n) else (if "*=" is t then n and i.indexOf(n) > -1 else (if "$=" is t then n and i.slice(-n.length) is n else (if "~=" is t then (" " + i + " ").indexOf(n) > -1 else (if "|=" is t then i is n or i.slice(0, n.length + 1) is n + "-" else not 1))))))) ) else not 0)) CHILD: (e, t, n, r, i) -> o = "nth" isnt e.slice(0, 3) a = "last" isnt e.slice(-4) s = "of-type" is t (if 1 is r and 0 is i then (e) -> !!e.parentNode else (t, n, u) -> l = undefined c = undefined p = undefined f = undefined d = undefined h = undefined g = (if o isnt a then "nextSibling" else "previousSibling") m = t.parentNode y = s and t.nodeName.toLowerCase() v = not u and not s if m if o while g p = t return not 1 if (if s then p.nodeName.toLowerCase() is y else 1 is p.nodeType) while p = p[g] h = g = "only" is e and not h and "nextSibling" return not 0 if h = [(if a then m.firstChild else m.lastChild)] a and v c = m[x] or (m[x] = {}) l = c[e] or [] d = l[0] is N and l[1] f = l[0] is N and l[2] p = d and m.childNodes[d] while p = ++d and p and p[g] or (f = d = 0) or h.pop() if 1 is p.nodeType and ++f and p is t c[e] = [N, d, f] break else if v and (l = (t[x] or (t[x] = {}))[e]) and l[0] is N f = l[1] else while p = ++d and p and p[g] or (f = d = 0) or h.pop() break if ((if s then p.nodeName.toLowerCase() is y else 1 is p.nodeType)) and ++f and (v and ((p[x] or (p[x] = {}))[e] = [N, f]) p is t ) f -= i f is r or 0 is f % r and f / r >= 0 ) PSEUDO: (e, t) -> n = undefined r = i.pseudos[e] or i.setFilters[e.toLowerCase()] or st.error("unsupported pseudo: " + e) (if r[x] then r(t) else (if r.length > 1 then (n = [e, e, "", t] (if i.setFilters.hasOwnProperty(e.toLowerCase()) then ot((e, n) -> i = undefined o = r(e, t) a = o.length while a-- i = M.call(e, o[a]) e[i] = not (n[i] = o[a]) ) else (e) -> r e, 0, n ) ) else r)) pseudos: not: ot((e) -> t = [] n = [] r = s(e.replace(W, "$1")) (if r[x] then ot((e, t, n, i) -> o = undefined a = r(e, null, i, []) s = e.length (o = a[s]) and (e[s] = not (t[s] = o)) while s-- ) else (e, i, o) -> t[0] = e r(t, null, o, n) not n.pop() ) ) has: ot((e) -> (t) -> st(e, t).length > 0 ) contains: ot((e) -> (t) -> (t.textContent or t.innerText or o(t)).indexOf(e) > -1 ) lang: ot((e) -> X.test(e or "") or st.error("unsupported lang: " + e) e = e.replace(et, tt).toLowerCase() (t) -> n = undefined loop if n = (if d then t.getAttribute("xml:lang") or t.getAttribute("lang") else t.lang) return n = n.toLowerCase() n is e or 0 is n.indexOf(e + "-") break unless (t = t.parentNode) and 1 is t.nodeType not 1 ) target: (t) -> n = e.location and e.location.hash n and n.slice(1) is t.id root: (e) -> e is f focus: (e) -> e is p.activeElement and (not p.hasFocus or p.hasFocus()) and !!(e.type or e.href or ~e.tabIndex) enabled: (e) -> e.disabled is not 1 disabled: (e) -> e.disabled is not 0 checked: (e) -> t = e.nodeName.toLowerCase() "input" is t and !!e.checked or "option" is t and !!e.selected selected: (e) -> e.parentNode and e.parentNode.selectedIndex e.selected is not 0 empty: (e) -> e = e.firstChild while e return not 1 if e.nodeName > "@" or 3 is e.nodeType or 4 is e.nodeType e = e.nextSibling not 0 parent: (e) -> not i.pseudos.empty(e) header: (e) -> Q.test e.nodeName input: (e) -> G.test e.nodeName button: (e) -> t = e.nodeName.toLowerCase() "input" is t and "button" is e.type or "button" is t text: (e) -> t = undefined "input" is e.nodeName.toLowerCase() and "text" is e.type and (null is (t = e.getAttribute("type")) or t.toLowerCase() is e.type) first: pt(-> [0] ) last: pt((e, t) -> [t - 1] ) eq: pt((e, t, n) -> [(if 0 > n then n + t else n)] ) even: pt((e, t) -> n = 0 while t > n e.push n n += 2 e ) odd: pt((e, t) -> n = 1 while t > n e.push n n += 2 e ) lt: pt((e, t, n) -> r = (if 0 > n then n + t else n) while --r >= 0 e.push r e ) gt: pt((e, t, n) -> r = (if 0 > n then n + t else n) while t > ++r e.push r e ) for n of radio: not 0 checkbox: not 0 file: not 0 password: not 0 image: not 0 i.pseudos[n] = lt(n) for n of submit: not 0 reset: not 0 i.pseudos[n] = ct(n) s = st.compile = (e, t) -> n = undefined r = [] i = [] o = S[e + " "] unless o t or (t = ft(e)) n = t.length while n-- o = vt(t[n]) (if o[x] then r.push(o) else i.push(o)) o = S(e, bt(i, r)) o i.pseudos.nth = i.pseudos.eq i.filters = Tt:: = i.pseudos i.setFilters = new Tt c() st.attr = b.attr b.find = st b.expr = st.selectors b.expr[":"] = b.expr.pseudos b.unique = st.uniqueSort b.text = st.getText b.isXMLDoc = st.isXML b.contains = st.contains (e) at = /Until$/ st = /^(?:parents|prev(?:Until|All))/ ut = /^.[^:#\[\.,]*$/ lt = b.expr.match.needsContext ct = children: not 0 contents: not 0 next: not 0 prev: not 0 b.fn.extend( find: (e) -> t = undefined n = undefined r = undefined i = @length unless "string" is typeof e return r = this @pushStack(b(e).filter(-> t = 0 while i > t return not 0 if b.contains(r[t], this) t++ )) n = [] t = 0 while i > t b.find e, this[t], n t++ n = @pushStack((if i > 1 then b.unique(n) else n)) n.selector = ((if @selector then @selector + " " else "")) + e n has: (e) -> t = undefined n = b(e, this) r = n.length @filter -> t = 0 while r > t return not 0 if b.contains(this, n[t]) t++ not: (e) -> @pushStack ft(this, e, not 1) filter: (e) -> @pushStack ft(this, e, not 0) is: (e) -> !!e and ((if "string" is typeof e then (if lt.test(e) then b(e, @context).index(this[0]) >= 0 else b.filter(e, this).length > 0) else @filter(e).length > 0)) closest: (e, t) -> n = undefined r = 0 i = @length o = [] a = (if lt.test(e) or "string" isnt typeof e then b(e, t or @context) else 0) while i > r n = this[r] while n and n.ownerDocument and n isnt t and 11 isnt n.nodeType if (if a then a.index(n) > -1 else b.find.matchesSelector(n, e)) o.push n break n = n.parentNode r++ @pushStack (if o.length > 1 then b.unique(o) else o) index: (e) -> (if e then (if "string" is typeof e then b.inArray(this[0], b(e)) else b.inArray((if e.jquery then e[0] else e), this)) else (if this[0] and this[0].parentNode then @first().prevAll().length else -1)) add: (e, t) -> n = (if "string" is typeof e then b(e, t) else b.makeArray((if e and e.nodeType then [e] else e))) r = b.merge(@get(), n) @pushStack b.unique(r) addBack: (e) -> @add (if null is e then @prevObject else @prevObject.filter(e)) ) b.fn.andSelf = b.fn.addBack b.each( parent: (e) -> t = e.parentNode (if t and 11 isnt t.nodeType then t else null) parents: (e) -> b.dir e, "parentNode" parentsUntil: (e, t, n) -> b.dir e, "parentNode", n next: (e) -> pt e, "nextSibling" prev: (e) -> pt e, "previousSibling" nextAll: (e) -> b.dir e, "nextSibling" prevAll: (e) -> b.dir e, "previousSibling" nextUntil: (e, t, n) -> b.dir e, "nextSibling", n prevUntil: (e, t, n) -> b.dir e, "previousSibling", n siblings: (e) -> b.sibling (e.parentNode or {}).firstChild, e children: (e) -> b.sibling e.firstChild contents: (e) -> (if b.nodeName(e, "iframe") then e.contentDocument or e.contentWindow.document else b.merge([], e.childNodes)) , (e, t) -> b.fn[e] = (n, r) -> i = b.map(this, t, n) at.test(e) or (r = n) r and "string" is typeof r and (i = b.filter(r, i)) i = (if @length > 1 and not ct[e] then b.unique(i) else i) @length > 1 and st.test(e) and (i = i.reverse()) @pushStack(i) ) b.extend( filter: (e, t, n) -> n and (e = ":not(" + e + ")") (if 1 is t.length then (if b.find.matchesSelector(t[0], e) then [t[0]] else []) else b.find.matches(e, t)) dir: (e, n, r) -> i = [] o = e[n] while o and 9 isnt o.nodeType and (r is t or 1 isnt o.nodeType or not b(o).is(r)) 1 is o.nodeType and i.push(o) o = o[n] i sibling: (e, t) -> n = [] while e 1 is e.nodeType and e isnt t and n.push(e) e = e.nextSibling n ) ht = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video" gt = RegExp(" jQuery\\d+=\"(?:null|\\d+)\"", "g") mt = RegExp("<(?:" + ht + ")[\\s/>]", "i") yt = /^\s+/ vt = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/g bt = /<([\w:]+)/ xt = /<tbody/i wt = /<|&#?\w+;/ Tt = /<(?:script|style|link)/i Nt = /^(?:checkbox|radio)$/i Ct = /checked\s*(?:[^=]|=\s*.checked.)/i kt = /^$|\/(?:java|ecma)script/i Et = /^true\/(.*)/ St = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g At = option: [1, "<select multiple='multiple'>", "</select>"] legend: [1, "<fieldset>", "</fieldset>"] area: [1, "<map>", "</map>"] param: [1, "<object>", "</object>"] thead: [1, "<table>", "</table>"] tr: [2, "<table><tbody>", "</tbody></table>"] col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"] td: [3, "<table><tbody><tr>", "</tr></tbody></table>"] _default: (if b.support.htmlSerialize then [0, "", ""] else [1, "X<div>", "</div>"]) jt = dt(o) Dt = jt.appendChild(o.createElement("div")) At.optgroup = At.option At.tbody = At.tfoot = At.colgroup = At.caption = At.thead At.th = At.td b.fn.extend( text: (e) -> b.access this, ((e) -> (if e is t then b.text(this) else @empty().append((this[0] and this[0].ownerDocument or o).createTextNode(e))) ), null, e, arguments_.length wrapAll: (e) -> if b.isFunction(e) return @each((t) -> b(this).wrapAll e.call(this, t) ) if this[0] t = b(e, this[0].ownerDocument).eq(0).clone(not 0) this[0].parentNode and t.insertBefore(this[0]) t.map(-> e = this e = e.firstChild while e.firstChild and 1 is e.firstChild.nodeType e ).append(this) this wrapInner: (e) -> (if b.isFunction(e) then @each((t) -> b(this).wrapInner e.call(this, t) ) else @each(-> t = b(this) n = t.contents() (if n.length then n.wrapAll(e) else t.append(e)) )) wrap: (e) -> t = b.isFunction(e) @each (n) -> b(this).wrapAll (if t then e.call(this, n) else e) unwrap: -> @parent().each(-> b.nodeName(this, "body") or b(this).replaceWith(@childNodes) ).end() append: -> @domManip arguments_, not 0, (e) -> (1 is @nodeType or 11 is @nodeType or 9 is @nodeType) and @appendChild(e) prepend: -> @domManip arguments_, not 0, (e) -> (1 is @nodeType or 11 is @nodeType or 9 is @nodeType) and @insertBefore(e, @firstChild) before: -> @domManip arguments_, not 1, (e) -> @parentNode and @parentNode.insertBefore(e, this) after: -> @domManip arguments_, not 1, (e) -> @parentNode and @parentNode.insertBefore(e, @nextSibling) remove: (e, t) -> n = undefined r = 0 while null isnt (n = this[r]) (not e or b.filter(e, [n]).length > 0) and (t or 1 isnt n.nodeType or b.cleanData(Ot(n)) n.parentNode and (t and b.contains(n.ownerDocument, n) and Mt(Ot(n, "script")) n.parentNode.removeChild(n) ) ) r++ this empty: -> e = undefined t = 0 while null isnt (e = this[t]) 1 is e.nodeType and b.cleanData(Ot(e, not 1)) e.removeChild e.firstChild while e.firstChild e.options and b.nodeName(e, "select") and (e.options.length = 0) t++ this clone: (e, t) -> e = (if null is e then not 1 else e) t = (if null is t then e else t) @map(-> b.clone this, e, t ) html: (e) -> b.access this, ((e) -> n = this[0] or {} r = 0 i = @length return (if 1 is n.nodeType then n.innerHTML.replace(gt, "") else t) if e is t unless "string" isnt typeof e or Tt.test(e) or not b.support.htmlSerialize and mt.test(e) or not b.support.leadingWhitespace and yt.test(e) or At[(bt.exec(e) or ["", ""])[1].toLowerCase()] e = e.replace(vt, "<$1></$2>") try while i > r n = this[r] or {} 1 is n.nodeType and (b.cleanData(Ot(n, not 1)) n.innerHTML = e ) r++ n = 0 n and @empty().append(e) ), null, e, arguments_.length replaceWith: (e) -> t = b.isFunction(e) t or "string" is typeof e or (e = b(e).not(this).detach()) @domManip([e], not 0, (e) -> t = @nextSibling n = @parentNode n and (b(this).remove() n.insertBefore(e, t) ) ) detach: (e) -> @remove e, not 0 domManip: (e, n, r) -> e = f.apply([], e) i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = 0 p = @length d = this h = p - 1 g = e[0] m = b.isFunction(g) if m or not (1 >= p or "string" isnt typeof g or b.support.checkClone) and Ct.test(g) return @each((i) -> o = d.eq(i) m and (e[0] = g.call(this, i, (if n then o.html() else t))) o.domManip(e, n, r) ) if p and (l = b.buildFragment(e, this[0].ownerDocument, not 1, this) i = l.firstChild 1 is l.childNodes.length and (l = i) i ) n = n and b.nodeName(i, "tr") s = b.map(Ot(l, "script"), Ht) a = s.length while p > c o = l c isnt h and (o = b.clone(o, not 0, not 0) a and b.merge(s, Ot(o, "script")) ) r.call((if n and b.nodeName(this[c], "table") then Lt(this[c], "tbody") else this[c]), o, c) c++ if a u = s[s.length - 1].ownerDocument b.map(s, qt) c = 0 while a > c o = s[c] kt.test(o.type or "") and not b._data(o, "globalEval") and b.contains(u, o) and ((if o.src then b.ajax( url: o.src type: "GET" dataType: "script" async: not 1 global: not 1 throws: not 0 ) else b.globalEval((o.text or o.textContent or o.innerHTML or "").replace(St, "")))) c++ l = i = null this ) b.each appendTo: "append" prependTo: "prepend" insertBefore: "before" insertAfter: "after" replaceAll: "replaceWith" , (e, t) -> b.fn[e] = (e) -> n = undefined r = 0 i = [] o = b(e) a = o.length - 1 while a >= r n = (if r is a then this else @clone(not 0)) b(o[r])[t](n) d.apply(i, n.get()) r++ @pushStack i b.extend clone: (e, t, n) -> r = undefined i = undefined o = undefined a = undefined s = undefined u = b.contains(e.ownerDocument, e) if (if b.support.html5Clone or b.isXMLDoc(e) or not mt.test("<" + e.nodeName + ">") then o = e.cloneNode(not 0) else (Dt.innerHTML = e.outerHTML Dt.removeChild(o = Dt.firstChild) )) not (b.support.noCloneEvent and b.support.noCloneChecked or 1 isnt e.nodeType and 11 isnt e.nodeType or b.isXMLDoc(e)) r = Ot(o) s = Ot(e) a = 0 while null isnt (i = s[a]) r[a] and Ft(i, r[a]) ++a if t if n s = s or Ot(e) r = r or Ot(o) a = 0 while null isnt (i = s[a]) _t i, r[a] a++ else _t e, o r = Ot(o, "script") r.length > 0 and Mt(r, not u and Ot(e, "script")) r = s = i = null o buildFragment: (e, t, n, r) -> i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = e.length f = dt(t) d = [] h = 0 while p > h if o = e[h] o or 0 is o if "object" is b.type(o) b.merge d, (if o.nodeType then [o] else o) else if wt.test(o) s = s or f.appendChild(t.createElement("div")) u = (bt.exec(o) or ["", ""])[1].toLowerCase() c = At[u] or At._default s.innerHTML = c[1] + o.replace(vt, "<$1></$2>") + c[2] i = c[0] s = s.lastChild while i-- if not b.support.leadingWhitespace and yt.test(o) and d.push(t.createTextNode(yt.exec(o)[0])) not b.support.tbody o = (if "table" isnt u or xt.test(o) then (if "<table>" isnt c[1] or xt.test(o) then 0 else s) else s.firstChild) i = o and o.childNodes.length b.nodeName(l = o.childNodes[i], "tbody") and not l.childNodes.length and o.removeChild(l) while i-- b.merge(d, s.childNodes) s.textContent = "" s.removeChild s.firstChild while s.firstChild s = f.lastChild else d.push t.createTextNode(o) h++ s and f.removeChild(s) b.support.appendChecked or b.grep(Ot(d, "input"), Bt) h = 0 while o = d[h++] if (not r or -1 is b.inArray(o, r)) and (a = b.contains(o.ownerDocument, o) s = Ot(f.appendChild(o), "script") a and Mt(s) n ) i = 0 kt.test(o.type or "") and n.push(o) while o = s[i++] s = null f cleanData: (e, t) -> n = undefined r = undefined o = undefined a = undefined s = 0 u = b.expando l = b.cache p = b.support.deleteExpando f = b.event.special while null isnt (n = e[s]) if (t or b.acceptData(n)) and (o = n[u] a = o and l[o] ) if a.events for r of a.events (if f[r] then b.event.remove(n, r) else b.removeEvent(n, r, a.handle)) l[o] and (delete l[o] (if p then delete n[u] else (if typeof n.removeAttribute isnt i then n.removeAttribute(u) else n[u] = null)) c.push(o) ) s++ Pt = undefined Rt = undefined Wt = undefined $t = /alpha\([^)]*\)/i It = /opacity\s*=\s*([^)]*)/ zt = /^(top|right|bottom|left)$/ Xt = /^(none|table(?!-c[ea]).+)/ Ut = /^margin/ Vt = RegExp("^(" + x + ")(.*)$", "i") Yt = RegExp("^(" + x + ")(?!px)[a-z%]+$", "i") Jt = RegExp("^([+-])=(" + x + ")", "i") Gt = BODY: "block" Qt = position: "absolute" visibility: "hidden" display: "block" Kt = letterSpacing: 0 fontWeight: 400 Zt = ["Top", "Right", "Bottom", "Left"] en = ["Webkit", "O", "Moz", "ms"] b.fn.extend( css: (e, n) -> b.access this, ((e, n, r) -> i = undefined o = undefined a = {} s = 0 if b.isArray(n) o = Rt(e) i = n.length while i > s a[n[s]] = b.css(e, n[s], not 1, o) s++ return a (if r isnt t then b.style(e, n, r) else b.css(e, n)) ), e, n, arguments_.length > 1 show: -> rn this, not 0 hide: -> rn this toggle: (e) -> t = "boolean" is typeof e @each -> (if ((if t then e else nn(this))) then b(this).show() else b(this).hide()) ) b.extend( cssHooks: opacity: get: (e, t) -> if t n = Wt(e, "opacity") (if "" is n then "1" else n) cssNumber: columnCount: not 0 fillOpacity: not 0 fontWeight: not 0 lineHeight: not 0 opacity: not 0 orphans: not 0 widows: not 0 zIndex: not 0 zoom: not 0 cssProps: float: (if b.support.cssFloat then "cssFloat" else "styleFloat") style: (e, n, r, i) -> if e and 3 isnt e.nodeType and 8 isnt e.nodeType and e.style o = undefined a = undefined s = undefined u = b.camelCase(n) l = e.style return (if s and "get" of s and (o = s.get(e, not 1, i)) isnt t then o else l[n]) if n = b.cssProps[u] or (b.cssProps[u] = tn(l, u)) s = b.cssHooks[n] or b.cssHooks[u] r is t if a = typeof r "string" is a and (o = Jt.exec(r)) and (r = (o[1] + 1) * o[2] + parseFloat(b.css(e, n)) a = "number" ) not (null is r or "number" is a and isNaN(r) or ("number" isnt a or b.cssNumber[u] or (r += "px") b.support.clearCloneStyle or "" isnt r or 0 isnt n.indexOf("background") or (l[n] = "inherit") s and "set" of s and (r = s.set(e, r, i)) is t )) try l[n] = r css: (e, n, r, i) -> o = undefined a = undefined s = undefined u = b.camelCase(n) n = b.cssProps[u] or (b.cssProps[u] = tn(e.style, u)) s = b.cssHooks[n] or b.cssHooks[u] s and "get" of s and (a = s.get(e, not 0, r)) a is t and (a = Wt(e, n, i)) "normal" is a and n of Kt and (a = Kt[n]) (if "" is r or r then (o = parseFloat(a) (if r is not 0 or b.isNumeric(o) then o or 0 else a) ) else a) swap: (e, t, n, r) -> i = undefined o = undefined a = {} for o of t a[o] = e.style[o] e.style[o] = t[o] i = n.apply(e, r or []) for o of t e.style[o] = a[o] i ) (if e.getComputedStyle then (Rt = (t) -> e.getComputedStyle t, null Wt = (e, n, r) -> i = undefined o = undefined a = undefined s = r or Rt(e) u = (if s then s.getPropertyValue(n) or s[n] else t) l = e.style s and ("" isnt u or b.contains(e.ownerDocument, e) or (u = b.style(e, n)) Yt.test(u) and Ut.test(n) and (i = l.width o = l.minWidth a = l.maxWidth l.minWidth = l.maxWidth = l.width = u u = s.width l.width = i l.minWidth = o l.maxWidth = a ) ) u ) else o.documentElement.currentStyle and (Rt = (e) -> e.currentStyle Wt = (e, n, r) -> i = undefined o = undefined a = undefined s = r or Rt(e) u = (if s then s[n] else t) l = e.style null is u and l and l[n] and (u = l[n]) Yt.test(u) and not zt.test(n) and (i = l.left o = e.runtimeStyle a = o and o.left a and (o.left = e.currentStyle.left) l.left = (if "fontSize" is n then "1em" else u) u = l.pixelLeft + "px" l.left = i a and (o.left = a) ) (if "" is u then "auto" else u) )) b.each(["height", "width"], (e, n) -> b.cssHooks[n] = get: (e, r, i) -> (if r then (if 0 is e.offsetWidth and Xt.test(b.css(e, "display")) then b.swap(e, Qt, -> sn e, n, i ) else sn(e, n, i)) else t) set: (e, t, r) -> i = r and Rt(e) on_ e, t, (if r then an(e, n, r, b.support.boxSizing and "border-box" is b.css(e, "boxSizing", not 1, i), i) else 0) ) b.support.opacity or (b.cssHooks.opacity = get: (e, t) -> (if It.test(((if t and e.currentStyle then e.currentStyle.filter else e.style.filter)) or "") then .01 * parseFloat(RegExp.$1) + "" else (if t then "1" else "")) set: (e, t) -> n = e.style r = e.currentStyle i = (if b.isNumeric(t) then "alpha(opacity=" + 100 * t + ")" else "") o = r and r.filter or n.filter or "" n.zoom = 1 (t >= 1 or "" is t) and "" is b.trim(o.replace($t, "")) and n.removeAttribute and (n.removeAttribute("filter") "" is t or r and not r.filter ) or (n.filter = (if $t.test(o) then o.replace($t, i) else o + " " + i)) ) b(-> b.support.reliableMarginRight or (b.cssHooks.marginRight = get: (e, n) -> (if n then b.swap(e, display: "inline-block" , Wt, [e, "marginRight"]) else t) ) not b.support.pixelPosition and b.fn.position and b.each(["top", "left"], (e, n) -> b.cssHooks[n] = get: (e, r) -> (if r then (r = Wt(e, n) (if Yt.test(r) then b(e).position()[n] + "px" else r) ) else t) ) ) b.expr and b.expr.filters and (b.expr.filters.hidden = (e) -> 0 >= e.offsetWidth and 0 >= e.offsetHeight or not b.support.reliableHiddenOffsets and "none" is (e.style and e.style.display or b.css(e, "display")) b.expr.filters.visible = (e) -> not b.expr.filters.hidden(e) ) b.each( margin: "" padding: "" border: "Width" , (e, t) -> b.cssHooks[e + t] = expand: (n) -> r = 0 i = {} o = (if "string" is typeof n then n.split(" ") else [n]) while 4 > r i[e + Zt[r] + t] = o[r] or o[r - 2] or o[0] r++ i Ut.test(e) or (b.cssHooks[e + t].set = on_) ) cn = /%20/g pn = /\[\]$/ fn = /\r?\n/g dn = /^(?:submit|button|image|reset|file)$/i hn = /^(?:input|select|textarea|keygen)/i b.fn.extend( serialize: -> b.param @serializeArray() serializeArray: -> @map(-> e = b.prop(this, "elements") (if e then b.makeArray(e) else this) ).filter(-> e = @type @name and not b(this).is(":disabled") and hn.test(@nodeName) and not dn.test(e) and (@checked or not Nt.test(e)) ).map((e, t) -> n = b(this).val() (if null is n then null else (if b.isArray(n) then b.map(n, (e) -> name: t.name value: e.replace(fn, "\r\n") ) else name: t.name value: n.replace(fn, "\r\n") )) ).get() ) b.param = (e, n) -> r = undefined i = [] o = (e, t) -> t = (if b.isFunction(t) then t() else (if null is t then "" else t)) i[i.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t) if n is t and (n = b.ajaxSettings and b.ajaxSettings.traditional) b.isArray(e) or e.jquery and not b.isPlainObject(e) b.each e, -> o @name, @value else for r of e gn r, e[r], n, o i.join("&").replace cn, "+" b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "), (e, t) -> b.fn[t] = (e, n) -> (if arguments_.length > 0 then @on(t, null, e, n) else @trigger(t)) ) b.fn.hover = (e, t) -> @mouseenter(e).mouseleave t or e mn = undefined yn = undefined vn = b.now() bn = /\?/ xn = /#.*$/ wn = /([?&])_=[^&]*/ Tn = /^(.*?):[ \t]*([^\r\n]*)\r?$/g Nn = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/ Cn = /^(?:GET|HEAD)$/ kn = /^\/\// En = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/ Sn = b.fn.load An = {} jn = {} Dn = "*/".concat("*") try yn = a.href catch Ln yn = o.createElement("a") yn.href = "" yn = yn.href mn = En.exec(yn.toLowerCase()) or [] b.fn.load = (e, n, r) -> return Sn.apply(this, arguments_) if "string" isnt typeof e and Sn i = undefined o = undefined a = undefined s = this u = e.indexOf(" ") u >= 0 and (i = e.slice(u, e.length) e = e.slice(0, u) ) (if b.isFunction(n) then (r = n n = t ) else n and "object" is typeof n and (a = "POST")) s.length > 0 and b.ajax( url: e type: a dataType: "html" data: n ).done((e) -> o = arguments_ s.html((if i then b("<div>").append(b.parseHTML(e)).find(i) else e)) ).complete(r and (e, t) -> s.each r, o or [e.responseText, t, e] ) this b.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], (e, t) -> b.fn[t] = (e) -> @on t, e ) b.each(["get", "post"], (e, n) -> b[n] = (e, r, i, o) -> b.isFunction(r) and (o = o or i i = r r = t ) b.ajax( url: e type: n dataType: o data: r success: i ) ) b.extend( active: 0 lastModified: {} etag: {} ajaxSettings: url: yn type: "GET" isLocal: Nn.test(mn[1]) global: not 0 processData: not 0 async: not 0 contentType: "application/x-www-form-urlencoded; charset=UTF-8" accepts: "*": Dn text: "text/plain" html: "text/html" xml: "application/xml, text/xml" json: "application/json, text/javascript" contents: xml: /xml/ html: /html/ json: /json/ responseFields: xml: "responseXML" text: "responseText" converters: "* text": e.String "text html": not 0 "text json": b.parseJSON "text xml": b.parseXML flatOptions: url: not 0 context: not 0 ajaxSetup: (e, t) -> (if t then Mn(Mn(e, b.ajaxSettings), t) else Mn(b.ajaxSettings, e)) ajaxPrefilter: Hn(An) ajaxTransport: Hn(jn) ajax: (e, n) -> k = (e, n, r, i) -> c = undefined y = undefined v = undefined w = undefined T = undefined C = n 2 isnt x and (x = 2 s and clearTimeout(s) l = t a = i or "" N.readyState = (if e > 0 then 4 else 0) r and (w = _n(p, N, r)) (if e >= 200 and 300 > e or 304 is e then (p.ifModified and (T = N.getResponseHeader("Last-Modified") T and (b.lastModified[o] = T) T = N.getResponseHeader("etag") T and (b.etag[o] = T) ) (if 204 is e then (c = not 0 C = "nocontent" ) else (if 304 is e then (c = not 0 C = "notmodified" ) else (c = Fn(p, w) C = c.state y = c.data v = c.error c = not v ))) ) else (v = C (e or not C) and (C = "error" 0 > e and (e = 0) ) )) N.status = e N.statusText = (n or C) + "" (if c then h.resolveWith(f, [y, C, N]) else h.rejectWith(f, [N, C, v])) N.statusCode(m) m = t u and d.trigger((if c then "ajaxSuccess" else "ajaxError"), [N, p, (if c then y else v)]) g.fireWith(f, [N, C]) u and (d.trigger("ajaxComplete", [N, p]) --b.active or b.event.trigger("ajaxStop") ) ) "object" is typeof e and (n = e e = t ) n = n or {} r = undefined i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = b.ajaxSetup({}, n) f = p.context or p d = (if p.context and (f.nodeType or f.jquery) then b(f) else b.event) h = b.Deferred() g = b.Callbacks("once memory") m = p.statusCode or {} y = {} v = {} x = 0 T = "canceled" N = readyState: 0 getResponseHeader: (e) -> t = undefined if 2 is x unless c c = {} c[t[1].toLowerCase()] = t[2] while t = Tn.exec(a) t = c[e.toLowerCase()] (if null is t then null else t) getAllResponseHeaders: -> (if 2 is x then a else null) setRequestHeader: (e, t) -> n = e.toLowerCase() x or (e = v[n] = v[n] or e y[e] = t ) this overrideMimeType: (e) -> x or (p.mimeType = e) this statusCode: (e) -> t = undefined if e if 2 > x for t of e m[t] = [m[t], e[t]] else N.always e[N.status] this abort: (e) -> t = e or T l and l.abort(t) k(0, t) this return N if h.promise(N).complete = g.add N.success = N.done N.error = N.fail p.url = ((e or p.url or yn) + "").replace(xn, "").replace(kn, mn[1] + "//") p.type = n.method or n.type or p.method or p.type p.dataTypes = b.trim(p.dataType or "*").toLowerCase().match(w) or [""] null is p.crossDomain and (r = En.exec(p.url.toLowerCase()) p.crossDomain = not (not r or r[1] is mn[1] and r[2] is mn[2] and (r[3] or ((if "http:" is r[1] then 80 else 443))) is (mn[3] or ((if "http:" is mn[1] then 80 else 443)))) ) p.data and p.processData and "string" isnt typeof p.data and (p.data = b.param(p.data, p.traditional)) qn(An, p, n, N) 2 is x u = p.global u and 0 is b.active++ and b.event.trigger("ajaxStart") p.type = p.type.toUpperCase() p.hasContent = not Cn.test(p.type) o = p.url p.hasContent or (p.data and (o = p.url += ((if bn.test(o) then "&" else "?")) + p.data delete p.data ) p.cache is not 1 and (p.url = (if wn.test(o) then o.replace(wn, "$1_=" + vn++) else o + ((if bn.test(o) then "&" else "?")) + "_=" + vn++)) ) p.ifModified and (b.lastModified[o] and N.setRequestHeader("If-Modified-Since", b.lastModified[o]) b.etag[o] and N.setRequestHeader("If-None-Match", b.etag[o]) ) (p.data and p.hasContent and p.contentType isnt not 1 or n.contentType) and N.setRequestHeader("Content-Type", p.contentType) N.setRequestHeader("Accept", (if p.dataTypes[0] and p.accepts[p.dataTypes[0]] then p.accepts[p.dataTypes[0]] + ((if "*" isnt p.dataTypes[0] then ", " + Dn + "; q=0.01" else "")) else p.accepts["*"])) for i of p.headers N.setRequestHeader i, p.headers[i] return N.abort() if p.beforeSend and (p.beforeSend.call(f, N, p) is not 1 or 2 is x) T = "abort" for i of success: 1 error: 1 complete: 1 N[i] p[i] if l = qn(jn, p, n, N) N.readyState = 1 u and d.trigger("ajaxSend", [N, p]) p.async and p.timeout > 0 and (s = setTimeout(-> N.abort "timeout" , p.timeout)) try x = 1 l.send(y, k) catch C throw C unless 2 > x k -1, C else k -1, "No Transport" N getScript: (e, n) -> b.get e, t, n, "script" getJSON: (e, t, n) -> b.get e, t, n, "json" ) b.ajaxSetup( accepts: script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" contents: script: /(?:java|ecma)script/ converters: "text script": (e) -> b.globalEval(e) e ) b.ajaxPrefilter("script", (e) -> e.cache is t and (e.cache = not 1) e.crossDomain and (e.type = "GET" e.global = not 1 ) ) b.ajaxTransport("script", (e) -> if e.crossDomain n = undefined r = o.head or b("head")[0] or o.documentElement send: (t, i) -> n = o.createElement("script") n.async = not 0 e.scriptCharset and (n.charset = e.scriptCharset) n.src = e.url n.onload = n.onreadystatechange = (e, t) -> (t or not n.readyState or /loaded|complete/.test(n.readyState)) and (n.onload = n.onreadystatechange = null n.parentNode and n.parentNode.removeChild(n) n = null t or i(200, "success") ) r.insertBefore(n, r.firstChild) abort: -> n and n.onload(t, not 0) ) On = [] Bn = /(=)\?(?=&|$)|\?\?/ b.ajaxSetup( jsonp: "callback" jsonpCallback: -> e = On.pop() or b.expando + "_" + vn++ this[e] = not 0 e ) b.ajaxPrefilter("json jsonp", (n, r, i) -> o = undefined a = undefined s = undefined u = n.jsonp isnt not 1 and ((if Bn.test(n.url) then "url" else "string" is typeof n.data and not (n.contentType or "").indexOf("application/x-www-form-urlencoded") and Bn.test(n.data) and "data")) (if u or "jsonp" is n.dataTypes[0] then (o = n.jsonpCallback = (if b.isFunction(n.jsonpCallback) then n.jsonpCallback() else n.jsonpCallback) (if u then n[u] = n[u].replace(Bn, "$1" + o) else n.jsonp isnt not 1 and (n.url += ((if bn.test(n.url) then "&" else "?")) + n.jsonp + "=" + o)) n.converters["script json"] = -> s or b.error(o + " was not called") s[0] n.dataTypes[0] = "json" a = e[o] e[o] = -> s = arguments_ i.always(-> e[o] = a n[o] and (n.jsonpCallback = r.jsonpCallback On.push(o) ) s and b.isFunction(a) and a(s[0]) s = a = t ) "script" ) else t) ) Pn = undefined Rn = undefined Wn = 0 $n = e.ActiveXObject and -> e = undefined for e of Pn Pn[e] t, not 0 b.ajaxSettings.xhr = (if e.ActiveXObject then -> not @isLocal and In() or zn() else In) Rn = b.ajaxSettings.xhr() b.support.cors = !!Rn and "withCredentials" of Rn Rn = b.support.ajax = !!Rn Rn and b.ajaxTransport((n) -> if not n.crossDomain or b.support.cors r = undefined send: (i, o) -> a = undefined s = undefined u = n.xhr() if (if n.username then u.open(n.type, n.url, n.async, n.username, n.password) else u.open(n.type, n.url, n.async)) n.xhrFields for s of n.xhrFields u[s] = n.xhrFields[s] n.mimeType and u.overrideMimeType and u.overrideMimeType(n.mimeType) n.crossDomain or i["X-Requested-With"] or (i["X-Requested-With"] = "XMLHttpRequest") try for s of i u.setRequestHeader s, i[s] u.send(n.hasContent and n.data or null) r = (e, i) -> s = undefined l = undefined c = undefined p = undefined try if r and (i or 4 is u.readyState) unless r = t a and (u.onreadystatechange = b.noop $n and delete Pn[a] ) i p = {} s = u.status l = u.getAllResponseHeaders() "string" is typeof u.responseText and (p.text = u.responseText) try c = u.statusText catch f c = "" (if s or not n.isLocal or n.crossDomain then 1223 is s and (s = 204) else s = (if p.text then 200 else 404)) catch d i or o(-1, d) p and o(s, c, p, l) (if n.async then (if 4 is u.readyState then setTimeout(r) else (a = ++Wn $n and (Pn or (Pn = {} b(e).unload($n) ) Pn[a] = r ) u.onreadystatechange = r )) else r()) abort: -> r and r(t, not 0) ) Xn = undefined Un = undefined Vn = /^(?:toggle|show|hide)$/ Yn = RegExp("^(?:([+-])=|)(" + x + ")([a-z%]*)$", "i") Jn = /queueHooks$/ Gn = [nr] Qn = "*": [(e, t) -> n = undefined r = undefined i = @createTween(e, t) o = Yn.exec(t) a = i.cur() s = +a or 0 u = 1 l = 20 if o if n = +o[2] r = o[3] or ((if b.cssNumber[e] then "" else "px")) "px" isnt r and s s = b.css(i.elem, e, not 0) or n or 1 loop u = u or ".5" s /= u b.style(i.elem, e, s + r) break unless u isnt (u = i.cur() / a) and 1 isnt u and --l i.unit = r i.start = s i.end = (if o[1] then s + (o[1] + 1) * n else n) i ] b.Animation = b.extend(er, tweener: (e, t) -> (if b.isFunction(e) then (t = e e = ["*"] ) else e = e.split(" ")) n = undefined r = 0 i = e.length while i > r n = e[r] Qn[n] = Qn[n] or [] Qn[n].unshift(t) r++ prefilter: (e, t) -> (if t then Gn.unshift(e) else Gn.push(e)) ) b.Tween = rr rr:: = constructor: rr init: (e, t, n, r, i, o) -> @elem = e @prop = n @easing = i or "swing" @options = t @start = @now = @cur() @end = r @unit = o or ((if b.cssNumber[n] then "" else "px")) cur: -> e = rr.propHooks[@prop] (if e and e.get then e.get(this) else rr.propHooks._default.get(this)) run: (e) -> t = undefined n = rr.propHooks[@prop] @pos = t = (if @options.duration then b.easing[@easing](e, @options.duration * e, 0, 1, @options.duration) else e) @now = (@end - @start) * t + @start @options.step and @options.step.call(@elem, @now, this) (if n and n.set then n.set(this) else rr.propHooks._default.set(this)) this rr::init:: = rr:: rr.propHooks = _default: get: (e) -> t = undefined (if null is e.elem[e.prop] or e.elem.style and null isnt e.elem.style[e.prop] then (t = b.css(e.elem, e.prop, "") (if t and "auto" isnt t then t else 0) ) else e.elem[e.prop]) set: (e) -> (if b.fx.step[e.prop] then b.fx.step[e.prop](e) else (if e.elem.style and (null isnt e.elem.style[b.cssProps[e.prop]] or b.cssHooks[e.prop]) then b.style(e.elem, e.prop, e.now + e.unit) else e.elem[e.prop] = e.now)) rr.propHooks.scrollTop = rr.propHooks.scrollLeft = set: (e) -> e.elem.nodeType and e.elem.parentNode and (e.elem[e.prop] = e.now) b.each(["toggle", "show", "hide"], (e, t) -> n = b.fn[t] b.fn[t] = (e, r, i) -> (if null is e or "boolean" is typeof e then n.apply(this, arguments_) else @animate(ir(t, not 0), e, r, i)) ) b.fn.extend( fadeTo: (e, t, n, r) -> @filter(nn).css("opacity", 0).show().end().animate opacity: t , e, n, r animate: (e, t, n, r) -> i = b.isEmptyObject(e) o = b.speed(t, n, r) a = -> t = er(this, b.extend({}, e), o) a.finish = -> t.stop not 0 (i or b._data(this, "finish")) and t.stop(not 0) a.finish = a (if i or o.queue is not 1 then @each(a) else @queue(o.queue, a)) stop: (e, n, r) -> i = (e) -> t = e.stop delete e.stop t(r) "string" isnt typeof e and (r = n n = e e = t ) n and e isnt not 1 and @queue(e or "fx", []) @each(-> t = not 0 n = null isnt e and e + "queueHooks" o = b.timers a = b._data(this) if n a[n] and a[n].stop and i(a[n]) else for n of a a[n] and a[n].stop and Jn.test(n) and i(a[n]) n = o.length while n-- o[n].elem isnt this or null isnt e and o[n].queue isnt e or (o[n].anim.stop(r) t = not 1 o.splice(n, 1) ) (t or not r) and b.dequeue(this, e) ) finish: (e) -> e isnt not 1 and (e = e or "fx") @each(-> t = undefined n = b._data(this) r = n[e + "queue"] i = n[e + "queueHooks"] o = b.timers a = (if r then r.length else 0) n.finish = not 0 b.queue(this, e, []) i and i.cur and i.cur.finish and i.cur.finish.call(this) t = o.length while t-- o[t].elem is this and o[t].queue is e and (o[t].anim.stop(not 0) o.splice(t, 1) ) t = 0 while a > t r[t] and r[t].finish and r[t].finish.call(this) t++ delete n.finish ) ) b.each( slideDown: ir("show") slideUp: ir("hide") slideToggle: ir("toggle") fadeIn: opacity: "show" fadeOut: opacity: "hide" fadeToggle: opacity: "toggle" , (e, t) -> b.fn[e] = (e, n, r) -> @animate t, e, n, r ) b.speed = (e, t, n) -> r = (if e and "object" is typeof e then b.extend({}, e) else complete: n or not n and t or b.isFunction(e) and e duration: e easing: n and t or t and not b.isFunction(t) and t ) r.duration = (if b.fx.off then 0 else (if "number" is typeof r.duration then r.duration else (if r.duration of b.fx.speeds then b.fx.speeds[r.duration] else b.fx.speeds._default))) (null is r.queue or r.queue is not 0) and (r.queue = "fx") r.old = r.complete r.complete = -> b.isFunction(r.old) and r.old.call(this) r.queue and b.dequeue(this, r.queue) r b.easing = linear: (e) -> e swing: (e) -> .5 - Math.cos(e * Math.PI) / 2 b.timers = [] b.fx = rr::init b.fx.tick = -> e = undefined n = b.timers r = 0 Xn = b.now() while n.length > r e = n[r] e() or n[r] isnt e or n.splice(r--, 1) r++ n.length or b.fx.stop() Xn = t b.fx.timer = (e) -> e() and b.timers.push(e) and b.fx.start() b.fx.interval = 13 b.fx.start = -> Un or (Un = setInterval(b.fx.tick, b.fx.interval)) b.fx.stop = -> clearInterval(Un) Un = null b.fx.speeds = slow: 600 fast: 200 _default: 400 b.fx.step = {} b.expr and b.expr.filters and (b.expr.filters.animated = (e) -> b.grep(b.timers, (t) -> e is t.elem ).length ) b.fn.offset = (e) -> if arguments_.length return (if e is t then this else @each((t) -> b.offset.setOffset this, e, t )) n = undefined r = undefined o = top: 0 left: 0 a = this[0] s = a and a.ownerDocument if s n = s.documentElement (if b.contains(n, a) then (typeof a.getBoundingClientRect isnt i and (o = a.getBoundingClientRect()) r = or_(s) top: o.top + (r.pageYOffset or n.scrollTop) - (n.clientTop or 0) left: o.left + (r.pageXOffset or n.scrollLeft) - (n.clientLeft or 0) ) else o) b.offset = setOffset: (e, t, n) -> r = b.css(e, "position") "static" is r and (e.style.position = "relative") i = b(e) o = i.offset() a = b.css(e, "top") s = b.css(e, "left") u = ("absolute" is r or "fixed" is r) and b.inArray("auto", [a, s]) > -1 l = {} c = {} p = undefined f = undefined (if u then (c = i.position() p = c.top f = c.left ) else (p = parseFloat(a) or 0 f = parseFloat(s) or 0 )) b.isFunction(t) and (t = t.call(e, n, o)) null isnt t.top and (l.top = t.top - o.top + p) null isnt t.left and (l.left = t.left - o.left + f) (if "using" of t then t.using.call(e, l) else i.css(l)) b.fn.extend( position: -> if this[0] e = undefined t = undefined n = top: 0 left: 0 r = this[0] (if "fixed" is b.css(r, "position") then t = r.getBoundingClientRect() else (e = @offsetParent() t = @offset() b.nodeName(e[0], "html") or (n = e.offset()) n.top += b.css(e[0], "borderTopWidth", not 0) n.left += b.css(e[0], "borderLeftWidth", not 0) )) top: t.top - n.top - b.css(r, "marginTop", not 0) left: t.left - n.left - b.css(r, "marginLeft", not 0) offsetParent: -> @map -> e = @offsetParent or o.documentElement e = e.offsetParent while e and not b.nodeName(e, "html") and "static" is b.css(e, "position") e or o.documentElement ) b.each( scrollLeft: "pageXOffset" scrollTop: "pageYOffset" , (e, n) -> r = /Y/.test(n) b.fn[e] = (i) -> b.access this, ((e, i, o) -> a = or_(e) (if o is t then (if a then (if n of a then a[n] else a.document.documentElement[i]) else e[i]) else ((if a then a.scrollTo((if r then b(a).scrollLeft() else o), (if r then o else b(a).scrollTop())) else e[i] = o) t )) ), e, i, arguments_.length, null ) b.each( Height: "height" Width: "width" , (e, n) -> b.each padding: "inner" + e content: n "": "outer" + e , (r, i) -> b.fn[i] = (i, o) -> a = arguments_.length and (r or "boolean" isnt typeof i) s = r or ((if i is not 0 or o is not 0 then "margin" else "border")) b.access this, ((n, r, i) -> o = undefined (if b.isWindow(n) then n.document.documentElement["client" + e] else (if 9 is n.nodeType then (o = n.documentElement Math.max(n.body["scroll" + e], o["scroll" + e], n.body["offset" + e], o["offset" + e], o["client" + e]) ) else (if i is t then b.css(n, r, s) else b.style(n, r, i, s)))) ), n, (if a then i else t), a, null ) e.jQuery = e.$ = b "function" is typeof define and define.amd and define.amd.jQuery and define("jquery", [], -> b ) ) window
83031
#! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license # ((e, t) -> M = (e) -> t = e.length n = b.type(e) (if b.isWindow(e) then not 1 else (if 1 is e.nodeType and t then not 0 else "array" is n or "function" isnt n and (0 is t or "number" is typeof t and t > 0 and t - 1 of e))) F = (e) -> t = _[e] = {} b.each(e.match(w) or [], (e, n) -> t[n] = not 0 ) t P = (e, n, r, i) -> if b.acceptData(e) o = undefined a = undefined s = b.expando u = "string" is typeof n l = e.nodeType p = (if l then b.cache else e) f = (if l then e[s] else e[s] and s) if f and p[f] and (i or p[f].data) or not u or r isnt t f or ((if l then e[s] = f = c.pop() or b.guid++ else f = s)) p[f] or (p[f] = {} l or (p[f].toJSON = b.noop) ) ("object" is typeof n or "function" is typeof n) and ((if i then p[f] = b.extend(p[f], n) else p[f].data = b.extend(p[f].data, n))) o = p[f] i or (o.data or (o.data = {}) o = o.data ) r isnt t and (o[b.camelCase(n)] = r) (if u then (a = o[n] null is a and (a = o[b.camelCase(n)]) ) else a = o) a R = (e, t, n) -> if b.acceptData(e) r = undefined i = undefined o = undefined a = e.nodeType s = (if a then b.cache else e) u = (if a then e[b.expando] else b.expando) if s[u] if t and (o = (if n then s[u] else s[u].data)) (if b.isArray(t) then t = t.concat(b.map(t, b.camelCase)) else (if t of o then t = [t] else (t = b.camelCase(t) t = (if t of o then [t] else t.split(" ")) ))) r = 0 i = t.length while i > r delete o[t[r]] r++ return unless ((if n then $ else b.isEmptyObject))(o) (n or (delete s[u].data $(s[u]) )) and ((if a then b.cleanData([e], not 0) else (if b.support.deleteExpando or s isnt s.window then delete s[u] else s[u] = null))) W = (e, n, r) -> if r is t and 1 is e.nodeType i = "data-" + n.replace(B, "-$1").toLowerCase() if r = e.getAttribute(i) "string" is typeof r try r = (if "true" is r then not 0 else (if "false" is r then not 1 else (if "null" is r then null else (if +r + "" is r then +r else (if O.test(r) then b.parseJSON(r) else r))))) b.data e, n, r else r = t r $ = (e) -> t = undefined for t of e return not 1 if ("data" isnt t or not b.isEmptyObject(e[t])) and "toJSON" isnt t not 0 it = -> not 0 ot = -> not 1 pt = (e, t) -> loop e = e[t] break unless e and 1 isnt e.nodeType e ft = (e, t, n) -> if t = t or 0 b.isFunction(t) return b.grep(e, (e, r) -> i = !!t.call(e, r, e) i is n ) if t.nodeType return b.grep(e, (e) -> e is t is n ) if "string" is typeof t r = b.grep(e, (e) -> 1 is e.nodeType ) return b.filter(t, r, not n) if ut.test(t) t = b.filter(t, r) b.grep e, (e) -> b.inArray(e, t) >= 0 is n dt = (e) -> t = ht.split("|") n = e.createDocumentFragment() n.createElement t.pop() while t.length if n.createElement n Lt = (e, t) -> e.getElementsByTagName(t)[0] or e.appendChild(e.ownerDocument.createElement(t)) Ht = (e) -> t = e.getAttributeNode("type") e.type = (t and t.specified) + "/" + e.type e qt = (e) -> t = Et.exec(e.type) (if t then e.type = t[1] else e.removeAttribute("type")) e Mt = (e, t) -> n = undefined r = 0 while null isnt (n = e[r]) b._data n, "globalEval", not t or b._data(t[r], "globalEval") r++ _t = (e, t) -> if 1 is t.nodeType and b.hasData(e) n = undefined r = undefined i = undefined o = b._data(e) a = b._data(t, o) s = o.events if s delete a.handle a.events = {} for n of s r = 0 i = s[n].length while i > r b.event.add t, n, s[n][r] r++ a.data and (a.data = b.extend({}, a.data)) Ft = (e, t) -> n = undefined r = undefined i = undefined if 1 is t.nodeType if n = t.nodeName.toLowerCase() not b.support.noCloneEvent and t[b.expando] i = b._data(t) for r of i.events b.removeEvent t, r, i.handle t.removeAttribute b.expando (if "script" is n and t.text isnt e.text then (Ht(t).text = e.text qt(t) ) else (if "object" is n then (t.parentNode and (t.outerHTML = e.outerHTML) b.support.html5Clone and e.innerHTML and not b.trim(t.innerHTML) and (t.innerHTML = e.innerHTML) ) else (if "input" is n and Nt.test(e.type) then (t.defaultChecked = t.checked = e.checked t.value isnt e.value and (t.value = e.value) ) else (if "option" is n then t.defaultSelected = t.selected = e.defaultSelected else ("input" is n or "textarea" is n) and (t.defaultValue = e.defaultValue))))) Ot = (e, n) -> r = undefined o = undefined a = 0 s = (if typeof e.getElementsByTagName isnt i then e.getElementsByTagName(n or "*") else (if typeof e.querySelectorAll isnt i then e.querySelectorAll(n or "*") else t)) unless s s = [] r = e.childNodes or e while null isnt (o = r[a]) (if not n or b.nodeName(o, n) then s.push(o) else b.merge(s, Ot(o, n))) a++ (if n is t or n and b.nodeName(e, n) then b.merge([e], s) else s) Bt = (e) -> Nt.test(e.type) and (e.defaultChecked = e.checked) tn = (e, t) -> return t if t of e n = t.charAt(0).toUpperCase() + t.slice(1) r = t i = en.length while i-- return t if t = en[i] + n t of e r nn = (e, t) -> e = t or e "none" is b.css(e, "display") or not b.contains(e.ownerDocument, e) rn = (e, t) -> n = undefined r = undefined i = undefined o = [] a = 0 s = e.length while s > a r = e[a] r.style and (o[a] = b._data(r, "olddisplay") n = r.style.display (if t then (o[a] or "none" isnt n or (r.style.display = "") "" is r.style.display and nn(r) and (o[a] = b._data(r, "olddisplay", un(r.nodeName))) ) else o[a] or (i = nn(r) (n and "none" isnt n or not i) and b._data(r, "olddisplay", (if i then n else b.css(r, "display"))) )) ) a++ a = 0 while s > a r = e[a] r.style and (t and "none" isnt r.style.display and "" isnt r.style.display or (r.style.display = (if t then o[a] or "" else "none"))) a++ e on = (e, t, n) -> r = Vt.exec(t) (if r then Math.max(0, r[1] - (n or 0)) + (r[2] or "px") else t) an = (e, t, n, r, i) -> o = (if n is ((if r then "border" else "content")) then 4 else (if "width" is t then 1 else 0)) a = 0 while 4 > o "margin" is n and (a += b.css(e, n + Zt[o], not 0, i)) (if r then ("content" is n and (a -= b.css(e, "padding" + Zt[o], not 0, i)) "margin" isnt n and (a -= b.css(e, "border" + Zt[o] + "Width", not 0, i)) ) else (a += b.css(e, "padding" + Zt[o], not 0, i) "padding" isnt n and (a += b.css(e, "border" + Zt[o] + "Width", not 0, i)) )) o += 2 a sn = (e, t, n) -> r = not 0 i = (if "width" is t then e.offsetWidth else e.offsetHeight) o = Rt(e) a = b.support.boxSizing and "border-box" is b.css(e, "boxSizing", not 1, o) if 0 >= i or null is i return i if i = Wt(e, t, o) (0 > i or null is i) and (i = e.style[t]) Yt.test(i) r = a and (b.support.boxSizingReliable or i is e.style[t]) i = parseFloat(i) or 0 i + an(e, t, n or ((if a then "border" else "content")), r, o) + "px" un = (e) -> t = o n = Gt[e] n or (n = ln(e, t) "none" isnt n and n or (Pt = (Pt or b("<iframe frameborder='0' width='0' height='0'/>").css("cssText", "display:block !important")).appendTo(t.documentElement) t = (Pt[0].contentWindow or Pt[0].contentDocument).document t.write("<!doctype html><html><body>") t.close() n = ln(e, t) Pt.detach() ) Gt[e] = n ) n ln = (e, t) -> n = b(t.createElement(e)).appendTo(t.body) r = b.css(n[0], "display") n.remove() r gn = (e, t, n, r) -> i = undefined if b.isArray(t) b.each t, (t, i) -> (if n or pn.test(e) then r(e, i) else gn(e + "[" + ((if "object" is typeof i then t else "")) + "]", i, n, r)) else if n or "object" isnt b.type(t) r e, t else for i of t gn e + "[" + i + "]", t[i], n, r Hn = (e) -> (t, n) -> "string" isnt typeof t and (n = t t = "*" ) r = undefined i = 0 o = t.toLowerCase().match(w) or [] if b.isFunction(n) while r = o[i++] (if "+" is r[0] then (r = r.slice(1) or "*" (e[r] = e[r] or []).unshift(n) ) else (e[r] = e[r] or []).push(n)) qn = (e, n, r, i) -> s = (u) -> l = undefined o[u] = not 0 b.each(e[u] or [], (e, u) -> c = u(n, r, i) (if "string" isnt typeof c or a or o[c] then (if a then not (l = c) else t) else (n.dataTypes.unshift(c) s(c) not 1 )) ) l o = {} a = e is jn s(n.dataTypes[0]) or not o["*"] and s("*") Mn = (e, n) -> r = undefined i = undefined o = b.ajaxSettings.flatOptions or {} for i of n n[i] isnt t and (((if o[i] then e else r or (r = {})))[i] = n[i]) r and b.extend(not 0, e, r) e _n = (e, n, r) -> i = undefined o = undefined a = undefined s = undefined u = e.contents l = e.dataTypes c = e.responseFields for s of c s of r and (n[c[s]] = r[s]) while "*" is l[0] l.shift() o is t and (o = e.mimeType or n.getResponseHeader("Content-Type")) if o for s of u if u[s] and u[s].test(o) l.unshift s break unless l[0] of r for s of r if not l[0] or e.converters[s + " " + l[0]] a = s break i or (i = s) a = a or i (if a then (a isnt l[0] and l.unshift(a) r[a] ) else t) Fn = (e, t) -> n = undefined r = undefined i = undefined o = undefined a = {} s = 0 u = e.dataTypes.slice() l = u[0] if e.dataFilter and (t = e.dataFilter(t, e.dataType)) u[1] for i of e.converters a[i.toLowerCase()] = e.converters[i] while r = u[++s] if "*" isnt r if "*" isnt l and l isnt r if i = a[l + " " + r] or a["* " + r] not i for n of a if o = n.split(" ") o[1] is r and (i = a[l + " " + o[0]] or a["* " + o[0]]) (if i is not 0 then i = a[n] else a[n] isnt not 0 and (r = o[0] u.splice(s--, 0, r) )) break if i isnt not 0 if i and e["throws"] t = i(t) else try t = i(t) catch c return ( state: "parsererror" error: (if i then c else "No conversion from " + l + " to " + r) ) l = r state: "success" data: t In = -> try return new e.XMLHttpRequest zn = -> try return new e.ActiveXObject("Microsoft.XMLHTTP") Kn = -> setTimeout(-> Xn = t ) Xn = b.now() Zn = (e, t) -> b.each t, (t, n) -> r = (Qn[t] or []).concat(Qn["*"]) i = 0 o = r.length while o > i return if r[i].call(e, t, n) i++ er = (e, t, n) -> r = undefined i = undefined o = 0 a = Gn.length s = b.Deferred().always(-> delete u.elem ) u = -> return not 1 if i t = Xn or Kn() n = Math.max(0, l.startTime + l.duration - t) r = n / l.duration or 0 o = 1 - r a = 0 u = l.tweens.length while u > a l.tweens[a].run o a++ s.notifyWith(e, [l, o, n]) (if 1 > o and u then n else (s.resolveWith(e, [l]) not 1 )) l = s.promise( elem: e props: b.extend({}, t) opts: b.extend(not 0, specialEasing: {} , n) originalProperties: t originalOptions: n startTime: Xn or Kn() duration: n.duration tweens: [] createTween: (t, n) -> r = b.Tween(e, l.opts, t, n, l.opts.specialEasing[t] or l.opts.easing) l.tweens.push(r) r stop: (t) -> n = 0 r = (if t then l.tweens.length else 0) return this if i i = not 0 while r > n l.tweens[n].run 1 n++ (if t then s.resolveWith(e, [l, t]) else s.rejectWith(e, [l, t])) this ) c = l.props tr(c, l.opts.specialEasing) while a > o return r if r = Gn[o].call(l, e, c, l.opts) o++ Zn(l, c) b.isFunction(l.opts.start) and l.opts.start.call(e, l) b.fx.timer(b.extend(u, elem: e anim: l queue: l.opts.queue )) l.progress(l.opts.progress).done(l.opts.done, l.opts.complete).fail(l.opts.fail).always(l.opts.always) tr = (e, t) -> n = undefined r = undefined i = undefined o = undefined a = undefined for i of e if r = b.camelCase(i) o = t[r] n = e[i] b.isArray(n) and (o = n[1] n = e[i] = n[0] ) i isnt r and (e[r] = n delete e[i] ) a = b.cssHooks[r] a and "expand" of a n = a.expand(n) delete e[r] for i of n i of e or (e[i] = n[i] t[i] = o ) else t[r] = o nr = (e, t, n) -> r = undefined i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = undefined f = this d = e.style h = {} g = [] m = e.nodeType and nn(e) n.queue or (c = b._queueHooks(e, "fx") null is c.unqueued and (c.unqueued = 0 p = c.empty.fire c.empty.fire = -> c.unqueued or p() ) c.unqueued++ f.always(-> f.always -> c.unqueued-- b.queue(e, "fx").length or c.empty.fire() ) ) 1 is e.nodeType and ("height" of t or "width" of t) and (n.overflow = [d.overflow, d.overflowX, d.overflowY] "inline" is b.css(e, "display") and "none" is b.css(e, "float") and ((if b.support.inlineBlockNeedsLayout and "inline" isnt un(e.nodeName) then d.zoom = 1 else d.display = "inline-block")) ) n.overflow and (d.overflow = "hidden" b.support.shrinkWrapBlocks or f.always(-> d.overflow = n.overflow[0] d.overflowX = n.overflow[1] d.overflowY = n.overflow[2] ) ) for i of t if a = t[i] Vn.exec(a) continue if delete t[i] u = u or "toggle" is a a is ((if m then "hide" else "show")) g.push i if o = g.length s = b._data(e, "fxshow") or b._data(e, "fxshow", {}) "hidden" of s and (m = s.hidden) u and (s.hidden = not m) (if m then b(e).show() else f.done(-> b(e).hide() )) f.done(-> t = undefined b._removeData e, "fxshow" for t of h b.style e, t, h[t] ) i = 0 while o > i r = g[i] l = f.createTween(r, (if m then s[r] else 0)) h[r] = s[r] or b.style(e, r) r of s or (s[r] = l.start m and (l.end = l.start l.start = (if "width" is r or "height" is r then 1 else 0) ) ) i++ rr = (e, t, n, r, i) -> new rr::init(e, t, n, r, i) ir = (e, t) -> n = undefined r = height: e i = 0 t = (if t then 1 else 0) while 4 > i n = Zt[i] r["margin" + n] = r["padding" + n] = e i += 2 - t t and (r.opacity = r.width = e) r or = (e) -> (if b.isWindow(e) then e else (if 9 is e.nodeType then e.defaultView or e.parentWindow else not 1)) n = undefined r = undefined i = typeof t o = e.document a = e.location s = e.jQuery u = e.$ l = {} c = [] p = "1.9.1" f = c.concat d = c.push h = c.slice g = c.indexOf m = l.toString y = l.hasOwnProperty v = p.trim b = (e, t) -> new b.fn.init(e, t, r) x = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source w = /\S+/g T = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g N = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/ C = /^<(\w+)\s*\/?>(?:<\/\1>|)$/ k = /^[\],:{}\s]*$/ E = /(?:^|:|,)(?:\s*\[)+/g S = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g A = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g j = /^-ms-/ D = /-([\da-z])/g L = (e, t) -> t.toUpperCase() H = (e) -> (o.addEventListener or "load" is e.type or "complete" is o.readyState) and (q() b.ready() ) q = -> (if o.addEventListener then (o.removeEventListener("DOMContentLoaded", H, not 1) e.removeEventListener("load", H, not 1) ) else (o.detachEvent("onreadystatechange", H) e.detachEvent("onload", H) )) b.fn = b:: = jquery: p constructor: b init: (e, n, r) -> i = undefined a = undefined return this unless e if "string" is typeof e return (if not n or n.jquery then (n or r).find(e) else @constructor(n).find(e)) if i = (if "<" is e.charAt(0) and ">" is e.charAt(e.length - 1) and e.length >= 3 then [null, e, null] else N.exec(e)) not i or not i[1] and n if i[1] if n = (if n instanceof b then n[0] else n) b.merge(this, b.parseHTML(i[1], (if n and n.nodeType then n.ownerDocument or n else o), not 0)) C.test(i[1]) and b.isPlainObject(n) for i of n (if b.isFunction(this[i]) then this[i](n[i]) else @attr(i, n[i])) return this if a = o.getElementById(i[2]) a and a.parentNode return r.find(e) if a.id isnt i[2] @length = 1 this[0] = a return @context = o @selector = e this (if e.nodeType then (@context = this[0] = e @length = 1 this ) else (if b.isFunction(e) then r.ready(e) else (e.selector isnt t and (@selector = e.selector @context = e.context ) b.makeArray(e, this) ))) selector: "" length: 0 size: -> @length toArray: -> h.call this get: (e) -> (if null is e then @toArray() else (if 0 > e then this[@length + e] else this[e])) pushStack: (e) -> t = b.merge(@constructor(), e) t.prevObject = this t.context = @context t each: (e, t) -> b.each this, e, t ready: (e) -> b.ready.promise().done(e) this slice: -> @pushStack h.apply(this, arguments_) first: -> @eq 0 last: -> @eq -1 eq: (e) -> t = @length n = +e + ((if 0 > e then t else 0)) @pushStack (if n >= 0 and t > n then [this[n]] else []) map: (e) -> @pushStack b.map(this, (t, n) -> e.call t, n, t ) end: -> @prevObject or @constructor(null) push: d sort: [].sort splice: [].splice b.fn.init:: = b.fn b.extend = b.fn.extend = -> e = undefined n = undefined r = undefined i = undefined o = undefined a = undefined s = arguments_[0] or {} u = 1 l = arguments_.length c = not 1 "boolean" is typeof s and (c = s s = arguments_[1] or {} u = 2 ) "object" is typeof s or b.isFunction(s) or (s = {}) l is u and (s = this --u ) while l > u unless null is (o = arguments_[u]) for i of o e = s[i] r = o[i] s isnt r and ((if c and r and (b.isPlainObject(r) or (n = b.isArray(r))) then ((if n then (n = not 1 a = (if e and b.isArray(e) then e else []) ) else a = (if e and b.isPlainObject(e) then e else {})) s[i] = b.extend(c, a, r) ) else r isnt t and (s[i] = r))) u++ s b.extend( noConflict: (t) -> e.$ is b and (e.$ = u) t and e.jQuery is b and (e.jQuery = s) b isReady: not 1 readyWait: 1 holdReady: (e) -> (if e then b.readyWait++ else b.ready(not 0)) ready: (e) -> if (if e is not 0 then not --b.readyWait else not b.isReady) return setTimeout(b.ready) unless o.body b.isReady = not 0 e isnt not 0 and --b.readyWait > 0 or (n.resolveWith(o, [b]) b.fn.trigger and b(o).trigger("ready").off("ready") ) isFunction: (e) -> "function" is b.type(e) isArray: Array.isArray or (e) -> "array" is b.type(e) isWindow: (e) -> null isnt e and e is e.window isNumeric: (e) -> not isNaN(parseFloat(e)) and isFinite(e) type: (e) -> (if null is e then e + "" else (if "object" is typeof e or "function" is typeof e then l[m.call(e)] or "object" else typeof e)) isPlainObject: (e) -> return not 1 if not e or "object" isnt b.type(e) or e.nodeType or b.isWindow(e) try return not 1 if e.constructor and not y.call(e, "constructor") and not y.call(e.constructor::, "isPrototypeOf") catch n return not 1 r = undefined for r of e r is t or y.call(e, r) isEmptyObject: (e) -> t = undefined for t of e return not 1 not 0 error: (e) -> throw Error(e) parseHTML: (e, t, n) -> return null if not e or "string" isnt typeof e "boolean" is typeof t and (n = t t = not 1 ) t = t or o r = C.exec(e) i = not n and [] (if r then [t.createElement(r[1])] else (r = b.buildFragment([e], t, i) i and b(i).remove() b.merge([], r.childNodes) )) parseJSON: (n) -> (if e.JSON and e.JSON.parse then e.JSON.parse(n) else (if null is n then n else (if "string" is typeof n and (n = b.trim(n) n and k.test(n.replace(S, "@").replace(A, "]").replace(E, "")) ) then Function("return " + n)() else (b.error("Invalid JSON: " + n) t )))) parseXML: (n) -> r = undefined i = undefined return null if not n or "string" isnt typeof n try (if e.DOMParser then (i = new DOMParser r = i.parseFromString(n, "text/xml") ) else (r = new ActiveXObject("Microsoft.XMLDOM") r.async = "false" r.loadXML(n) )) catch o r = t r and r.documentElement and not r.getElementsByTagName("parsererror").length or b.error("Invalid XML: " + n) r noop: -> globalEval: (t) -> t and b.trim(t) and (e.execScript or (t) -> e.eval.call e, t )(t) camelCase: (e) -> e.replace(j, "ms-").replace D, L nodeName: (e, t) -> e.nodeName and e.nodeName.toLowerCase() is t.toLowerCase() each: (e, t, n) -> r = undefined i = 0 o = e.length a = M(e) if n if a while o > i break if r = t.apply(e[i], n) r is not 1 i++ else for i of e break if r = t.apply(e[i], n) r is not 1 else if a while o > i break if r = t.call(e[i], i, e[i]) r is not 1 i++ else for i of e break if r = t.call(e[i], i, e[i]) r is not 1 e trim: (if v and not v.call(" ") then (e) -> (if null is e then "" else v.call(e)) else (e) -> (if null is e then "" else (e + "").replace(T, "")) ) makeArray: (e, t) -> n = t or [] null isnt e and ((if M(Object(e)) then b.merge(n, (if "string" is typeof e then [e] else e)) else d.call(n, e))) n inArray: (e, t, n) -> r = undefined if t return g.call(t, e, n) if g r = t.length n = (if n then (if 0 > n then Math.max(0, r + n) else n) else 0) while r > n return n if n of t and t[n] is e n++ -1 merge: (e, n) -> r = n.length i = e.length o = 0 if "number" is typeof r while r > o e[i++] = n[o] o++ else e[i++] = n[o++] while n[o] isnt t e.length = i e grep: (e, t, n) -> r = undefined i = [] o = 0 a = e.length n = !!n while a > o r = !!t(e[o], o) n isnt r and i.push(e[o]) o++ i map: (e, t, n) -> r = undefined i = 0 o = e.length a = M(e) s = [] if a while o > i r = t(e[i], i, n) null isnt r and (s[s.length] = r) i++ else for i of e r = t(e[i], i, n) null isnt r and (s[s.length] = r) f.apply [], s guid: 1 proxy: (e, n) -> r = undefined i = undefined o = undefined "string" is typeof n and (o = e[n] n = e e = o ) (if b.isFunction(e) then (r = h.call(arguments_, 2) i = -> e.apply n or this, r.concat(h.call(arguments_)) i.guid = e.guid = e.guid or b.guid++ i ) else t) access: (e, n, r, i, o, a, s) -> u = 0 l = e.length c = null is r if "object" is b.type(r) o = not 0 for u of r b.access e, n, u, r[u], not 0, a, s else if i isnt t and (o = not 0 b.isFunction(i) or (s = not 0) c and ((if s then (n.call(e, i) n = null ) else (c = n n = (e, t, n) -> c.call b(e), n ))) n ) while l > u n e[u], r, (if s then i else i.call(e[u], u, n(e[u], r))) u++ (if o then e else (if c then n.call(e) else (if l then n(e[0], r) else a))) now: -> (new Date).getTime() ) b.ready.promise = (t) -> unless n if n = b.Deferred() "complete" is o.readyState setTimeout b.ready else unless o.addEventListener o.attachEvent("onreadystatechange", H) e.attachEvent("onload", H) r = not 1 try r = null is e.frameElement and o.documentElement r and r.doScroll and a = -> unless b.isReady try r.doScroll "left" catch e return setTimeout(a, 50) q() b.ready() () n.promise t b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), (e, t) -> l["[object " + t + "]"] = t.toLowerCase() ) r = b(o) _ = {} b.Callbacks = (e) -> e = (if "string" is typeof e then _[e] or F(e) else b.extend({}, e)) n = undefined r = undefined i = undefined o = undefined a = undefined s = undefined u = [] l = not e.once and [] c = (t) -> r = e.memory and t i = not 0 a = s or 0 s = 0 o = u.length n = not 0 while u and o > a if u[a].apply(t[0], t[1]) is not 1 and e.stopOnFalse r = not 1 break a++ n = not 1 u and ((if l then l.length and c(l.shift()) else (if r then u = [] else p.disable()))) p = add: -> if u t = u.length (i = (t) -> b.each t, (t, n) -> r = b.type(n) (if "function" is r then e.unique and p.has(n) or u.push(n) else n and n.length and "string" isnt r and i(n)) )(arguments_) (if n then o = u.length else r and (s = t c(r) )) this remove: -> u and b.each(arguments_, (e, t) -> r = undefined while (r = b.inArray(t, u, r)) > -1 u.splice(r, 1) n and (o >= r and o-- a >= r and a-- ) ) this has: (e) -> (if e then b.inArray(e, u) > -1 else not (not u or not u.length)) empty: -> u = [] this disable: -> u = l = r = t this disabled: -> not u lock: -> l = t r or p.disable() this locked: -> not l fireWith: (e, t) -> t = t or [] t = [e, (if t.slice then t.slice() else t)] not u or i and not l or ((if n then l.push(t) else c(t))) this fire: -> p.fireWith(this, arguments_) this fired: -> !!i p b.extend( Deferred: (e) -> t = [["resolve", "done", b.Callbacks("once memory"), "resolved"], ["reject", "fail", b.Callbacks("once memory"), "rejected"], ["notify", "progress", b.Callbacks("memory")]] n = "pending" r = state: -> n always: -> i.done(arguments_).fail(arguments_) this then: -> e = arguments_ b.Deferred((n) -> b.each(t, (t, o) -> a = o[0] s = b.isFunction(e[t]) and e[t] i[o[1]] -> e = s and s.apply(this, arguments_) (if e and b.isFunction(e.promise) then e.promise().done(n.resolve).fail(n.reject).progress(n.notify) else n[a + "With"]((if this is r then n.promise() else this), (if s then [e] else arguments_))) ) e = null ).promise() promise: (e) -> (if null isnt e then b.extend(e, r) else r) i = {} r.pipe = r.then b.each(t, (e, o) -> a = o[2] s = o[3] r[o[1]] = a.add s and a.add(-> n = s , t[1 ^ e][2].disable, t[2][2].lock) i[o[0]] = -> i[o[0] + "With"]((if this is i then r else this), arguments_) this i[o[0] + "With"] = a.fireWith ) r.promise(i) e and e.call(i, i) i when: (e) -> t = 0 n = h.call(arguments_) r = n.length i = (if 1 isnt r or e and b.isFunction(e.promise) then r else 0) o = (if 1 is i then e else b.Deferred()) a = (e, t, n) -> (r) -> t[e] = this n[e] = (if arguments_.length > 1 then h.call(arguments_) else r) (if n is s then o.notifyWith(t, n) else --i or o.resolveWith(t, n)) s = undefined u = undefined l = undefined if r > 1 s = Array(r) u = Array(r) l = Array(r) while r > t (if n[t] and b.isFunction(n[t].promise) then n[t].promise().done(a(t, l, n)).fail(o.reject).progress(a(t, u, s)) else --i) t++ i or o.resolveWith(l, n) o.promise() ) b.support = -> t = undefined n = undefined r = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = undefined f = undefined d = o.createElement("div") return {} if d.setAttribute("className", "t") d.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>" n = d.getElementsByTagName("*") r = d.getElementsByTagName("a")[0] not n or not r or not n.length s = o.createElement("select") l = s.appendChild(o.createElement("option")) a = d.getElementsByTagName("input")[0] r.style.cssText = "top:1px;float:left;opacity:.5" t = getSetAttribute: "t" isnt d.className leadingWhitespace: 3 is d.firstChild.nodeType tbody: not d.getElementsByTagName("tbody").length htmlSerialize: !!d.getElementsByTagName("link").length style: /top/.test(r.getAttribute("style")) hrefNormalized: "/a" is r.getAttribute("href") opacity: /^0.5/.test(r.style.opacity) cssFloat: !!r.style.cssFloat checkOn: !!a.value optSelected: l.selected enctype: !!o.createElement("form").enctype html5Clone: "<:nav></:nav>" isnt o.createElement("nav").cloneNode(not 0).outerHTML boxModel: "CSS1Compat" is o.compatMode deleteExpando: not 0 noCloneEvent: not 0 inlineBlockNeedsLayout: not 1 shrinkWrapBlocks: not 1 reliableMarginRight: not 0 boxSizingReliable: not 0 pixelPosition: not 1 a.checked = not 0 t.noCloneChecked = a.cloneNode(not 0).checked s.disabled = not 0 t.optDisabled = not l.disabled try delete d.test catch h t.deleteExpando = not 1 a = o.createElement("input") a.setAttribute("value", "") t.input = "" is a.getAttribute("value") a.value = "t" a.setAttribute("type", "radio") t.radioValue = "t" is a.value a.setAttribute("checked", "t") a.setAttribute("name", "t") u = o.createDocumentFragment() u.appendChild(a) t.appendChecked = a.checked t.checkClone = u.cloneNode(not 0).cloneNode(not 0).lastChild.checked d.attachEvent and (d.attachEvent("onclick", -> t.noCloneEvent = not 1 ) d.cloneNode(not 0).click() ) for f of submit: not 0 change: not 0 focusin: not 0 d.setAttribute(c = "on" + f, "t") t[f + "Bubbles"] = c of e or d.attributes[c].expando is not 1 d.style.backgroundClip = "content-box" d.cloneNode(not 0).style.backgroundClip = "" t.clearCloneStyle = "content-box" is d.style.backgroundClip b(-> n = undefined r = undefined a = undefined s = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;" u = o.getElementsByTagName("body")[0] u and (n = o.createElement("div") n.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px" u.appendChild(n).appendChild(d) d.innerHTML = "<table><tr><td></td><td>t</td></tr></table>" a = d.getElementsByTagName("td") a[0].style.cssText = "padding:0;margin:0;border:0;display:none" p = 0 is a[0].offsetHeight a[0].style.display = "" a[1].style.display = "none" t.reliableHiddenOffsets = p and 0 is a[0].offsetHeight d.innerHTML = "" d.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;" t.boxSizing = 4 is d.offsetWidth t.doesNotIncludeMarginInBodyOffset = 1 isnt u.offsetTop e.getComputedStyle and (t.pixelPosition = "1%" isnt (e.getComputedStyle(d, null) or {}).top t.boxSizingReliable = "4px" is (e.getComputedStyle(d, null) or width: "4px").width r = d.appendChild(o.createElement("div")) r.style.cssText = d.style.cssText = s r.style.marginRight = r.style.width = "0" d.style.width = "1px" t.reliableMarginRight = not parseFloat((e.getComputedStyle(r, null) or {}).marginRight) ) typeof d.style.zoom isnt i and (d.innerHTML = "" d.style.cssText = s + "width:1px;padding:1px;display:inline;zoom:1" t.inlineBlockNeedsLayout = 3 is d.offsetWidth d.style.display = "block" d.innerHTML = "<div></div>" d.firstChild.style.width = "5px" t.shrinkWrapBlocks = 3 isnt d.offsetWidth t.inlineBlockNeedsLayout and (u.style.zoom = 1) ) u.removeChild(n) n = d = a = r = null ) ) n = s = u = l = r = a = null t () O = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/ B = /([A-Z])/g b.extend( cache: {} expando: "jQuery" + (p + Math.random()).replace(/\D/g, "") noData: embed: not 0 object: "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" applet: not 0 hasData: (e) -> e = (if e.nodeType then b.cache[e[b.expando]] else e[b.expando]) !!e and not $(e) data: (e, t, n) -> P e, t, n removeData: (e, t) -> R e, t _data: (e, t, n) -> P e, t, n, not 0 _removeData: (e, t) -> R e, t, not 0 acceptData: (e) -> return not 1 if e.nodeType and 1 isnt e.nodeType and 9 isnt e.nodeType t = e.nodeName and b.noData[e.nodeName.toLowerCase()] not t or t isnt not 0 and e.getAttribute("classid") is t ) b.fn.extend( data: (e, n) -> r = undefined i = undefined o = this[0] a = 0 s = null if e is t if @length and (s = b.data(o) 1 is o.nodeType and not b._data(o, "parsedAttrs") ) r = o.attributes while r.length > a i = r[a].name i.indexOf("data-") or (i = b.camelCase(i.slice(5)) W(o, i, s[i]) ) a++ b._data o, "parsedAttrs", not 0 return s (if "object" is typeof e then @each(-> b.data this, e ) else b.access(this, (n) -> (if n is t then (if o then W(o, e, b.data(o, e)) else null) else (@each(-> b.data this, e, n ) t )) , null, n, arguments_.length > 1, null, not 0)) removeData: (e) -> @each -> b.removeData this, e ) b.extend( queue: (e, n, r) -> i = undefined (if e then (n = (n or "fx") + "queue" i = b._data(e, n) r and ((if not i or b.isArray(r) then i = b._data(e, n, b.makeArray(r)) else i.push(r))) i or [] ) else t) dequeue: (e, t) -> t = t or "fx" n = b.queue(e, t) r = n.length i = n.shift() o = b._queueHooks(e, t) a = -> b.dequeue e, t "inprogress" is i and (i = n.shift() r-- ) o.cur = i i and ("fx" is t and n.unshift("inprogress") delete o.stop i.call(e, a, o) ) not r and o and o.empty.fire() _queueHooks: (e, t) -> n = t + "queueHooks" b._data(e, n) or b._data(e, n, empty: b.Callbacks("once memory").add(-> b._removeData(e, t + "queue") b._removeData(e, n) ) ) ) b.fn.extend( queue: (e, n) -> r = 2 "string" isnt typeof e and (n = e e = "fx" r-- ) (if r > arguments_.length then b.queue(this[0], e) else (if n is t then this else @each(-> t = b.queue(this, e, n) b._queueHooks(this, e) "fx" is e and "inprogress" isnt t[0] and b.dequeue(this, e) ))) dequeue: (e) -> @each -> b.dequeue this, e delay: (e, t) -> e = (if b.fx then b.fx.speeds[e] or e else e) t = t or "fx" @queue(t, (t, n) -> r = setTimeout(t, e) n.stop = -> clearTimeout r ) clearQueue: (e) -> @queue e or "fx", [] promise: (e, n) -> r = undefined i = 1 o = b.Deferred() a = this s = @length u = -> --i or o.resolveWith(a, [a]) "string" isnt typeof e and (n = e e = t ) e = e or "fx" while s-- r = b._data(a[s], e + "queueHooks") r and r.empty and (i++ r.empty.add(u) ) u() o.promise(n) ) I = undefined z = undefined X = /[\t\r\n]/g U = /\r/g V = /^(?:input|select|textarea|button|object)$/i Y = /^(?:a|area)$/i J = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i G = /^(?:checked|selected)$/i Q = b.support.getSetAttribute K = b.support.input b.fn.extend( attr: (e, t) -> b.access this, b.attr, e, t, arguments_.length > 1 removeAttr: (e) -> @each -> b.removeAttr this, e prop: (e, t) -> b.access this, b.prop, e, t, arguments_.length > 1 removeProp: (e) -> e = b.propFix[e] or e @each(-> try this[e] = t delete this[e] ) addClass: (e) -> t = undefined n = undefined r = undefined i = undefined o = undefined a = 0 s = @length u = "string" is typeof e and e if b.isFunction(e) return @each((t) -> b(this).addClass e.call(this, t, @className) ) if u t = (e or "").match(w) or [] while s > a if n = this[a] r = 1 is n.nodeType and ((if n.className then (" " + n.className + " ").replace(X, " ") else " ")) o = 0 0 > r.indexOf(" " + i + " ") and (r += i + " ") while i = t[o++] n.className = b.trim(r) a++ this removeClass: (e) -> t = undefined n = undefined r = undefined i = undefined o = undefined a = 0 s = @length u = 0 is arguments_.length or "string" is typeof e and e if b.isFunction(e) return @each((t) -> b(this).removeClass e.call(this, t, @className) ) if u t = (e or "").match(w) or [] while s > a if n = this[a] r = 1 is n.nodeType and ((if n.className then (" " + n.className + " ").replace(X, " ") else "")) o = 0 r = r.replace(" " + i + " ", " ") while r.indexOf(" " + i + " ") >= 0 while i = t[o++] n.className = (if e then b.trim(r) else "") a++ this toggleClass: (e, t) -> n = typeof e r = "boolean" is typeof t (if b.isFunction(e) then @each((n) -> b(this).toggleClass e.call(this, n, @className, t), t ) else @each(-> if "string" is n o = undefined a = 0 s = b(this) u = t l = e.match(w) or [] while o = l[a++] u = (if r then u else not s.hasClass(o)) s[(if u then "addClass" else "removeClass")](o) else (n is i or "boolean" is n) and (@className and b._data(this, "__className__", @className) @className = (if @className or e is not 1 then "" else b._data(this, "__className__") or "") ) )) hasClass: (e) -> t = " " + e + " " n = 0 r = @length while r > n return not 0 if 1 is this[n].nodeType and (" " + this[n].className + " ").replace(X, " ").indexOf(t) >= 0 n++ not 1 val: (e) -> n = undefined r = undefined i = undefined o = this[0] if arguments_.length return i = b.isFunction(e) @each((n) -> o = undefined a = b(this) 1 is @nodeType and (o = (if i then e.call(this, n, a.val()) else e) (if null is o then o = "" else (if "number" is typeof o then o += "" else b.isArray(o) and (o = b.map(o, (e) -> (if null is e then "" else e + "") )))) r = b.valHooks[@type] or b.valHooks[@nodeName.toLowerCase()] r and "set" of r and r.set(this, o, "value") isnt t or (@value = o) ) ) if o r = b.valHooks[o.type] or b.valHooks[o.nodeName.toLowerCase()] (if r and "get" of r and (n = r.get(o, "value")) isnt t then n else (n = o.value (if "string" is typeof n then n.replace(U, "") else (if null is n then "" else n)) )) ) b.extend( valHooks: option: get: (e) -> t = e.attributes.value (if not t or t.specified then e.value else e.text) select: get: (e) -> t = undefined n = undefined r = e.options i = e.selectedIndex o = "select-one" is e.type or 0 > i a = (if o then null else []) s = (if o then i + 1 else r.length) u = (if 0 > i then s else (if o then i else 0)) while s > u if n = r[u] not (not n.selected and u isnt i or ((if b.support.optDisabled then n.disabled else null isnt n.getAttribute("disabled"))) or n.parentNode.disabled and b.nodeName(n.parentNode, "optgroup")) return t if t = b(n).val() o a.push t u++ a set: (e, t) -> n = b.makeArray(t) b(e).find("option").each(-> @selected = b.inArray(b(this).val(), n) >= 0 ) n.length or (e.selectedIndex = -1) n attr: (e, n, r) -> o = undefined a = undefined s = undefined u = e.nodeType if e and 3 isnt u and 8 isnt u and 2 isnt u (if typeof e.getAttribute is i then b.prop(e, n, r) else (a = 1 isnt u or not b.isXMLDoc(e) a and (n = n.toLowerCase() o = b.attrHooks[n] or ((if J.test(n) then z else I)) ) (if r is t then (if o and a and "get" of o and null isnt (s = o.get(e, n)) then s else (typeof e.getAttribute isnt i and (s = e.getAttribute(n)) (if null is s then t else s) )) else (if null isnt r then (if o and a and "set" of o and (s = o.set(e, r, n)) isnt t then s else (e.setAttribute(n, r + "") r )) else (b.removeAttr(e, n) t ))) )) removeAttr: (e, t) -> n = undefined r = undefined i = 0 o = t and t.match(w) if o and 1 is e.nodeType while n = o[i++] r = b.propFix[n] or n (if J.test(n) then (if not Q and G.test(n) then e[b.camelCase("default-" + n)] = e[r] = not 1 else e[r] = not 1) else b.attr(e, n, "")) e.removeAttribute((if Q then n else r)) attrHooks: type: set: (e, t) -> if not b.support.radioValue and "radio" is t and b.nodeName(e, "input") n = e.value e.setAttribute("type", t) n and (e.value = n) t propFix: tabindex: "tabIndex" readonly: "readOnly" for: "htmlFor" class: "className" maxlength: "maxLength" cellspacing: "cellSpacing" cellpadding: "cellPadding" rowspan: "rowSpan" colspan: "colSpan" usemap: "useMap" frameborder: "frameBorder" contenteditable: "contentEditable" prop: (e, n, r) -> i = undefined o = undefined a = undefined s = e.nodeType if e and 3 isnt s and 8 isnt s and 2 isnt s a = 1 isnt s or not b.isXMLDoc(e) a and (n = b.propFix[n] or n o = b.propHooks[n] ) (if r isnt t then (if o and "set" of o and (i = o.set(e, r, n)) isnt t then i else e[n] = r) else (if o and "get" of o and null isnt (i = o.get(e, n)) then i else e[n])) propHooks: tabIndex: get: (e) -> n = e.getAttributeNode("tabindex") (if n and n.specified then parseInt(n.value, 10) else (if V.test(e.nodeName) or Y.test(e.nodeName) and e.href then 0 else t)) ) z = get: (e, n) -> r = b.prop(e, n) i = "boolean" is typeof r and e.getAttribute(n) o = (if "boolean" is typeof r then (if K and Q then null isnt i else (if G.test(n) then e[b.camelCase("default-" + n)] else !!i)) else e.getAttributeNode(n)) (if o and o.value isnt not 1 then n.toLowerCase() else t) set: (e, t, n) -> (if t is not 1 then b.removeAttr(e, n) else (if K and Q or not G.test(n) then e.setAttribute(not Q and b.propFix[n] or n, n) else e[b.camelCase("default-" + n)] = e[n] = not 0)) n K and Q or (b.attrHooks.value = get: (e, n) -> r = e.getAttributeNode(n) (if b.nodeName(e, "input") then e.defaultValue else (if r and r.specified then r.value else t)) set: (e, n, r) -> (if b.nodeName(e, "input") then (e.defaultValue = n t ) else I and I.set(e, n, r)) ) Q or (I = b.valHooks.button = get: (e, n) -> r = e.getAttributeNode(n) (if r and ((if "id" is n or "name" is n or "coords" is n then "" isnt r.value else r.specified)) then r.value else t) set: (e, n, r) -> i = e.getAttributeNode(r) i or e.setAttributeNode(i = e.ownerDocument.createAttribute(r)) i.value = n += "" (if "value" is r or n is e.getAttribute(r) then n else t) b.attrHooks.contenteditable = get: I.get set: (e, t, n) -> I.set e, (if "" is t then not 1 else t), n b.each(["width", "height"], (e, n) -> b.attrHooks[n] = b.extend(b.attrHooks[n], set: (e, r) -> (if "" is r then (e.setAttribute(n, "auto") r ) else t) ) ) ) b.support.hrefNormalized or (b.each(["href", "src", "width", "height"], (e, n) -> b.attrHooks[n] = b.extend(b.attrHooks[n], get: (e) -> r = e.getAttribute(n, 2) (if null is r then t else r) ) ) b.each(["href", "src"], (e, t) -> b.propHooks[t] = get: (e) -> e.getAttribute t, 4 ) ) b.support.style or (b.attrHooks.style = get: (e) -> e.style.cssText or t set: (e, t) -> e.style.cssText = t + "" ) b.support.optSelected or (b.propHooks.selected = b.extend(b.propHooks.selected, get: (e) -> t = e.parentNode t and (t.selectedIndex t.parentNode and t.parentNode.selectedIndex ) null )) b.support.enctype or (b.propFix.enctype = "encoding") b.support.checkOn or b.each(["radio", "checkbox"], -> b.valHooks[this] = get: (e) -> (if null is e.getAttribute("value") then "on" else e.value) ) b.each(["radio", "checkbox"], -> b.valHooks[this] = b.extend(b.valHooks[this], set: (e, n) -> (if b.isArray(n) then e.checked = b.inArray(b(e).val(), n) >= 0 else t) ) ) Z = /^(?:input|select|textarea)$/i et = /^key/ tt = /^(?:mouse|contextmenu)|click/ nt = /^(?:focusinfocus|focusoutblur)$/ rt = /^([^.]*)(?:\.(.+)|)$/ b.event = global: {} add: (e, n, r, o, a) -> s = undefined u = undefined l = undefined c = undefined p = undefined f = undefined d = undefined h = undefined g = undefined m = undefined y = undefined v = b._data(e) if v r.handler and (c = r r = c.handler a = c.selector ) r.guid or (r.guid = b.guid++) (u = v.events) or (u = v.events = {}) (f = v.handle) or (f = v.handle = (e) -> (if typeof b is i or e and b.event.triggered is e.type then t else b.event.dispatch.apply(f.elem, arguments_)) f.elem = e ) n = (n or "").match(w) or [""] l = n.length while l-- s = rt.exec(n[l]) or [] g = y = s[1] m = (s[2] or "").split(".").sort() p = b.event.special[g] or {} g = ((if a then p.delegateType else p.bindType)) or g p = b.event.special[g] or {} d = b.extend( type: g origType: y data: o handler: r guid: r.guid selector: a needsContext: a and b.expr.match.needsContext.test(a) namespace: m.join(".") , c) (h = u[g]) or (h = u[g] = [] h.delegateCount = 0 p.setup and p.setup.call(e, o, m, f) isnt not 1 or ((if e.addEventListener then e.addEventListener(g, f, not 1) else e.attachEvent and e.attachEvent("on" + g, f))) ) p.add and (p.add.call(e, d) d.handler.guid or (d.handler.guid = r.guid) ) (if a then h.splice(h.delegateCount++, 0, d) else h.push(d)) b.event.global[g] = not 0 e = null remove: (e, t, n, r, i) -> o = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = undefined f = undefined d = undefined h = undefined g = undefined m = b.hasData(e) and b._data(e) if m and (c = m.events) t = (t or "").match(w) or [""] l = t.length while l-- if s = rt.exec(t[l]) or [] d = g = s[1] h = (s[2] or "").split(".").sort() d p = b.event.special[d] or {} d = ((if r then p.delegateType else p.bindType)) or d f = c[d] or [] s = s[2] and RegExp("(^|\\.)" + h.join("\\.(?:.*\\.|)") + "(\\.|$)") u = o = f.length while o-- a = f[o] not i and g isnt a.origType or n and n.guid isnt a.guid or s and not s.test(a.namespace) or r and r isnt a.selector and ("**" isnt r or not a.selector) or (f.splice(o, 1) a.selector and f.delegateCount-- p.remove and p.remove.call(e, a) ) u and not f.length and (p.teardown and p.teardown.call(e, h, m.handle) isnt not 1 or b.removeEvent(e, d, m.handle) delete c[d] ) else for d of c b.event.remove e, d + t[l], n, r, not 0 b.isEmptyObject(c) and (delete m.handle b._removeData(e, "events") ) trigger: (n, r, i, a) -> s = undefined u = undefined l = undefined c = undefined p = undefined f = undefined d = undefined h = [i or o] g = (if y.call(n, "type") then n.type else n) m = (if y.call(n, "namespace") then n.namespace.split(".") else []) if l = f = i = i or o 3 isnt i.nodeType and 8 isnt i.nodeType and not nt.test(g + b.event.triggered) and (g.indexOf(".") >= 0 and (m = g.split(".") g = m.shift() m.sort() ) u = 0 > g.indexOf(":") and "on" + g n = (if n[b.expando] then n else new b.Event(g, "object" is typeof n and n)) n.isTrigger = not 0 n.namespace = m.join(".") n.namespace_re = (if n.namespace then RegExp("(^|\\.)" + m.join("\\.(?:.*\\.|)") + "(\\.|$)") else null) n.result = t n.target or (n.target = i) r = (if null is r then [n] else b.makeArray(r, [n])) p = b.event.special[g] or {} a or not p.trigger or p.trigger.apply(i, r) isnt not 1 ) if not a and not p.noBubble and not b.isWindow(i) c = p.delegateType or g nt.test(c + g) or (l = l.parentNode) while l h.push(l) f = l l = l.parentNode f is (i.ownerDocument or o) and h.push(f.defaultView or f.parentWindow or e) d = 0 while (l = h[d++]) and not n.isPropagationStopped() n.type = (if d > 1 then c else p.bindType or g) s = (b._data(l, "events") or {})[n.type] and b._data(l, "handle") s and s.apply(l, r) s = u and l[u] s and b.acceptData(l) and s.apply and s.apply(l, r) is not 1 and n.preventDefault() if n.type = g not (a or n.isDefaultPrevented() or p._default and p._default.apply(i.ownerDocument, r) isnt not 1 or "click" is g and b.nodeName(i, "a") or not b.acceptData(i) or not u or not i[g] or b.isWindow(i)) f = i[u] f and (i[u] = null) b.event.triggered = g try i[g]() b.event.triggered = t f and (i[u] = f) n.result dispatch: (e) -> e = b.event.fix(e) n = undefined r = undefined i = undefined o = undefined a = undefined s = [] u = h.call(arguments_) l = (b._data(this, "events") or {})[e.type] or [] c = b.event.special[e.type] or {} if u[0] = e e.delegateTarget = this not c.preDispatch or c.preDispatch.call(this, e) isnt not 1 s = b.event.handlers.call(this, e, l) n = 0 while (o = s[n++]) and not e.isPropagationStopped() e.currentTarget = o.elem a = 0 while (i = o.handlers[a++]) and not e.isImmediatePropagationStopped() (not e.namespace_re or e.namespace_re.test(i.namespace)) and (e.handleObj = i e.data = i.data r = ((b.event.special[i.origType] or {}).handle or i.handler).apply(o.elem, u) r isnt t and (e.result = r) is not 1 and (e.preventDefault() e.stopPropagation() ) ) c.postDispatch and c.postDispatch.call(this, e) e.result handlers: (e, n) -> r = undefined i = undefined o = undefined a = undefined s = [] u = n.delegateCount l = e.target if u and l.nodeType and (not e.button or "click" isnt e.type) while l isnt this if 1 is l.nodeType and (l.disabled isnt not 0 or "click" isnt e.type) o = [] a = 0 while u > a i = n[a] r = i.selector + " " o[r] is t and (o[r] = (if i.needsContext then b(r, this).index(l) >= 0 else b.find(r, this, null, [l]).length)) o[r] and o.push(i) a++ o.length and s.push( elem: l handlers: o ) l = l.parentNode or this n.length > u and s.push( elem: this handlers: n.slice(u) ) s fix: (e) -> return e if e[b.expando] t = undefined n = undefined r = undefined i = e.type a = e s = @fixHooks[i] s or (@fixHooks[i] = s = (if tt.test(i) then @mouseHooks else (if et.test(i) then @keyHooks else {}))) r = (if s.props then @props.concat(s.props) else @props) e = new b.Event(a) t = r.length while t-- n = r[t] e[n] = a[n] e.target or (e.target = a.srcElement or o) 3 is e.target.nodeType and (e.target = e.target.parentNode) e.metaKey = !!e.metaKey (if s.filter then s.filter(e, a) else e) props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" ") fixHooks: {} keyHooks: props: "char charCode key keyCode".split(" ") filter: (e, t) -> null is e.which and (e.which = (if null isnt t.charCode then t.charCode else t.keyCode)) e mouseHooks: props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" ") filter: (e, n) -> r = undefined i = undefined a = undefined s = n.button u = n.fromElement null is e.pageX and null isnt n.clientX and (i = e.target.ownerDocument or o a = i.documentElement r = i.body e.pageX = n.clientX + (a and a.scrollLeft or r and r.scrollLeft or 0) - (a and a.clientLeft or r and r.clientLeft or 0) e.pageY = n.clientY + (a and a.scrollTop or r and r.scrollTop or 0) - (a and a.clientTop or r and r.clientTop or 0) ) not e.relatedTarget and u and (e.relatedTarget = (if u is e.target then n.toElement else u)) e.which or s is t or (e.which = (if 1 & s then 1 else (if 2 & s then 3 else (if 4 & s then 2 else 0)))) e special: load: noBubble: not 0 click: trigger: -> (if b.nodeName(this, "input") and "checkbox" is @type and @click then (@click() not 1 ) else t) focus: trigger: -> if this isnt o.activeElement and @focus try return @focus() not 1 delegateType: "focusin" blur: trigger: -> (if this is o.activeElement and @blur then (@blur() not 1 ) else t) delegateType: "focusout" beforeunload: postDispatch: (e) -> e.result isnt t and (e.originalEvent.returnValue = e.result) simulate: (e, t, n, r) -> i = b.extend(new b.Event, n, type: e isSimulated: not 0 originalEvent: {} ) (if r then b.event.trigger(i, null, t) else b.event.dispatch.call(t, i)) i.isDefaultPrevented() and n.preventDefault() b.removeEvent = (if o.removeEventListener then (e, t, n) -> e.removeEventListener and e.removeEventListener(t, n, not 1) else (e, t, n) -> r = "on" + t e.detachEvent and (typeof e[r] is i and (e[r] = null) e.detachEvent(r, n) ) ) b.Event = (e, n) -> (if this instanceof b.Event then ((if e and e.type then (@originalEvent = e @type = e.type @isDefaultPrevented = (if e.defaultPrevented or e.returnValue is not 1 or e.getPreventDefault and e.getPreventDefault() then it else ot) ) else @type = e) n and b.extend(this, n) @timeStamp = e and e.timeStamp or b.now() this[b.expando] = not 0 t ) else new b.Event(e, n)) b.Event:: = isDefaultPrevented: ot isPropagationStopped: ot isImmediatePropagationStopped: ot preventDefault: -> e = @originalEvent @isDefaultPrevented = it e and ((if e.preventDefault then e.preventDefault() else e.returnValue = not 1)) stopPropagation: -> e = @originalEvent @isPropagationStopped = it e and (e.stopPropagation and e.stopPropagation() e.cancelBubble = not 0 ) stopImmediatePropagation: -> @isImmediatePropagationStopped = it @stopPropagation() b.each( mouseenter: "mouseover" mouseleave: "mouseout" , (e, t) -> b.event.special[e] = delegateType: t bindType: t handle: (e) -> n = undefined r = this i = e.relatedTarget o = e.handleObj (not i or i isnt r and not b.contains(r, i)) and (e.type = o.origType n = o.handler.apply(this, arguments_) e.type = t ) n ) b.support.submitBubbles or (b.event.special.submit = setup: -> (if b.nodeName(this, "form") then not 1 else (b.event.add(this, "click._submit keypress._submit", (e) -> n = e.target r = (if b.nodeName(n, "input") or b.nodeName(n, "button") then n.form else t) r and not b._data(r, "submitBubbles") and (b.event.add(r, "submit._submit", (e) -> e._submit_bubble = not 0 ) b._data(r, "submitBubbles", not 0) ) ) t )) postDispatch: (e) -> e._submit_bubble and (delete e._submit_bubble @parentNode and not e.isTrigger and b.event.simulate("submit", @parentNode, e, not 0) ) teardown: -> (if b.nodeName(this, "form") then not 1 else (b.event.remove(this, "._submit") t )) ) b.support.changeBubbles or (b.event.special.change = setup: -> (if Z.test(@nodeName) then (("checkbox" is @type or "radio" is @type) and (b.event.add(this, "propertychange._change", (e) -> "checked" is e.originalEvent.propertyName and (@_just_changed = not 0) ) b.event.add(this, "click._change", (e) -> @_just_changed and not e.isTrigger and (@_just_changed = not 1) b.event.simulate("change", this, e, not 0) ) ) not 1 ) else (b.event.add(this, "beforeactivate._change", (e) -> t = e.target Z.test(t.nodeName) and not b._data(t, "changeBubbles") and (b.event.add(t, "change._change", (e) -> not @parentNode or e.isSimulated or e.isTrigger or b.event.simulate("change", @parentNode, e, not 0) ) b._data(t, "changeBubbles", not 0) ) ) t )) handle: (e) -> n = e.target (if this isnt n or e.isSimulated or e.isTrigger or "radio" isnt n.type and "checkbox" isnt n.type then e.handleObj.handler.apply(this, arguments_) else t) teardown: -> b.event.remove(this, "._change") not Z.test(@nodeName) ) b.support.focusinBubbles or b.each( focus: "focusin" blur: "focusout" , (e, t) -> n = 0 r = (e) -> b.event.simulate t, e.target, b.event.fix(e), not 0 b.event.special[t] = setup: -> 0 is n++ and o.addEventListener(e, r, not 0) teardown: -> 0 is --n and o.removeEventListener(e, r, not 0) ) b.fn.extend( on: (e, n, r, i, o) -> a = undefined s = undefined if "object" is typeof e "string" isnt typeof n and (r = r or n n = t ) for a of e @on a, n, r, e[a], o return this if (if null is r and null is i then (i = n r = n = t ) else null is i and ((if "string" is typeof n then (i = r r = t ) else (i = r r = n n = t )))) i is not 1 i = ot else return this unless i 1 is o and (s = i i = (e) -> b().off(e) s.apply(this, arguments_) i.guid = s.guid or (s.guid = b.guid++) ) @each(-> b.event.add this, e, i, r, n ) one: (e, t, n, r) -> @on e, t, n, r, 1 off: (e, n, r) -> i = undefined o = undefined if e and e.preventDefault and e.handleObj return i = e.handleObj b(e.delegateTarget).off((if i.namespace then i.origType + "." + i.namespace else i.origType), i.selector, i.handler) this if "object" is typeof e for o of e @off o, n, e[o] return this (n is not 1 or "function" is typeof n) and (r = n n = t ) r is not 1 and (r = ot) @each(-> b.event.remove this, e, r, n ) bind: (e, t, n) -> @on e, null, t, n unbind: (e, t) -> @off e, null, t delegate: (e, t, n, r) -> @on t, e, n, r undelegate: (e, t, n) -> (if 1 is arguments_.length then @off(e, "**") else @off(t, e or "**", n)) trigger: (e, t) -> @each -> b.event.trigger e, t, this triggerHandler: (e, n) -> r = this[0] (if r then b.event.trigger(e, n, r, not 0) else t) ) (e, t) -> rt = (e) -> Y.test e + "" it = -> e = undefined t = [] e = (n, r) -> t.push(n += " ") > i.cacheLength and delete e[t.shift()] e[n] = r ot = (e) -> e[x] = not 0 e at = (e) -> t = p.createElement("div") try return e(t) catch n return not 1 finally t = null st = (e, t, n, r) -> i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined f = undefined g = undefined m = undefined v = undefined return n if ((if t then t.ownerDocument or t else w)) isnt p and c(t) t = t or p n = n or [] not e or "string" isnt typeof e return [] if 1 isnt (s = t.nodeType) and 9 isnt s if not d and not r if i = J.exec(e) if a = i[1] if 9 is s return n if o = t.getElementById(a) not o or not o.parentNode if o.id is a return n.push(o) n else if t.ownerDocument and (o = t.ownerDocument.getElementById(a)) and y(t, o) and o.id is a return n.push(o) n else if i[2] return H.apply(n, q.call(t.getElementsByTagName(e), 0)) n if (a = i[3]) and T.getByClassName and t.getElementsByClassName return H.apply(n, q.call(t.getElementsByClassName(a), 0)) n if T.qsa and not h.test(e) if f = not 0 g = x m = t v = 9 is s and e 1 is s and "object" isnt t.nodeName.toLowerCase() l = ft(e) (if (f = t.getAttribute("id")) then g = f.replace(K, "\\$&") else t.setAttribute("id", g)) g = "[id='" + g + "'] " u = l.length l[u] = g + dt(l[u]) while u-- m = V.test(e) and t.parentNode or t v = l.join(",") if v try return H.apply(n, q.call(m.querySelectorAll(v), 0)) n finally f or t.removeAttribute("id") wt e.replace(W, "$1"), t, n, r ut = (e, t) -> n = t and e r = n and (~t.sourceIndex or j) - (~e.sourceIndex or j) return r if r return -1 if n is t while n = n.nextSibling if n (if e then 1 else -1) lt = (e) -> (t) -> n = t.nodeName.toLowerCase() "input" is n and t.type is e ct = (e) -> (t) -> n = t.nodeName.toLowerCase() ("input" is n or "button" is n) and t.type is e pt = (e) -> ot (t) -> t = +t ot((n, r) -> i = undefined o = e([], n.length, t) a = o.length n[i = o[a]] and (n[i] = not (r[i] = n[i])) while a-- ) ft = (e, t) -> n = undefined r = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = E[e + " "] return (if t then 0 else c.slice(0)) if c s = e u = [] l = i.preFilter while s (not n or (r = $.exec(s))) and (r and (s = s.slice(r[0].length) or s) u.push(o = []) ) n = not 1 (r = I.exec(s)) and (n = r.shift() o.push( value: n type: r[0].replace(W, " ") ) s = s.slice(n.length) ) for a of i.filter not (r = U[a].exec(s)) or l[a] and not (r = l[a](r)) or (n = r.shift() o.push( value: n type: a matches: r ) s = s.slice(n.length) ) break unless n (if t then s.length else (if s then st.error(e) else E(e, u).slice(0))) dt = (e) -> t = 0 n = e.length r = "" while n > t r += e[t].value t++ r ht = (e, t, n) -> i = t.dir o = n and "parentNode" is i a = C++ (if t.first then (t, n, r) -> return e(t, n, r) if 1 is t.nodeType or o while t = t[i] else (t, n, s) -> u = undefined l = undefined c = undefined p = N + " " + a if s return not 0 if (1 is t.nodeType or o) and e(t, n, s) while t = t[i] else while t = t[i] if 1 is t.nodeType or o if c = t[x] or (t[x] = {}) (l = c[i]) and l[0] is p return u is not 0 if (u = l[1]) is not 0 or u is r else return not 0 if l = c[i] = [p] l[1] = e(t, n, s) or r l[1] is not 0 ) gt = (e) -> (if e.length > 1 then (t, n, r) -> i = e.length return not 1 unless e[i](t, n, r) while i-- not 0 else e[0]) mt = (e, t, n, r, i) -> o = undefined a = [] s = 0 u = e.length l = null isnt t while u > s (o = e[s]) and (not n or n(o, r, i)) and (a.push(o) l and t.push(s) ) s++ a yt = (e, t, n, r, i, o) -> r and not r[x] and (r = yt(r)) i and not i[x] and (i = yt(i, o)) ot((o, a, s, u) -> l = undefined c = undefined p = undefined f = [] d = [] h = a.length g = o or xt(t or "*", (if s.nodeType then [s] else s), []) m = (if not e or not o and t then g else mt(g, f, e, s, u)) y = (if n then (if i or ((if o then e else h or r)) then [] else a) else m) if n and n(m, y, s, u) r l = mt(y, d) r(l, [], s, u) c = l.length (p = l[c]) and (y[d[c]] = not (m[d[c]] = p)) while c-- if o if i or e if i l = [] c = y.length (p = y[c]) and l.push(m[c] = p) while c-- i null, y = [], l, u c = y.length (p = y[c]) and (l = (if i then M.call(o, p) else f[c])) > -1 and (o[l] = not (a[l] = p)) while c-- else y = mt((if y is a then y.splice(h, y.length) else y)) (if i then i(null, a, y, u) else H.apply(a, y)) ) vt = (e) -> t = undefined n = undefined r = undefined o = e.length a = i.relative[e[0].type] s = a or i.relative[" "] u = (if a then 1 else 0) c = ht((e) -> e is t , s, not 0) p = ht((e) -> M.call(t, e) > -1 , s, not 0) f = [(e, n, r) -> not a and (r or n isnt l) or ((if (t = n).nodeType then c(e, n, r) else p(e, n, r))) ] while o > u unless n = i.relative[e[u].type] if n = i.filter[e[u].type].apply(null, e[u].matches) n[x] r = ++u while o > r break if i.relative[e[r].type] r++ return yt(u > 1 and gt(f), u > 1 and dt(e.slice(0, u - 1)).replace(W, "$1"), n, r > u and vt(e.slice(u, r)), o > r and vt(e = e.slice(r)), o > r and dt(e)) f.push n u++ gt f bt = (e, t) -> n = 0 o = t.length > 0 a = e.length > 0 s = (s, u, c, f, d) -> h = undefined g = undefined m = undefined y = [] v = 0 b = "0" x = s and [] w = null isnt d T = l C = s or a and i.find.TAG("*", d and u.parentNode or u) k = N += (if null is T then 1 else Math.random() or .1) w and (l = u isnt p and u r = n ) while null isnt (h = C[b]) if a and h g = 0 while m = e[g++] if m(h, u, c) f.push h break w and (N = k r = ++n ) o and ((h = not m and h) and v-- s and x.push(h) ) b++ if v += b o and b isnt v g = 0 m x, y, u, c while m = t[g++] if s x[b] or y[b] or (y[b] = L.call(f)) while b-- if v > 0 y = mt(y) H.apply(f, y) w and not s and y.length > 0 and v + t.length > 1 and st.uniqueSort(f) w and (N = k l = T ) x (if o then ot(s) else s) xt = (e, t, n) -> r = 0 i = t.length while i > r st e, t[r], n r++ n wt = (e, t, n, r) -> o = undefined a = undefined u = undefined l = undefined c = undefined p = ft(e) if not r and 1 is p.length if a = p[0] = p[0].slice(0) a.length > 2 and "ID" is (u = a[0]).type and 9 is t.nodeType and not d and i.relative[a[1].type] return n if t = i.find.ID(u.matches[0].replace(et, tt), t)[0] not t e = e.slice(a.shift().value.length) o = (if U.needsContext.test(e) then 0 else a.length) while o-- break if u = a[o] i.relative[l = u.type] if (c = i.find[l]) and (r = c(u.matches[0].replace(et, tt), V.test(a[0].type) and t.parentNode or t)) if a.splice(o, 1) e = r.length and dt(a) not e return H.apply(n, q.call(r, 0)) n break s(e, p)(r, t, d, n, V.test(e)) n Tt = -> n = undefined r = undefined i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = undefined f = undefined d = undefined h = undefined g = undefined m = undefined y = undefined v = undefined x = "sizzle" + -new Date w = e.document T = {} N = 0 C = 0 k = it() E = it() S = it() A = typeof t j = 1 << 31 D = [] L = D.pop H = D.push q = D.slice M = D.indexOf or (e) -> t = 0 n = @length while n > t return t if this[t] is e t++ -1 _ = "[\\x20\\t\\r\\n\\f]" F = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+" O = F.replace("w", "w#") B = "([*^$|!~]?=)" P = "\\[" + _ + "*(" + F + ")" + _ + "*(?:" + B + _ + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + O + ")|)|)" + _ + "*\\]" R = ":(" + F + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + P.replace(3, 8) + ")*)|.*)\\)|)" W = RegExp("^" + _ + "+|((?:^|[^\\\\])(?:\\\\.)*)" + _ + "+$", "g") $ = RegExp("^" + _ + "*," + _ + "*") I = RegExp("^" + _ + "*([\\x20\\t\\r\\n\\f>+~])" + _ + "*") z = RegExp(R) X = RegExp("^" + O + "$") U = ID: RegExp("^#(" + F + ")") CLASS: RegExp("^\\.(" + F + ")") NAME: RegExp("^\\[name=['\"]?(" + F + ")['\"]?\\]") TAG: RegExp("^(" + F.replace("w", "w*") + ")") ATTR: RegExp("^" + P) PSEUDO: RegExp("^" + R) CHILD: RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + _ + "*(even|odd|(([+-]|)(\\d*)n|)" + _ + "*(?:([+-]|)" + _ + "*(\\d+)|))" + _ + "*\\)|)", "i") needsContext: RegExp("^" + _ + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + _ + "*((?:-\\d)?\\d*)" + _ + "*\\)|)(?=[^-]|$)", "i") V = /[\x20\t\r\n\f]*[+~]/ Y = /^[^{]+\{\s*\[native code/ J = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/ G = /^(?:input|select|textarea|button)$/i Q = /^h\d$/i K = /'|\\/g Z = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g et = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g tt = (e, t) -> n = "0x" + t - 65536 (if n isnt n then t else (if 0 > n then String.fromCharCode(n + 65536) else String.fromCharCode(55296 | n >> 10, 56320 | 1023 & n))) try q.call(w.documentElement.childNodes, 0)[0].nodeType catch nt q = (e) -> t = undefined n = [] n.push t while t = this[e++] n a = st.isXML = (e) -> t = e and (e.ownerDocument or e).documentElement (if t then "HTML" isnt t.nodeName else not 1) c = st.setDocument = (e) -> n = (if e then e.ownerDocument or e else w) (if n isnt p and 9 is n.nodeType and n.documentElement then (p = n f = n.documentElement d = a(n) T.tagNameNoComments = at((e) -> e.appendChild(n.createComment("")) not e.getElementsByTagName("*").length ) T.attributes = at((e) -> e.innerHTML = "<select></select>" t = typeof e.lastChild.getAttribute("multiple") "boolean" isnt t and "string" isnt t ) T.getByClassName = at((e) -> e.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>" (if e.getElementsByClassName and e.getElementsByClassName("e").length then (e.lastChild.className = "e" 2 is e.getElementsByClassName("e").length ) else not 1) ) T.getByName = at((e) -> e.id = x + 0 e.innerHTML = "<a name='" + x + "'></a><div name='" + x + "'></div>" f.insertBefore(e, f.firstChild) t = n.getElementsByName and n.getElementsByName(x).length is 2 + n.getElementsByName(x + 0).length T.getIdNotName = not n.getElementById(x) f.removeChild(e) t ) i.attrHandle = (if at((e) -> e.innerHTML = "<a href='#'></a>" e.firstChild and typeof e.firstChild.getAttribute isnt A and "#" is e.firstChild.getAttribute("href") ) then {} else href: (e) -> e.getAttribute "href", 2 type: (e) -> e.getAttribute "type" ) (if T.getIdNotName then (i.find.ID = (e, t) -> if typeof t.getElementById isnt A and not d n = t.getElementById(e) (if n and n.parentNode then [n] else []) i.filter.ID = (e) -> t = e.replace(et, tt) (e) -> e.getAttribute("id") is t ) else (i.find.ID = (e, n) -> if typeof n.getElementById isnt A and not d r = n.getElementById(e) (if r then (if r.id is e or typeof r.getAttributeNode isnt A and r.getAttributeNode("id").value is e then [r] else t) else []) i.filter.ID = (e) -> t = e.replace(et, tt) (e) -> n = typeof e.getAttributeNode isnt A and e.getAttributeNode("id") n and n.value is t )) i.find.TAG = (if T.tagNameNoComments then (e, n) -> (if typeof n.getElementsByTagName isnt A then n.getElementsByTagName(e) else t) else (e, t) -> n = undefined r = [] i = 0 o = t.getElementsByTagName(e) if "*" is e 1 is n.nodeType and r.push(n) while n = o[i++] return r o ) i.find.NAME = T.getByName and (e, n) -> (if typeof n.getElementsByName isnt A then n.getElementsByName(name) else t) i.find.CLASS = T.getByClassName and (e, n) -> (if typeof n.getElementsByClassName is A or d then t else n.getElementsByClassName(e)) g = [] h = [":focus"] (T.qsa = rt(n.querySelectorAll)) and (at((e) -> e.innerHTML = "<select><option selected=''></option></select>" e.querySelectorAll("[selected]").length or h.push("\\[" + _ + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)") e.querySelectorAll(":checked").length or h.push(":checked") ) at((e) -> e.innerHTML = "<input type='hidden' i=''/>" e.querySelectorAll("[i^='']").length and h.push("[*^$]=" + _ + "*(?:\"\"|'')") e.querySelectorAll(":enabled").length or h.push(":enabled", ":disabled") e.querySelectorAll("*,:x") h.push(",.*:") ) ) (T.matchesSelector = rt(m = f.matchesSelector or f.mozMatchesSelector or f.webkitMatchesSelector or f.oMatchesSelector or f.msMatchesSelector)) and at((e) -> T.disconnectedMatch = m.call(e, "div") m.call(e, "[s!='']:x") g.push("!=", R) ) h = RegExp(h.join("|")) g = RegExp(g.join("|")) y = (if rt(f.contains) or f.compareDocumentPosition then (e, t) -> n = (if 9 is e.nodeType then e.documentElement else e) r = t and t.parentNode e is r or not (not r or 1 isnt r.nodeType or not ((if n.contains then n.contains(r) else e.compareDocumentPosition and 16 & e.compareDocumentPosition(r)))) else (e, t) -> return not 0 if t is e while t = t.parentNode if t not 1 ) v = (if f.compareDocumentPosition then (e, t) -> r = undefined (if e is t then (u = not 0 0 ) else (if (r = t.compareDocumentPosition and e.compareDocumentPosition and e.compareDocumentPosition(t)) then (if 1 & r or e.parentNode and 11 is e.parentNode.nodeType then (if e is n or y(w, e) then -1 else (if t is n or y(w, t) then 1 else 0)) else (if 4 & r then -1 else 1)) else (if e.compareDocumentPosition then -1 else 1))) else (e, t) -> r = undefined i = 0 o = e.parentNode a = t.parentNode s = [e] l = [t] if e is t return u = not 0 0 return (if e is n then -1 else (if t is n then 1 else (if o then -1 else (if a then 1 else 0)))) if not o or not a return ut(e, t) if o is a r = e s.unshift r while r = r.parentNode r = t l.unshift r while r = r.parentNode i++ while s[i] is l[i] (if i then ut(s[i], l[i]) else (if s[i] is w then -1 else (if l[i] is w then 1 else 0))) ) u = not 1 [0, 0].sort(v) T.detectDuplicates = u p ) else p) st.matches = (e, t) -> st e, null, null, t st.matchesSelector = (e, t) -> if (e.ownerDocument or e) isnt p and c(e) t = t.replace(Z, "='$1']") not (not T.matchesSelector or d or g and g.test(t) or h.test(t)) try n = m.call(e, t) return n if n or T.disconnectedMatch or e.document and 11 isnt e.document.nodeType st(t, p, null, [e]).length > 0 st.contains = (e, t) -> (e.ownerDocument or e) isnt p and c(e) y(e, t) st.attr = (e, t) -> n = undefined (e.ownerDocument or e) isnt p and c(e) d or (t = t.toLowerCase()) (if (n = i.attrHandle[t]) then n(e) else (if d or T.attributes then e.getAttribute(t) else (if ((n = e.getAttributeNode(t)) or e.getAttribute(t)) and e[t] is not 0 then t else (if n and n.specified then n.value else null)))) st.error = (e) -> throw Error("Syntax error, unrecognized expression: " + e) st.uniqueSort = (e) -> t = undefined n = [] r = 1 i = 0 if u = not T.detectDuplicates e.sort(v) u while t = e[r] t is e[r - 1] and (i = n.push(r)) r++ e.splice n[i], 1 while i-- e o = st.getText = (e) -> t = undefined n = "" r = 0 i = e.nodeType if i if 1 is i or 9 is i or 11 is i return e.textContent if "string" is typeof e.textContent e = e.firstChild while e n += o(e) e = e.nextSibling else return e.nodeValue if 3 is i or 4 is i else while t = e[r] n += o(t) r++ n i = st.selectors = cacheLength: 50 createPseudo: ot match: U find: {} relative: ">": dir: "parentNode" first: not 0 " ": dir: "parentNode" "+": dir: "previousSibling" first: not 0 "~": dir: "previousSibling" preFilter: ATTR: (e) -> e[1] = e[1].replace(et, tt) e[3] = (e[4] or e[5] or "").replace(et, tt) "~=" is e[2] and (e[3] = " " + e[3] + " ") e.slice(0, 4) CHILD: (e) -> e[1] = e[1].toLowerCase() (if "nth" is e[1].slice(0, 3) then (e[3] or st.error(e[0]) e[4] = +((if e[4] then e[5] + (e[6] or 1) else 2 * ("even" is e[3] or "odd" is e[3]))) e[5] = +(e[7] + e[8] or "odd" is e[3]) ) else e[3] and st.error(e[0])) e PSEUDO: (e) -> t = undefined n = not e[5] and e[2] (if U.CHILD.test(e[0]) then null else ((if e[4] then e[2] = e[4] else n and z.test(n) and (t = ft(n, not 0)) and (t = n.indexOf(")", n.length - t) - n.length) and (e[0] = e[0].slice(0, t) e[2] = n.slice(0, t) )) e.slice(0, 3) )) filter: TAG: (e) -> (if "*" is e then -> not 0 else (e = e.replace(et, tt).toLowerCase() (t) -> t.nodeName and t.nodeName.toLowerCase() is e )) CLASS: (e) -> t = k[e + " "] t or (t = RegExp("(^|" + _ + ")" + e + "(" + _ + "|$)")) and k(e, (e) -> t.test e.className or typeof e.getAttribute isnt A and e.getAttribute("class") or "" ) ATTR: (e, t, n) -> (r) -> i = st.attr(r, e) (if null is i then "!=" is t else (if t then (i += "" (if "=" is t then i is n else (if "!=" is t then i isnt n else (if "^=" is t then n and 0 is i.indexOf(n) else (if "*=" is t then n and i.indexOf(n) > -1 else (if "$=" is t then n and i.slice(-n.length) is n else (if "~=" is t then (" " + i + " ").indexOf(n) > -1 else (if "|=" is t then i is n or i.slice(0, n.length + 1) is n + "-" else not 1))))))) ) else not 0)) CHILD: (e, t, n, r, i) -> o = "nth" isnt e.slice(0, 3) a = "last" isnt e.slice(-4) s = "of-type" is t (if 1 is r and 0 is i then (e) -> !!e.parentNode else (t, n, u) -> l = undefined c = undefined p = undefined f = undefined d = undefined h = undefined g = (if o isnt a then "nextSibling" else "previousSibling") m = t.parentNode y = s and t.nodeName.toLowerCase() v = not u and not s if m if o while g p = t return not 1 if (if s then p.nodeName.toLowerCase() is y else 1 is p.nodeType) while p = p[g] h = g = "only" is e and not h and "nextSibling" return not 0 if h = [(if a then m.firstChild else m.lastChild)] a and v c = m[x] or (m[x] = {}) l = c[e] or [] d = l[0] is N and l[1] f = l[0] is N and l[2] p = d and m.childNodes[d] while p = ++d and p and p[g] or (f = d = 0) or h.pop() if 1 is p.nodeType and ++f and p is t c[e] = [N, d, f] break else if v and (l = (t[x] or (t[x] = {}))[e]) and l[0] is N f = l[1] else while p = ++d and p and p[g] or (f = d = 0) or h.pop() break if ((if s then p.nodeName.toLowerCase() is y else 1 is p.nodeType)) and ++f and (v and ((p[x] or (p[x] = {}))[e] = [N, f]) p is t ) f -= i f is r or 0 is f % r and f / r >= 0 ) PSEUDO: (e, t) -> n = undefined r = i.pseudos[e] or i.setFilters[e.toLowerCase()] or st.error("unsupported pseudo: " + e) (if r[x] then r(t) else (if r.length > 1 then (n = [e, e, "", t] (if i.setFilters.hasOwnProperty(e.toLowerCase()) then ot((e, n) -> i = undefined o = r(e, t) a = o.length while a-- i = M.call(e, o[a]) e[i] = not (n[i] = o[a]) ) else (e) -> r e, 0, n ) ) else r)) pseudos: not: ot((e) -> t = [] n = [] r = s(e.replace(W, "$1")) (if r[x] then ot((e, t, n, i) -> o = undefined a = r(e, null, i, []) s = e.length (o = a[s]) and (e[s] = not (t[s] = o)) while s-- ) else (e, i, o) -> t[0] = e r(t, null, o, n) not n.pop() ) ) has: ot((e) -> (t) -> st(e, t).length > 0 ) contains: ot((e) -> (t) -> (t.textContent or t.innerText or o(t)).indexOf(e) > -1 ) lang: ot((e) -> X.test(e or "") or st.error("unsupported lang: " + e) e = e.replace(et, tt).toLowerCase() (t) -> n = undefined loop if n = (if d then t.getAttribute("xml:lang") or t.getAttribute("lang") else t.lang) return n = n.toLowerCase() n is e or 0 is n.indexOf(e + "-") break unless (t = t.parentNode) and 1 is t.nodeType not 1 ) target: (t) -> n = e.location and e.location.hash n and n.slice(1) is t.id root: (e) -> e is f focus: (e) -> e is p.activeElement and (not p.hasFocus or p.hasFocus()) and !!(e.type or e.href or ~e.tabIndex) enabled: (e) -> e.disabled is not 1 disabled: (e) -> e.disabled is not 0 checked: (e) -> t = e.nodeName.toLowerCase() "input" is t and !!e.checked or "option" is t and !!e.selected selected: (e) -> e.parentNode and e.parentNode.selectedIndex e.selected is not 0 empty: (e) -> e = e.firstChild while e return not 1 if e.nodeName > "@" or 3 is e.nodeType or 4 is e.nodeType e = e.nextSibling not 0 parent: (e) -> not i.pseudos.empty(e) header: (e) -> Q.test e.nodeName input: (e) -> G.test e.nodeName button: (e) -> t = e.nodeName.toLowerCase() "input" is t and "button" is e.type or "button" is t text: (e) -> t = undefined "input" is e.nodeName.toLowerCase() and "text" is e.type and (null is (t = e.getAttribute("type")) or t.toLowerCase() is e.type) first: pt(-> [0] ) last: pt((e, t) -> [t - 1] ) eq: pt((e, t, n) -> [(if 0 > n then n + t else n)] ) even: pt((e, t) -> n = 0 while t > n e.push n n += 2 e ) odd: pt((e, t) -> n = 1 while t > n e.push n n += 2 e ) lt: pt((e, t, n) -> r = (if 0 > n then n + t else n) while --r >= 0 e.push r e ) gt: pt((e, t, n) -> r = (if 0 > n then n + t else n) while t > ++r e.push r e ) for n of radio: not 0 checkbox: not 0 file: not 0 password: <PASSWORD> image: not 0 i.pseudos[n] = lt(n) for n of submit: not 0 reset: not 0 i.pseudos[n] = ct(n) s = st.compile = (e, t) -> n = undefined r = [] i = [] o = S[e + " "] unless o t or (t = ft(e)) n = t.length while n-- o = vt(t[n]) (if o[x] then r.push(o) else i.push(o)) o = S(e, bt(i, r)) o i.pseudos.nth = i.pseudos.eq i.filters = Tt:: = i.pseudos i.setFilters = new Tt c() st.attr = b.attr b.find = st b.expr = st.selectors b.expr[":"] = b.expr.pseudos b.unique = st.uniqueSort b.text = st.getText b.isXMLDoc = st.isXML b.contains = st.contains (e) at = /Until$/ st = /^(?:parents|prev(?:Until|All))/ ut = /^.[^:#\[\.,]*$/ lt = b.expr.match.needsContext ct = children: not 0 contents: not 0 next: not 0 prev: not 0 b.fn.extend( find: (e) -> t = undefined n = undefined r = undefined i = @length unless "string" is typeof e return r = this @pushStack(b(e).filter(-> t = 0 while i > t return not 0 if b.contains(r[t], this) t++ )) n = [] t = 0 while i > t b.find e, this[t], n t++ n = @pushStack((if i > 1 then b.unique(n) else n)) n.selector = ((if @selector then @selector + " " else "")) + e n has: (e) -> t = undefined n = b(e, this) r = n.length @filter -> t = 0 while r > t return not 0 if b.contains(this, n[t]) t++ not: (e) -> @pushStack ft(this, e, not 1) filter: (e) -> @pushStack ft(this, e, not 0) is: (e) -> !!e and ((if "string" is typeof e then (if lt.test(e) then b(e, @context).index(this[0]) >= 0 else b.filter(e, this).length > 0) else @filter(e).length > 0)) closest: (e, t) -> n = undefined r = 0 i = @length o = [] a = (if lt.test(e) or "string" isnt typeof e then b(e, t or @context) else 0) while i > r n = this[r] while n and n.ownerDocument and n isnt t and 11 isnt n.nodeType if (if a then a.index(n) > -1 else b.find.matchesSelector(n, e)) o.push n break n = n.parentNode r++ @pushStack (if o.length > 1 then b.unique(o) else o) index: (e) -> (if e then (if "string" is typeof e then b.inArray(this[0], b(e)) else b.inArray((if e.jquery then e[0] else e), this)) else (if this[0] and this[0].parentNode then @first().prevAll().length else -1)) add: (e, t) -> n = (if "string" is typeof e then b(e, t) else b.makeArray((if e and e.nodeType then [e] else e))) r = b.merge(@get(), n) @pushStack b.unique(r) addBack: (e) -> @add (if null is e then @prevObject else @prevObject.filter(e)) ) b.fn.andSelf = b.fn.addBack b.each( parent: (e) -> t = e.parentNode (if t and 11 isnt t.nodeType then t else null) parents: (e) -> b.dir e, "parentNode" parentsUntil: (e, t, n) -> b.dir e, "parentNode", n next: (e) -> pt e, "nextSibling" prev: (e) -> pt e, "previousSibling" nextAll: (e) -> b.dir e, "nextSibling" prevAll: (e) -> b.dir e, "previousSibling" nextUntil: (e, t, n) -> b.dir e, "nextSibling", n prevUntil: (e, t, n) -> b.dir e, "previousSibling", n siblings: (e) -> b.sibling (e.parentNode or {}).firstChild, e children: (e) -> b.sibling e.firstChild contents: (e) -> (if b.nodeName(e, "iframe") then e.contentDocument or e.contentWindow.document else b.merge([], e.childNodes)) , (e, t) -> b.fn[e] = (n, r) -> i = b.map(this, t, n) at.test(e) or (r = n) r and "string" is typeof r and (i = b.filter(r, i)) i = (if @length > 1 and not ct[e] then b.unique(i) else i) @length > 1 and st.test(e) and (i = i.reverse()) @pushStack(i) ) b.extend( filter: (e, t, n) -> n and (e = ":not(" + e + ")") (if 1 is t.length then (if b.find.matchesSelector(t[0], e) then [t[0]] else []) else b.find.matches(e, t)) dir: (e, n, r) -> i = [] o = e[n] while o and 9 isnt o.nodeType and (r is t or 1 isnt o.nodeType or not b(o).is(r)) 1 is o.nodeType and i.push(o) o = o[n] i sibling: (e, t) -> n = [] while e 1 is e.nodeType and e isnt t and n.push(e) e = e.nextSibling n ) ht = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video" gt = RegExp(" jQuery\\d+=\"(?:null|\\d+)\"", "g") mt = RegExp("<(?:" + ht + ")[\\s/>]", "i") yt = /^\s+/ vt = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/g bt = /<([\w:]+)/ xt = /<tbody/i wt = /<|&#?\w+;/ Tt = /<(?:script|style|link)/i Nt = /^(?:checkbox|radio)$/i Ct = /checked\s*(?:[^=]|=\s*.checked.)/i kt = /^$|\/(?:java|ecma)script/i Et = /^true\/(.*)/ St = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g At = option: [1, "<select multiple='multiple'>", "</select>"] legend: [1, "<fieldset>", "</fieldset>"] area: [1, "<map>", "</map>"] param: [1, "<object>", "</object>"] thead: [1, "<table>", "</table>"] tr: [2, "<table><tbody>", "</tbody></table>"] col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"] td: [3, "<table><tbody><tr>", "</tr></tbody></table>"] _default: (if b.support.htmlSerialize then [0, "", ""] else [1, "X<div>", "</div>"]) jt = dt(o) Dt = jt.appendChild(o.createElement("div")) At.optgroup = At.option At.tbody = At.tfoot = At.colgroup = At.caption = At.thead At.th = At.td b.fn.extend( text: (e) -> b.access this, ((e) -> (if e is t then b.text(this) else @empty().append((this[0] and this[0].ownerDocument or o).createTextNode(e))) ), null, e, arguments_.length wrapAll: (e) -> if b.isFunction(e) return @each((t) -> b(this).wrapAll e.call(this, t) ) if this[0] t = b(e, this[0].ownerDocument).eq(0).clone(not 0) this[0].parentNode and t.insertBefore(this[0]) t.map(-> e = this e = e.firstChild while e.firstChild and 1 is e.firstChild.nodeType e ).append(this) this wrapInner: (e) -> (if b.isFunction(e) then @each((t) -> b(this).wrapInner e.call(this, t) ) else @each(-> t = b(this) n = t.contents() (if n.length then n.wrapAll(e) else t.append(e)) )) wrap: (e) -> t = b.isFunction(e) @each (n) -> b(this).wrapAll (if t then e.call(this, n) else e) unwrap: -> @parent().each(-> b.nodeName(this, "body") or b(this).replaceWith(@childNodes) ).end() append: -> @domManip arguments_, not 0, (e) -> (1 is @nodeType or 11 is @nodeType or 9 is @nodeType) and @appendChild(e) prepend: -> @domManip arguments_, not 0, (e) -> (1 is @nodeType or 11 is @nodeType or 9 is @nodeType) and @insertBefore(e, @firstChild) before: -> @domManip arguments_, not 1, (e) -> @parentNode and @parentNode.insertBefore(e, this) after: -> @domManip arguments_, not 1, (e) -> @parentNode and @parentNode.insertBefore(e, @nextSibling) remove: (e, t) -> n = undefined r = 0 while null isnt (n = this[r]) (not e or b.filter(e, [n]).length > 0) and (t or 1 isnt n.nodeType or b.cleanData(Ot(n)) n.parentNode and (t and b.contains(n.ownerDocument, n) and Mt(Ot(n, "script")) n.parentNode.removeChild(n) ) ) r++ this empty: -> e = undefined t = 0 while null isnt (e = this[t]) 1 is e.nodeType and b.cleanData(Ot(e, not 1)) e.removeChild e.firstChild while e.firstChild e.options and b.nodeName(e, "select") and (e.options.length = 0) t++ this clone: (e, t) -> e = (if null is e then not 1 else e) t = (if null is t then e else t) @map(-> b.clone this, e, t ) html: (e) -> b.access this, ((e) -> n = this[0] or {} r = 0 i = @length return (if 1 is n.nodeType then n.innerHTML.replace(gt, "") else t) if e is t unless "string" isnt typeof e or Tt.test(e) or not b.support.htmlSerialize and mt.test(e) or not b.support.leadingWhitespace and yt.test(e) or At[(bt.exec(e) or ["", ""])[1].toLowerCase()] e = e.replace(vt, "<$1></$2>") try while i > r n = this[r] or {} 1 is n.nodeType and (b.cleanData(Ot(n, not 1)) n.innerHTML = e ) r++ n = 0 n and @empty().append(e) ), null, e, arguments_.length replaceWith: (e) -> t = b.isFunction(e) t or "string" is typeof e or (e = b(e).not(this).detach()) @domManip([e], not 0, (e) -> t = @nextSibling n = @parentNode n and (b(this).remove() n.insertBefore(e, t) ) ) detach: (e) -> @remove e, not 0 domManip: (e, n, r) -> e = f.apply([], e) i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = 0 p = @length d = this h = p - 1 g = e[0] m = b.isFunction(g) if m or not (1 >= p or "string" isnt typeof g or b.support.checkClone) and Ct.test(g) return @each((i) -> o = d.eq(i) m and (e[0] = g.call(this, i, (if n then o.html() else t))) o.domManip(e, n, r) ) if p and (l = b.buildFragment(e, this[0].ownerDocument, not 1, this) i = l.firstChild 1 is l.childNodes.length and (l = i) i ) n = n and b.nodeName(i, "tr") s = b.map(Ot(l, "script"), Ht) a = s.length while p > c o = l c isnt h and (o = b.clone(o, not 0, not 0) a and b.merge(s, Ot(o, "script")) ) r.call((if n and b.nodeName(this[c], "table") then Lt(this[c], "tbody") else this[c]), o, c) c++ if a u = s[s.length - 1].ownerDocument b.map(s, qt) c = 0 while a > c o = s[c] kt.test(o.type or "") and not b._data(o, "globalEval") and b.contains(u, o) and ((if o.src then b.ajax( url: o.src type: "GET" dataType: "script" async: not 1 global: not 1 throws: not 0 ) else b.globalEval((o.text or o.textContent or o.innerHTML or "").replace(St, "")))) c++ l = i = null this ) b.each appendTo: "append" prependTo: "prepend" insertBefore: "before" insertAfter: "after" replaceAll: "replaceWith" , (e, t) -> b.fn[e] = (e) -> n = undefined r = 0 i = [] o = b(e) a = o.length - 1 while a >= r n = (if r is a then this else @clone(not 0)) b(o[r])[t](n) d.apply(i, n.get()) r++ @pushStack i b.extend clone: (e, t, n) -> r = undefined i = undefined o = undefined a = undefined s = undefined u = b.contains(e.ownerDocument, e) if (if b.support.html5Clone or b.isXMLDoc(e) or not mt.test("<" + e.nodeName + ">") then o = e.cloneNode(not 0) else (Dt.innerHTML = e.outerHTML Dt.removeChild(o = Dt.firstChild) )) not (b.support.noCloneEvent and b.support.noCloneChecked or 1 isnt e.nodeType and 11 isnt e.nodeType or b.isXMLDoc(e)) r = Ot(o) s = Ot(e) a = 0 while null isnt (i = s[a]) r[a] and Ft(i, r[a]) ++a if t if n s = s or Ot(e) r = r or Ot(o) a = 0 while null isnt (i = s[a]) _t i, r[a] a++ else _t e, o r = Ot(o, "script") r.length > 0 and Mt(r, not u and Ot(e, "script")) r = s = i = null o buildFragment: (e, t, n, r) -> i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = e.length f = dt(t) d = [] h = 0 while p > h if o = e[h] o or 0 is o if "object" is b.type(o) b.merge d, (if o.nodeType then [o] else o) else if wt.test(o) s = s or f.appendChild(t.createElement("div")) u = (bt.exec(o) or ["", ""])[1].toLowerCase() c = At[u] or At._default s.innerHTML = c[1] + o.replace(vt, "<$1></$2>") + c[2] i = c[0] s = s.lastChild while i-- if not b.support.leadingWhitespace and yt.test(o) and d.push(t.createTextNode(yt.exec(o)[0])) not b.support.tbody o = (if "table" isnt u or xt.test(o) then (if "<table>" isnt c[1] or xt.test(o) then 0 else s) else s.firstChild) i = o and o.childNodes.length b.nodeName(l = o.childNodes[i], "tbody") and not l.childNodes.length and o.removeChild(l) while i-- b.merge(d, s.childNodes) s.textContent = "" s.removeChild s.firstChild while s.firstChild s = f.lastChild else d.push t.createTextNode(o) h++ s and f.removeChild(s) b.support.appendChecked or b.grep(Ot(d, "input"), Bt) h = 0 while o = d[h++] if (not r or -1 is b.inArray(o, r)) and (a = b.contains(o.ownerDocument, o) s = Ot(f.appendChild(o), "script") a and Mt(s) n ) i = 0 kt.test(o.type or "") and n.push(o) while o = s[i++] s = null f cleanData: (e, t) -> n = undefined r = undefined o = undefined a = undefined s = 0 u = b.expando l = b.cache p = b.support.deleteExpando f = b.event.special while null isnt (n = e[s]) if (t or b.acceptData(n)) and (o = n[u] a = o and l[o] ) if a.events for r of a.events (if f[r] then b.event.remove(n, r) else b.removeEvent(n, r, a.handle)) l[o] and (delete l[o] (if p then delete n[u] else (if typeof n.removeAttribute isnt i then n.removeAttribute(u) else n[u] = null)) c.push(o) ) s++ Pt = undefined Rt = undefined Wt = undefined $t = /alpha\([^)]*\)/i It = /opacity\s*=\s*([^)]*)/ zt = /^(top|right|bottom|left)$/ Xt = /^(none|table(?!-c[ea]).+)/ Ut = /^margin/ Vt = RegExp("^(" + x + ")(.*)$", "i") Yt = RegExp("^(" + x + ")(?!px)[a-z%]+$", "i") Jt = RegExp("^([+-])=(" + x + ")", "i") Gt = BODY: "block" Qt = position: "absolute" visibility: "hidden" display: "block" Kt = letterSpacing: 0 fontWeight: 400 Zt = ["Top", "Right", "Bottom", "Left"] en = ["Webkit", "O", "Moz", "ms"] b.fn.extend( css: (e, n) -> b.access this, ((e, n, r) -> i = undefined o = undefined a = {} s = 0 if b.isArray(n) o = Rt(e) i = n.length while i > s a[n[s]] = b.css(e, n[s], not 1, o) s++ return a (if r isnt t then b.style(e, n, r) else b.css(e, n)) ), e, n, arguments_.length > 1 show: -> rn this, not 0 hide: -> rn this toggle: (e) -> t = "boolean" is typeof e @each -> (if ((if t then e else nn(this))) then b(this).show() else b(this).hide()) ) b.extend( cssHooks: opacity: get: (e, t) -> if t n = Wt(e, "opacity") (if "" is n then "1" else n) cssNumber: columnCount: not 0 fillOpacity: not 0 fontWeight: not 0 lineHeight: not 0 opacity: not 0 orphans: not 0 widows: not 0 zIndex: not 0 zoom: not 0 cssProps: float: (if b.support.cssFloat then "cssFloat" else "styleFloat") style: (e, n, r, i) -> if e and 3 isnt e.nodeType and 8 isnt e.nodeType and e.style o = undefined a = undefined s = undefined u = b.camelCase(n) l = e.style return (if s and "get" of s and (o = s.get(e, not 1, i)) isnt t then o else l[n]) if n = b.cssProps[u] or (b.cssProps[u] = tn(l, u)) s = b.cssHooks[n] or b.cssHooks[u] r is t if a = typeof r "string" is a and (o = Jt.exec(r)) and (r = (o[1] + 1) * o[2] + parseFloat(b.css(e, n)) a = "number" ) not (null is r or "number" is a and isNaN(r) or ("number" isnt a or b.cssNumber[u] or (r += "px") b.support.clearCloneStyle or "" isnt r or 0 isnt n.indexOf("background") or (l[n] = "inherit") s and "set" of s and (r = s.set(e, r, i)) is t )) try l[n] = r css: (e, n, r, i) -> o = undefined a = undefined s = undefined u = b.camelCase(n) n = b.cssProps[u] or (b.cssProps[u] = tn(e.style, u)) s = b.cssHooks[n] or b.cssHooks[u] s and "get" of s and (a = s.get(e, not 0, r)) a is t and (a = Wt(e, n, i)) "normal" is a and n of Kt and (a = Kt[n]) (if "" is r or r then (o = parseFloat(a) (if r is not 0 or b.isNumeric(o) then o or 0 else a) ) else a) swap: (e, t, n, r) -> i = undefined o = undefined a = {} for o of t a[o] = e.style[o] e.style[o] = t[o] i = n.apply(e, r or []) for o of t e.style[o] = a[o] i ) (if e.getComputedStyle then (Rt = (t) -> e.getComputedStyle t, null Wt = (e, n, r) -> i = undefined o = undefined a = undefined s = r or Rt(e) u = (if s then s.getPropertyValue(n) or s[n] else t) l = e.style s and ("" isnt u or b.contains(e.ownerDocument, e) or (u = b.style(e, n)) Yt.test(u) and Ut.test(n) and (i = l.width o = l.minWidth a = l.maxWidth l.minWidth = l.maxWidth = l.width = u u = s.width l.width = i l.minWidth = o l.maxWidth = a ) ) u ) else o.documentElement.currentStyle and (Rt = (e) -> e.currentStyle Wt = (e, n, r) -> i = undefined o = undefined a = undefined s = r or Rt(e) u = (if s then s[n] else t) l = e.style null is u and l and l[n] and (u = l[n]) Yt.test(u) and not zt.test(n) and (i = l.left o = e.runtimeStyle a = o and o.left a and (o.left = e.currentStyle.left) l.left = (if "fontSize" is n then "1em" else u) u = l.pixelLeft + "px" l.left = i a and (o.left = a) ) (if "" is u then "auto" else u) )) b.each(["height", "width"], (e, n) -> b.cssHooks[n] = get: (e, r, i) -> (if r then (if 0 is e.offsetWidth and Xt.test(b.css(e, "display")) then b.swap(e, Qt, -> sn e, n, i ) else sn(e, n, i)) else t) set: (e, t, r) -> i = r and Rt(e) on_ e, t, (if r then an(e, n, r, b.support.boxSizing and "border-box" is b.css(e, "boxSizing", not 1, i), i) else 0) ) b.support.opacity or (b.cssHooks.opacity = get: (e, t) -> (if It.test(((if t and e.currentStyle then e.currentStyle.filter else e.style.filter)) or "") then .01 * parseFloat(RegExp.$1) + "" else (if t then "1" else "")) set: (e, t) -> n = e.style r = e.currentStyle i = (if b.isNumeric(t) then "alpha(opacity=" + 100 * t + ")" else "") o = r and r.filter or n.filter or "" n.zoom = 1 (t >= 1 or "" is t) and "" is b.trim(o.replace($t, "")) and n.removeAttribute and (n.removeAttribute("filter") "" is t or r and not r.filter ) or (n.filter = (if $t.test(o) then o.replace($t, i) else o + " " + i)) ) b(-> b.support.reliableMarginRight or (b.cssHooks.marginRight = get: (e, n) -> (if n then b.swap(e, display: "inline-block" , Wt, [e, "marginRight"]) else t) ) not b.support.pixelPosition and b.fn.position and b.each(["top", "left"], (e, n) -> b.cssHooks[n] = get: (e, r) -> (if r then (r = Wt(e, n) (if Yt.test(r) then b(e).position()[n] + "px" else r) ) else t) ) ) b.expr and b.expr.filters and (b.expr.filters.hidden = (e) -> 0 >= e.offsetWidth and 0 >= e.offsetHeight or not b.support.reliableHiddenOffsets and "none" is (e.style and e.style.display or b.css(e, "display")) b.expr.filters.visible = (e) -> not b.expr.filters.hidden(e) ) b.each( margin: "" padding: "" border: "Width" , (e, t) -> b.cssHooks[e + t] = expand: (n) -> r = 0 i = {} o = (if "string" is typeof n then n.split(" ") else [n]) while 4 > r i[e + Zt[r] + t] = o[r] or o[r - 2] or o[0] r++ i Ut.test(e) or (b.cssHooks[e + t].set = on_) ) cn = /%20/g pn = /\[\]$/ fn = /\r?\n/g dn = /^(?:submit|button|image|reset|file)$/i hn = /^(?:input|select|textarea|keygen)/i b.fn.extend( serialize: -> b.param @serializeArray() serializeArray: -> @map(-> e = b.prop(this, "elements") (if e then b.makeArray(e) else this) ).filter(-> e = @type @name and not b(this).is(":disabled") and hn.test(@nodeName) and not dn.test(e) and (@checked or not Nt.test(e)) ).map((e, t) -> n = b(this).val() (if null is n then null else (if b.isArray(n) then b.map(n, (e) -> name: t.name value: e.replace(fn, "\r\n") ) else name: t.name value: n.replace(fn, "\r\n") )) ).get() ) b.param = (e, n) -> r = undefined i = [] o = (e, t) -> t = (if b.isFunction(t) then t() else (if null is t then "" else t)) i[i.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t) if n is t and (n = b.ajaxSettings and b.ajaxSettings.traditional) b.isArray(e) or e.jquery and not b.isPlainObject(e) b.each e, -> o @name, @value else for r of e gn r, e[r], n, o i.join("&").replace cn, "+" b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "), (e, t) -> b.fn[t] = (e, n) -> (if arguments_.length > 0 then @on(t, null, e, n) else @trigger(t)) ) b.fn.hover = (e, t) -> @mouseenter(e).mouseleave t or e mn = undefined yn = undefined vn = b.now() bn = /\?/ xn = /#.*$/ wn = /([?&])_=[^&]*/ Tn = /^(.*?):[ \t]*([^\r\n]*)\r?$/g Nn = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/ Cn = /^(?:GET|HEAD)$/ kn = /^\/\// En = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/ Sn = b.fn.load An = {} jn = {} Dn = "*/".concat("*") try yn = a.href catch Ln yn = o.createElement("a") yn.href = "" yn = yn.href mn = En.exec(yn.toLowerCase()) or [] b.fn.load = (e, n, r) -> return Sn.apply(this, arguments_) if "string" isnt typeof e and Sn i = undefined o = undefined a = undefined s = this u = e.indexOf(" ") u >= 0 and (i = e.slice(u, e.length) e = e.slice(0, u) ) (if b.isFunction(n) then (r = n n = t ) else n and "object" is typeof n and (a = "POST")) s.length > 0 and b.ajax( url: e type: a dataType: "html" data: n ).done((e) -> o = arguments_ s.html((if i then b("<div>").append(b.parseHTML(e)).find(i) else e)) ).complete(r and (e, t) -> s.each r, o or [e.responseText, t, e] ) this b.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], (e, t) -> b.fn[t] = (e) -> @on t, e ) b.each(["get", "post"], (e, n) -> b[n] = (e, r, i, o) -> b.isFunction(r) and (o = o or i i = r r = t ) b.ajax( url: e type: n dataType: o data: r success: i ) ) b.extend( active: 0 lastModified: {} etag: {} ajaxSettings: url: yn type: "GET" isLocal: Nn.test(mn[1]) global: not 0 processData: not 0 async: not 0 contentType: "application/x-www-form-urlencoded; charset=UTF-8" accepts: "*": Dn text: "text/plain" html: "text/html" xml: "application/xml, text/xml" json: "application/json, text/javascript" contents: xml: /xml/ html: /html/ json: /json/ responseFields: xml: "responseXML" text: "responseText" converters: "* text": e.String "text html": not 0 "text json": b.parseJSON "text xml": b.parseXML flatOptions: url: not 0 context: not 0 ajaxSetup: (e, t) -> (if t then Mn(Mn(e, b.ajaxSettings), t) else Mn(b.ajaxSettings, e)) ajaxPrefilter: Hn(An) ajaxTransport: Hn(jn) ajax: (e, n) -> k = (e, n, r, i) -> c = undefined y = undefined v = undefined w = undefined T = undefined C = n 2 isnt x and (x = 2 s and clearTimeout(s) l = t a = i or "" N.readyState = (if e > 0 then 4 else 0) r and (w = _n(p, N, r)) (if e >= 200 and 300 > e or 304 is e then (p.ifModified and (T = N.getResponseHeader("Last-Modified") T and (b.lastModified[o] = T) T = N.getResponseHeader("etag") T and (b.etag[o] = T) ) (if 204 is e then (c = not 0 C = "nocontent" ) else (if 304 is e then (c = not 0 C = "notmodified" ) else (c = Fn(p, w) C = c.state y = c.data v = c.error c = not v ))) ) else (v = C (e or not C) and (C = "error" 0 > e and (e = 0) ) )) N.status = e N.statusText = (n or C) + "" (if c then h.resolveWith(f, [y, C, N]) else h.rejectWith(f, [N, C, v])) N.statusCode(m) m = t u and d.trigger((if c then "ajaxSuccess" else "ajaxError"), [N, p, (if c then y else v)]) g.fireWith(f, [N, C]) u and (d.trigger("ajaxComplete", [N, p]) --b.active or b.event.trigger("ajaxStop") ) ) "object" is typeof e and (n = e e = t ) n = n or {} r = undefined i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = b.ajaxSetup({}, n) f = p.context or p d = (if p.context and (f.nodeType or f.jquery) then b(f) else b.event) h = b.Deferred() g = b.Callbacks("once memory") m = p.statusCode or {} y = {} v = {} x = 0 T = "canceled" N = readyState: 0 getResponseHeader: (e) -> t = undefined if 2 is x unless c c = {} c[t[1].toLowerCase()] = t[2] while t = Tn.exec(a) t = c[e.toLowerCase()] (if null is t then null else t) getAllResponseHeaders: -> (if 2 is x then a else null) setRequestHeader: (e, t) -> n = e.toLowerCase() x or (e = v[n] = v[n] or e y[e] = t ) this overrideMimeType: (e) -> x or (p.mimeType = e) this statusCode: (e) -> t = undefined if e if 2 > x for t of e m[t] = [m[t], e[t]] else N.always e[N.status] this abort: (e) -> t = e or T l and l.abort(t) k(0, t) this return N if h.promise(N).complete = g.add N.success = N.done N.error = N.fail p.url = ((e or p.url or yn) + "").replace(xn, "").replace(kn, mn[1] + "//") p.type = n.method or n.type or p.method or p.type p.dataTypes = b.trim(p.dataType or "*").toLowerCase().match(w) or [""] null is p.crossDomain and (r = En.exec(p.url.toLowerCase()) p.crossDomain = not (not r or r[1] is mn[1] and r[2] is mn[2] and (r[3] or ((if "http:" is r[1] then 80 else 443))) is (mn[3] or ((if "http:" is mn[1] then 80 else 443)))) ) p.data and p.processData and "string" isnt typeof p.data and (p.data = b.param(p.data, p.traditional)) qn(An, p, n, N) 2 is x u = p.global u and 0 is b.active++ and b.event.trigger("ajaxStart") p.type = p.type.toUpperCase() p.hasContent = not Cn.test(p.type) o = p.url p.hasContent or (p.data and (o = p.url += ((if bn.test(o) then "&" else "?")) + p.data delete p.data ) p.cache is not 1 and (p.url = (if wn.test(o) then o.replace(wn, "$1_=" + vn++) else o + ((if bn.test(o) then "&" else "?")) + "_=" + vn++)) ) p.ifModified and (b.lastModified[o] and N.setRequestHeader("If-Modified-Since", b.lastModified[o]) b.etag[o] and N.setRequestHeader("If-None-Match", b.etag[o]) ) (p.data and p.hasContent and p.contentType isnt not 1 or n.contentType) and N.setRequestHeader("Content-Type", p.contentType) N.setRequestHeader("Accept", (if p.dataTypes[0] and p.accepts[p.dataTypes[0]] then p.accepts[p.dataTypes[0]] + ((if "*" isnt p.dataTypes[0] then ", " + Dn + "; q=0.01" else "")) else p.accepts["*"])) for i of p.headers N.setRequestHeader i, p.headers[i] return N.abort() if p.beforeSend and (p.beforeSend.call(f, N, p) is not 1 or 2 is x) T = "abort" for i of success: 1 error: 1 complete: 1 N[i] p[i] if l = qn(jn, p, n, N) N.readyState = 1 u and d.trigger("ajaxSend", [N, p]) p.async and p.timeout > 0 and (s = setTimeout(-> N.abort "timeout" , p.timeout)) try x = 1 l.send(y, k) catch C throw C unless 2 > x k -1, C else k -1, "No Transport" N getScript: (e, n) -> b.get e, t, n, "script" getJSON: (e, t, n) -> b.get e, t, n, "json" ) b.ajaxSetup( accepts: script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" contents: script: /(?:java|ecma)script/ converters: "text script": (e) -> b.globalEval(e) e ) b.ajaxPrefilter("script", (e) -> e.cache is t and (e.cache = not 1) e.crossDomain and (e.type = "GET" e.global = not 1 ) ) b.ajaxTransport("script", (e) -> if e.crossDomain n = undefined r = o.head or b("head")[0] or o.documentElement send: (t, i) -> n = o.createElement("script") n.async = not 0 e.scriptCharset and (n.charset = e.scriptCharset) n.src = e.url n.onload = n.onreadystatechange = (e, t) -> (t or not n.readyState or /loaded|complete/.test(n.readyState)) and (n.onload = n.onreadystatechange = null n.parentNode and n.parentNode.removeChild(n) n = null t or i(200, "success") ) r.insertBefore(n, r.firstChild) abort: -> n and n.onload(t, not 0) ) On = [] Bn = /(=)\?(?=&|$)|\?\?/ b.ajaxSetup( jsonp: "callback" jsonpCallback: -> e = On.pop() or b.expando + "_" + vn++ this[e] = not 0 e ) b.ajaxPrefilter("json jsonp", (n, r, i) -> o = undefined a = undefined s = undefined u = n.jsonp isnt not 1 and ((if Bn.test(n.url) then "url" else "string" is typeof n.data and not (n.contentType or "").indexOf("application/x-www-form-urlencoded") and Bn.test(n.data) and "data")) (if u or "jsonp" is n.dataTypes[0] then (o = n.jsonpCallback = (if b.isFunction(n.jsonpCallback) then n.jsonpCallback() else n.jsonpCallback) (if u then n[u] = n[u].replace(Bn, "$1" + o) else n.jsonp isnt not 1 and (n.url += ((if bn.test(n.url) then "&" else "?")) + n.jsonp + "=" + o)) n.converters["script json"] = -> s or b.error(o + " was not called") s[0] n.dataTypes[0] = "json" a = e[o] e[o] = -> s = arguments_ i.always(-> e[o] = a n[o] and (n.jsonpCallback = r.jsonpCallback On.push(o) ) s and b.isFunction(a) and a(s[0]) s = a = t ) "script" ) else t) ) Pn = undefined Rn = undefined Wn = 0 $n = e.ActiveXObject and -> e = undefined for e of Pn Pn[e] t, not 0 b.ajaxSettings.xhr = (if e.ActiveXObject then -> not @isLocal and In() or zn() else In) Rn = b.ajaxSettings.xhr() b.support.cors = !!Rn and "withCredentials" of Rn Rn = b.support.ajax = !!Rn Rn and b.ajaxTransport((n) -> if not n.crossDomain or b.support.cors r = undefined send: (i, o) -> a = undefined s = undefined u = n.xhr() if (if n.username then u.open(n.type, n.url, n.async, n.username, n.password) else u.open(n.type, n.url, n.async)) n.xhrFields for s of n.xhrFields u[s] = n.xhrFields[s] n.mimeType and u.overrideMimeType and u.overrideMimeType(n.mimeType) n.crossDomain or i["X-Requested-With"] or (i["X-Requested-With"] = "XMLHttpRequest") try for s of i u.setRequestHeader s, i[s] u.send(n.hasContent and n.data or null) r = (e, i) -> s = undefined l = undefined c = undefined p = undefined try if r and (i or 4 is u.readyState) unless r = t a and (u.onreadystatechange = b.noop $n and delete Pn[a] ) i p = {} s = u.status l = u.getAllResponseHeaders() "string" is typeof u.responseText and (p.text = u.responseText) try c = u.statusText catch f c = "" (if s or not n.isLocal or n.crossDomain then 1223 is s and (s = 204) else s = (if p.text then 200 else 404)) catch d i or o(-1, d) p and o(s, c, p, l) (if n.async then (if 4 is u.readyState then setTimeout(r) else (a = ++Wn $n and (Pn or (Pn = {} b(e).unload($n) ) Pn[a] = r ) u.onreadystatechange = r )) else r()) abort: -> r and r(t, not 0) ) Xn = undefined Un = undefined Vn = /^(?:toggle|show|hide)$/ Yn = RegExp("^(?:([+-])=|)(" + x + ")([a-z%]*)$", "i") Jn = /queueHooks$/ Gn = [nr] Qn = "*": [(e, t) -> n = undefined r = undefined i = @createTween(e, t) o = Yn.exec(t) a = i.cur() s = +a or 0 u = 1 l = 20 if o if n = +o[2] r = o[3] or ((if b.cssNumber[e] then "" else "px")) "px" isnt r and s s = b.css(i.elem, e, not 0) or n or 1 loop u = u or ".5" s /= u b.style(i.elem, e, s + r) break unless u isnt (u = i.cur() / a) and 1 isnt u and --l i.unit = r i.start = s i.end = (if o[1] then s + (o[1] + 1) * n else n) i ] b.Animation = b.extend(er, tweener: (e, t) -> (if b.isFunction(e) then (t = e e = ["*"] ) else e = e.split(" ")) n = undefined r = 0 i = e.length while i > r n = e[r] Qn[n] = Qn[n] or [] Qn[n].unshift(t) r++ prefilter: (e, t) -> (if t then Gn.unshift(e) else Gn.push(e)) ) b.Tween = rr rr:: = constructor: rr init: (e, t, n, r, i, o) -> @elem = e @prop = n @easing = i or "swing" @options = t @start = @now = @cur() @end = r @unit = o or ((if b.cssNumber[n] then "" else "px")) cur: -> e = rr.propHooks[@prop] (if e and e.get then e.get(this) else rr.propHooks._default.get(this)) run: (e) -> t = undefined n = rr.propHooks[@prop] @pos = t = (if @options.duration then b.easing[@easing](e, @options.duration * e, 0, 1, @options.duration) else e) @now = (@end - @start) * t + @start @options.step and @options.step.call(@elem, @now, this) (if n and n.set then n.set(this) else rr.propHooks._default.set(this)) this rr::init:: = rr:: rr.propHooks = _default: get: (e) -> t = undefined (if null is e.elem[e.prop] or e.elem.style and null isnt e.elem.style[e.prop] then (t = b.css(e.elem, e.prop, "") (if t and "auto" isnt t then t else 0) ) else e.elem[e.prop]) set: (e) -> (if b.fx.step[e.prop] then b.fx.step[e.prop](e) else (if e.elem.style and (null isnt e.elem.style[b.cssProps[e.prop]] or b.cssHooks[e.prop]) then b.style(e.elem, e.prop, e.now + e.unit) else e.elem[e.prop] = e.now)) rr.propHooks.scrollTop = rr.propHooks.scrollLeft = set: (e) -> e.elem.nodeType and e.elem.parentNode and (e.elem[e.prop] = e.now) b.each(["toggle", "show", "hide"], (e, t) -> n = b.fn[t] b.fn[t] = (e, r, i) -> (if null is e or "boolean" is typeof e then n.apply(this, arguments_) else @animate(ir(t, not 0), e, r, i)) ) b.fn.extend( fadeTo: (e, t, n, r) -> @filter(nn).css("opacity", 0).show().end().animate opacity: t , e, n, r animate: (e, t, n, r) -> i = b.isEmptyObject(e) o = b.speed(t, n, r) a = -> t = er(this, b.extend({}, e), o) a.finish = -> t.stop not 0 (i or b._data(this, "finish")) and t.stop(not 0) a.finish = a (if i or o.queue is not 1 then @each(a) else @queue(o.queue, a)) stop: (e, n, r) -> i = (e) -> t = e.stop delete e.stop t(r) "string" isnt typeof e and (r = n n = e e = t ) n and e isnt not 1 and @queue(e or "fx", []) @each(-> t = not 0 n = null isnt e and e + "queueHooks" o = b.timers a = b._data(this) if n a[n] and a[n].stop and i(a[n]) else for n of a a[n] and a[n].stop and Jn.test(n) and i(a[n]) n = o.length while n-- o[n].elem isnt this or null isnt e and o[n].queue isnt e or (o[n].anim.stop(r) t = not 1 o.splice(n, 1) ) (t or not r) and b.dequeue(this, e) ) finish: (e) -> e isnt not 1 and (e = e or "fx") @each(-> t = undefined n = b._data(this) r = n[e + "queue"] i = n[e + "queueHooks"] o = b.timers a = (if r then r.length else 0) n.finish = not 0 b.queue(this, e, []) i and i.cur and i.cur.finish and i.cur.finish.call(this) t = o.length while t-- o[t].elem is this and o[t].queue is e and (o[t].anim.stop(not 0) o.splice(t, 1) ) t = 0 while a > t r[t] and r[t].finish and r[t].finish.call(this) t++ delete n.finish ) ) b.each( slideDown: ir("show") slideUp: ir("hide") slideToggle: ir("toggle") fadeIn: opacity: "show" fadeOut: opacity: "hide" fadeToggle: opacity: "toggle" , (e, t) -> b.fn[e] = (e, n, r) -> @animate t, e, n, r ) b.speed = (e, t, n) -> r = (if e and "object" is typeof e then b.extend({}, e) else complete: n or not n and t or b.isFunction(e) and e duration: e easing: n and t or t and not b.isFunction(t) and t ) r.duration = (if b.fx.off then 0 else (if "number" is typeof r.duration then r.duration else (if r.duration of b.fx.speeds then b.fx.speeds[r.duration] else b.fx.speeds._default))) (null is r.queue or r.queue is not 0) and (r.queue = "fx") r.old = r.complete r.complete = -> b.isFunction(r.old) and r.old.call(this) r.queue and b.dequeue(this, r.queue) r b.easing = linear: (e) -> e swing: (e) -> .5 - Math.cos(e * Math.PI) / 2 b.timers = [] b.fx = rr::init b.fx.tick = -> e = undefined n = b.timers r = 0 Xn = b.now() while n.length > r e = n[r] e() or n[r] isnt e or n.splice(r--, 1) r++ n.length or b.fx.stop() Xn = t b.fx.timer = (e) -> e() and b.timers.push(e) and b.fx.start() b.fx.interval = 13 b.fx.start = -> Un or (Un = setInterval(b.fx.tick, b.fx.interval)) b.fx.stop = -> clearInterval(Un) Un = null b.fx.speeds = slow: 600 fast: 200 _default: 400 b.fx.step = {} b.expr and b.expr.filters and (b.expr.filters.animated = (e) -> b.grep(b.timers, (t) -> e is t.elem ).length ) b.fn.offset = (e) -> if arguments_.length return (if e is t then this else @each((t) -> b.offset.setOffset this, e, t )) n = undefined r = undefined o = top: 0 left: 0 a = this[0] s = a and a.ownerDocument if s n = s.documentElement (if b.contains(n, a) then (typeof a.getBoundingClientRect isnt i and (o = a.getBoundingClientRect()) r = or_(s) top: o.top + (r.pageYOffset or n.scrollTop) - (n.clientTop or 0) left: o.left + (r.pageXOffset or n.scrollLeft) - (n.clientLeft or 0) ) else o) b.offset = setOffset: (e, t, n) -> r = b.css(e, "position") "static" is r and (e.style.position = "relative") i = b(e) o = i.offset() a = b.css(e, "top") s = b.css(e, "left") u = ("absolute" is r or "fixed" is r) and b.inArray("auto", [a, s]) > -1 l = {} c = {} p = undefined f = undefined (if u then (c = i.position() p = c.top f = c.left ) else (p = parseFloat(a) or 0 f = parseFloat(s) or 0 )) b.isFunction(t) and (t = t.call(e, n, o)) null isnt t.top and (l.top = t.top - o.top + p) null isnt t.left and (l.left = t.left - o.left + f) (if "using" of t then t.using.call(e, l) else i.css(l)) b.fn.extend( position: -> if this[0] e = undefined t = undefined n = top: 0 left: 0 r = this[0] (if "fixed" is b.css(r, "position") then t = r.getBoundingClientRect() else (e = @offsetParent() t = @offset() b.nodeName(e[0], "html") or (n = e.offset()) n.top += b.css(e[0], "borderTopWidth", not 0) n.left += b.css(e[0], "borderLeftWidth", not 0) )) top: t.top - n.top - b.css(r, "marginTop", not 0) left: t.left - n.left - b.css(r, "marginLeft", not 0) offsetParent: -> @map -> e = @offsetParent or o.documentElement e = e.offsetParent while e and not b.nodeName(e, "html") and "static" is b.css(e, "position") e or o.documentElement ) b.each( scrollLeft: "pageXOffset" scrollTop: "pageYOffset" , (e, n) -> r = /Y/.test(n) b.fn[e] = (i) -> b.access this, ((e, i, o) -> a = or_(e) (if o is t then (if a then (if n of a then a[n] else a.document.documentElement[i]) else e[i]) else ((if a then a.scrollTo((if r then b(a).scrollLeft() else o), (if r then o else b(a).scrollTop())) else e[i] = o) t )) ), e, i, arguments_.length, null ) b.each( Height: "height" Width: "width" , (e, n) -> b.each padding: "inner" + e content: n "": "outer" + e , (r, i) -> b.fn[i] = (i, o) -> a = arguments_.length and (r or "boolean" isnt typeof i) s = r or ((if i is not 0 or o is not 0 then "margin" else "border")) b.access this, ((n, r, i) -> o = undefined (if b.isWindow(n) then n.document.documentElement["client" + e] else (if 9 is n.nodeType then (o = n.documentElement Math.max(n.body["scroll" + e], o["scroll" + e], n.body["offset" + e], o["offset" + e], o["client" + e]) ) else (if i is t then b.css(n, r, s) else b.style(n, r, i, s)))) ), n, (if a then i else t), a, null ) e.jQuery = e.$ = b "function" is typeof define and define.amd and define.amd.jQuery and define("jquery", [], -> b ) ) window
true
#! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license # ((e, t) -> M = (e) -> t = e.length n = b.type(e) (if b.isWindow(e) then not 1 else (if 1 is e.nodeType and t then not 0 else "array" is n or "function" isnt n and (0 is t or "number" is typeof t and t > 0 and t - 1 of e))) F = (e) -> t = _[e] = {} b.each(e.match(w) or [], (e, n) -> t[n] = not 0 ) t P = (e, n, r, i) -> if b.acceptData(e) o = undefined a = undefined s = b.expando u = "string" is typeof n l = e.nodeType p = (if l then b.cache else e) f = (if l then e[s] else e[s] and s) if f and p[f] and (i or p[f].data) or not u or r isnt t f or ((if l then e[s] = f = c.pop() or b.guid++ else f = s)) p[f] or (p[f] = {} l or (p[f].toJSON = b.noop) ) ("object" is typeof n or "function" is typeof n) and ((if i then p[f] = b.extend(p[f], n) else p[f].data = b.extend(p[f].data, n))) o = p[f] i or (o.data or (o.data = {}) o = o.data ) r isnt t and (o[b.camelCase(n)] = r) (if u then (a = o[n] null is a and (a = o[b.camelCase(n)]) ) else a = o) a R = (e, t, n) -> if b.acceptData(e) r = undefined i = undefined o = undefined a = e.nodeType s = (if a then b.cache else e) u = (if a then e[b.expando] else b.expando) if s[u] if t and (o = (if n then s[u] else s[u].data)) (if b.isArray(t) then t = t.concat(b.map(t, b.camelCase)) else (if t of o then t = [t] else (t = b.camelCase(t) t = (if t of o then [t] else t.split(" ")) ))) r = 0 i = t.length while i > r delete o[t[r]] r++ return unless ((if n then $ else b.isEmptyObject))(o) (n or (delete s[u].data $(s[u]) )) and ((if a then b.cleanData([e], not 0) else (if b.support.deleteExpando or s isnt s.window then delete s[u] else s[u] = null))) W = (e, n, r) -> if r is t and 1 is e.nodeType i = "data-" + n.replace(B, "-$1").toLowerCase() if r = e.getAttribute(i) "string" is typeof r try r = (if "true" is r then not 0 else (if "false" is r then not 1 else (if "null" is r then null else (if +r + "" is r then +r else (if O.test(r) then b.parseJSON(r) else r))))) b.data e, n, r else r = t r $ = (e) -> t = undefined for t of e return not 1 if ("data" isnt t or not b.isEmptyObject(e[t])) and "toJSON" isnt t not 0 it = -> not 0 ot = -> not 1 pt = (e, t) -> loop e = e[t] break unless e and 1 isnt e.nodeType e ft = (e, t, n) -> if t = t or 0 b.isFunction(t) return b.grep(e, (e, r) -> i = !!t.call(e, r, e) i is n ) if t.nodeType return b.grep(e, (e) -> e is t is n ) if "string" is typeof t r = b.grep(e, (e) -> 1 is e.nodeType ) return b.filter(t, r, not n) if ut.test(t) t = b.filter(t, r) b.grep e, (e) -> b.inArray(e, t) >= 0 is n dt = (e) -> t = ht.split("|") n = e.createDocumentFragment() n.createElement t.pop() while t.length if n.createElement n Lt = (e, t) -> e.getElementsByTagName(t)[0] or e.appendChild(e.ownerDocument.createElement(t)) Ht = (e) -> t = e.getAttributeNode("type") e.type = (t and t.specified) + "/" + e.type e qt = (e) -> t = Et.exec(e.type) (if t then e.type = t[1] else e.removeAttribute("type")) e Mt = (e, t) -> n = undefined r = 0 while null isnt (n = e[r]) b._data n, "globalEval", not t or b._data(t[r], "globalEval") r++ _t = (e, t) -> if 1 is t.nodeType and b.hasData(e) n = undefined r = undefined i = undefined o = b._data(e) a = b._data(t, o) s = o.events if s delete a.handle a.events = {} for n of s r = 0 i = s[n].length while i > r b.event.add t, n, s[n][r] r++ a.data and (a.data = b.extend({}, a.data)) Ft = (e, t) -> n = undefined r = undefined i = undefined if 1 is t.nodeType if n = t.nodeName.toLowerCase() not b.support.noCloneEvent and t[b.expando] i = b._data(t) for r of i.events b.removeEvent t, r, i.handle t.removeAttribute b.expando (if "script" is n and t.text isnt e.text then (Ht(t).text = e.text qt(t) ) else (if "object" is n then (t.parentNode and (t.outerHTML = e.outerHTML) b.support.html5Clone and e.innerHTML and not b.trim(t.innerHTML) and (t.innerHTML = e.innerHTML) ) else (if "input" is n and Nt.test(e.type) then (t.defaultChecked = t.checked = e.checked t.value isnt e.value and (t.value = e.value) ) else (if "option" is n then t.defaultSelected = t.selected = e.defaultSelected else ("input" is n or "textarea" is n) and (t.defaultValue = e.defaultValue))))) Ot = (e, n) -> r = undefined o = undefined a = 0 s = (if typeof e.getElementsByTagName isnt i then e.getElementsByTagName(n or "*") else (if typeof e.querySelectorAll isnt i then e.querySelectorAll(n or "*") else t)) unless s s = [] r = e.childNodes or e while null isnt (o = r[a]) (if not n or b.nodeName(o, n) then s.push(o) else b.merge(s, Ot(o, n))) a++ (if n is t or n and b.nodeName(e, n) then b.merge([e], s) else s) Bt = (e) -> Nt.test(e.type) and (e.defaultChecked = e.checked) tn = (e, t) -> return t if t of e n = t.charAt(0).toUpperCase() + t.slice(1) r = t i = en.length while i-- return t if t = en[i] + n t of e r nn = (e, t) -> e = t or e "none" is b.css(e, "display") or not b.contains(e.ownerDocument, e) rn = (e, t) -> n = undefined r = undefined i = undefined o = [] a = 0 s = e.length while s > a r = e[a] r.style and (o[a] = b._data(r, "olddisplay") n = r.style.display (if t then (o[a] or "none" isnt n or (r.style.display = "") "" is r.style.display and nn(r) and (o[a] = b._data(r, "olddisplay", un(r.nodeName))) ) else o[a] or (i = nn(r) (n and "none" isnt n or not i) and b._data(r, "olddisplay", (if i then n else b.css(r, "display"))) )) ) a++ a = 0 while s > a r = e[a] r.style and (t and "none" isnt r.style.display and "" isnt r.style.display or (r.style.display = (if t then o[a] or "" else "none"))) a++ e on = (e, t, n) -> r = Vt.exec(t) (if r then Math.max(0, r[1] - (n or 0)) + (r[2] or "px") else t) an = (e, t, n, r, i) -> o = (if n is ((if r then "border" else "content")) then 4 else (if "width" is t then 1 else 0)) a = 0 while 4 > o "margin" is n and (a += b.css(e, n + Zt[o], not 0, i)) (if r then ("content" is n and (a -= b.css(e, "padding" + Zt[o], not 0, i)) "margin" isnt n and (a -= b.css(e, "border" + Zt[o] + "Width", not 0, i)) ) else (a += b.css(e, "padding" + Zt[o], not 0, i) "padding" isnt n and (a += b.css(e, "border" + Zt[o] + "Width", not 0, i)) )) o += 2 a sn = (e, t, n) -> r = not 0 i = (if "width" is t then e.offsetWidth else e.offsetHeight) o = Rt(e) a = b.support.boxSizing and "border-box" is b.css(e, "boxSizing", not 1, o) if 0 >= i or null is i return i if i = Wt(e, t, o) (0 > i or null is i) and (i = e.style[t]) Yt.test(i) r = a and (b.support.boxSizingReliable or i is e.style[t]) i = parseFloat(i) or 0 i + an(e, t, n or ((if a then "border" else "content")), r, o) + "px" un = (e) -> t = o n = Gt[e] n or (n = ln(e, t) "none" isnt n and n or (Pt = (Pt or b("<iframe frameborder='0' width='0' height='0'/>").css("cssText", "display:block !important")).appendTo(t.documentElement) t = (Pt[0].contentWindow or Pt[0].contentDocument).document t.write("<!doctype html><html><body>") t.close() n = ln(e, t) Pt.detach() ) Gt[e] = n ) n ln = (e, t) -> n = b(t.createElement(e)).appendTo(t.body) r = b.css(n[0], "display") n.remove() r gn = (e, t, n, r) -> i = undefined if b.isArray(t) b.each t, (t, i) -> (if n or pn.test(e) then r(e, i) else gn(e + "[" + ((if "object" is typeof i then t else "")) + "]", i, n, r)) else if n or "object" isnt b.type(t) r e, t else for i of t gn e + "[" + i + "]", t[i], n, r Hn = (e) -> (t, n) -> "string" isnt typeof t and (n = t t = "*" ) r = undefined i = 0 o = t.toLowerCase().match(w) or [] if b.isFunction(n) while r = o[i++] (if "+" is r[0] then (r = r.slice(1) or "*" (e[r] = e[r] or []).unshift(n) ) else (e[r] = e[r] or []).push(n)) qn = (e, n, r, i) -> s = (u) -> l = undefined o[u] = not 0 b.each(e[u] or [], (e, u) -> c = u(n, r, i) (if "string" isnt typeof c or a or o[c] then (if a then not (l = c) else t) else (n.dataTypes.unshift(c) s(c) not 1 )) ) l o = {} a = e is jn s(n.dataTypes[0]) or not o["*"] and s("*") Mn = (e, n) -> r = undefined i = undefined o = b.ajaxSettings.flatOptions or {} for i of n n[i] isnt t and (((if o[i] then e else r or (r = {})))[i] = n[i]) r and b.extend(not 0, e, r) e _n = (e, n, r) -> i = undefined o = undefined a = undefined s = undefined u = e.contents l = e.dataTypes c = e.responseFields for s of c s of r and (n[c[s]] = r[s]) while "*" is l[0] l.shift() o is t and (o = e.mimeType or n.getResponseHeader("Content-Type")) if o for s of u if u[s] and u[s].test(o) l.unshift s break unless l[0] of r for s of r if not l[0] or e.converters[s + " " + l[0]] a = s break i or (i = s) a = a or i (if a then (a isnt l[0] and l.unshift(a) r[a] ) else t) Fn = (e, t) -> n = undefined r = undefined i = undefined o = undefined a = {} s = 0 u = e.dataTypes.slice() l = u[0] if e.dataFilter and (t = e.dataFilter(t, e.dataType)) u[1] for i of e.converters a[i.toLowerCase()] = e.converters[i] while r = u[++s] if "*" isnt r if "*" isnt l and l isnt r if i = a[l + " " + r] or a["* " + r] not i for n of a if o = n.split(" ") o[1] is r and (i = a[l + " " + o[0]] or a["* " + o[0]]) (if i is not 0 then i = a[n] else a[n] isnt not 0 and (r = o[0] u.splice(s--, 0, r) )) break if i isnt not 0 if i and e["throws"] t = i(t) else try t = i(t) catch c return ( state: "parsererror" error: (if i then c else "No conversion from " + l + " to " + r) ) l = r state: "success" data: t In = -> try return new e.XMLHttpRequest zn = -> try return new e.ActiveXObject("Microsoft.XMLHTTP") Kn = -> setTimeout(-> Xn = t ) Xn = b.now() Zn = (e, t) -> b.each t, (t, n) -> r = (Qn[t] or []).concat(Qn["*"]) i = 0 o = r.length while o > i return if r[i].call(e, t, n) i++ er = (e, t, n) -> r = undefined i = undefined o = 0 a = Gn.length s = b.Deferred().always(-> delete u.elem ) u = -> return not 1 if i t = Xn or Kn() n = Math.max(0, l.startTime + l.duration - t) r = n / l.duration or 0 o = 1 - r a = 0 u = l.tweens.length while u > a l.tweens[a].run o a++ s.notifyWith(e, [l, o, n]) (if 1 > o and u then n else (s.resolveWith(e, [l]) not 1 )) l = s.promise( elem: e props: b.extend({}, t) opts: b.extend(not 0, specialEasing: {} , n) originalProperties: t originalOptions: n startTime: Xn or Kn() duration: n.duration tweens: [] createTween: (t, n) -> r = b.Tween(e, l.opts, t, n, l.opts.specialEasing[t] or l.opts.easing) l.tweens.push(r) r stop: (t) -> n = 0 r = (if t then l.tweens.length else 0) return this if i i = not 0 while r > n l.tweens[n].run 1 n++ (if t then s.resolveWith(e, [l, t]) else s.rejectWith(e, [l, t])) this ) c = l.props tr(c, l.opts.specialEasing) while a > o return r if r = Gn[o].call(l, e, c, l.opts) o++ Zn(l, c) b.isFunction(l.opts.start) and l.opts.start.call(e, l) b.fx.timer(b.extend(u, elem: e anim: l queue: l.opts.queue )) l.progress(l.opts.progress).done(l.opts.done, l.opts.complete).fail(l.opts.fail).always(l.opts.always) tr = (e, t) -> n = undefined r = undefined i = undefined o = undefined a = undefined for i of e if r = b.camelCase(i) o = t[r] n = e[i] b.isArray(n) and (o = n[1] n = e[i] = n[0] ) i isnt r and (e[r] = n delete e[i] ) a = b.cssHooks[r] a and "expand" of a n = a.expand(n) delete e[r] for i of n i of e or (e[i] = n[i] t[i] = o ) else t[r] = o nr = (e, t, n) -> r = undefined i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = undefined f = this d = e.style h = {} g = [] m = e.nodeType and nn(e) n.queue or (c = b._queueHooks(e, "fx") null is c.unqueued and (c.unqueued = 0 p = c.empty.fire c.empty.fire = -> c.unqueued or p() ) c.unqueued++ f.always(-> f.always -> c.unqueued-- b.queue(e, "fx").length or c.empty.fire() ) ) 1 is e.nodeType and ("height" of t or "width" of t) and (n.overflow = [d.overflow, d.overflowX, d.overflowY] "inline" is b.css(e, "display") and "none" is b.css(e, "float") and ((if b.support.inlineBlockNeedsLayout and "inline" isnt un(e.nodeName) then d.zoom = 1 else d.display = "inline-block")) ) n.overflow and (d.overflow = "hidden" b.support.shrinkWrapBlocks or f.always(-> d.overflow = n.overflow[0] d.overflowX = n.overflow[1] d.overflowY = n.overflow[2] ) ) for i of t if a = t[i] Vn.exec(a) continue if delete t[i] u = u or "toggle" is a a is ((if m then "hide" else "show")) g.push i if o = g.length s = b._data(e, "fxshow") or b._data(e, "fxshow", {}) "hidden" of s and (m = s.hidden) u and (s.hidden = not m) (if m then b(e).show() else f.done(-> b(e).hide() )) f.done(-> t = undefined b._removeData e, "fxshow" for t of h b.style e, t, h[t] ) i = 0 while o > i r = g[i] l = f.createTween(r, (if m then s[r] else 0)) h[r] = s[r] or b.style(e, r) r of s or (s[r] = l.start m and (l.end = l.start l.start = (if "width" is r or "height" is r then 1 else 0) ) ) i++ rr = (e, t, n, r, i) -> new rr::init(e, t, n, r, i) ir = (e, t) -> n = undefined r = height: e i = 0 t = (if t then 1 else 0) while 4 > i n = Zt[i] r["margin" + n] = r["padding" + n] = e i += 2 - t t and (r.opacity = r.width = e) r or = (e) -> (if b.isWindow(e) then e else (if 9 is e.nodeType then e.defaultView or e.parentWindow else not 1)) n = undefined r = undefined i = typeof t o = e.document a = e.location s = e.jQuery u = e.$ l = {} c = [] p = "1.9.1" f = c.concat d = c.push h = c.slice g = c.indexOf m = l.toString y = l.hasOwnProperty v = p.trim b = (e, t) -> new b.fn.init(e, t, r) x = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source w = /\S+/g T = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g N = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/ C = /^<(\w+)\s*\/?>(?:<\/\1>|)$/ k = /^[\],:{}\s]*$/ E = /(?:^|:|,)(?:\s*\[)+/g S = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g A = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g j = /^-ms-/ D = /-([\da-z])/g L = (e, t) -> t.toUpperCase() H = (e) -> (o.addEventListener or "load" is e.type or "complete" is o.readyState) and (q() b.ready() ) q = -> (if o.addEventListener then (o.removeEventListener("DOMContentLoaded", H, not 1) e.removeEventListener("load", H, not 1) ) else (o.detachEvent("onreadystatechange", H) e.detachEvent("onload", H) )) b.fn = b:: = jquery: p constructor: b init: (e, n, r) -> i = undefined a = undefined return this unless e if "string" is typeof e return (if not n or n.jquery then (n or r).find(e) else @constructor(n).find(e)) if i = (if "<" is e.charAt(0) and ">" is e.charAt(e.length - 1) and e.length >= 3 then [null, e, null] else N.exec(e)) not i or not i[1] and n if i[1] if n = (if n instanceof b then n[0] else n) b.merge(this, b.parseHTML(i[1], (if n and n.nodeType then n.ownerDocument or n else o), not 0)) C.test(i[1]) and b.isPlainObject(n) for i of n (if b.isFunction(this[i]) then this[i](n[i]) else @attr(i, n[i])) return this if a = o.getElementById(i[2]) a and a.parentNode return r.find(e) if a.id isnt i[2] @length = 1 this[0] = a return @context = o @selector = e this (if e.nodeType then (@context = this[0] = e @length = 1 this ) else (if b.isFunction(e) then r.ready(e) else (e.selector isnt t and (@selector = e.selector @context = e.context ) b.makeArray(e, this) ))) selector: "" length: 0 size: -> @length toArray: -> h.call this get: (e) -> (if null is e then @toArray() else (if 0 > e then this[@length + e] else this[e])) pushStack: (e) -> t = b.merge(@constructor(), e) t.prevObject = this t.context = @context t each: (e, t) -> b.each this, e, t ready: (e) -> b.ready.promise().done(e) this slice: -> @pushStack h.apply(this, arguments_) first: -> @eq 0 last: -> @eq -1 eq: (e) -> t = @length n = +e + ((if 0 > e then t else 0)) @pushStack (if n >= 0 and t > n then [this[n]] else []) map: (e) -> @pushStack b.map(this, (t, n) -> e.call t, n, t ) end: -> @prevObject or @constructor(null) push: d sort: [].sort splice: [].splice b.fn.init:: = b.fn b.extend = b.fn.extend = -> e = undefined n = undefined r = undefined i = undefined o = undefined a = undefined s = arguments_[0] or {} u = 1 l = arguments_.length c = not 1 "boolean" is typeof s and (c = s s = arguments_[1] or {} u = 2 ) "object" is typeof s or b.isFunction(s) or (s = {}) l is u and (s = this --u ) while l > u unless null is (o = arguments_[u]) for i of o e = s[i] r = o[i] s isnt r and ((if c and r and (b.isPlainObject(r) or (n = b.isArray(r))) then ((if n then (n = not 1 a = (if e and b.isArray(e) then e else []) ) else a = (if e and b.isPlainObject(e) then e else {})) s[i] = b.extend(c, a, r) ) else r isnt t and (s[i] = r))) u++ s b.extend( noConflict: (t) -> e.$ is b and (e.$ = u) t and e.jQuery is b and (e.jQuery = s) b isReady: not 1 readyWait: 1 holdReady: (e) -> (if e then b.readyWait++ else b.ready(not 0)) ready: (e) -> if (if e is not 0 then not --b.readyWait else not b.isReady) return setTimeout(b.ready) unless o.body b.isReady = not 0 e isnt not 0 and --b.readyWait > 0 or (n.resolveWith(o, [b]) b.fn.trigger and b(o).trigger("ready").off("ready") ) isFunction: (e) -> "function" is b.type(e) isArray: Array.isArray or (e) -> "array" is b.type(e) isWindow: (e) -> null isnt e and e is e.window isNumeric: (e) -> not isNaN(parseFloat(e)) and isFinite(e) type: (e) -> (if null is e then e + "" else (if "object" is typeof e or "function" is typeof e then l[m.call(e)] or "object" else typeof e)) isPlainObject: (e) -> return not 1 if not e or "object" isnt b.type(e) or e.nodeType or b.isWindow(e) try return not 1 if e.constructor and not y.call(e, "constructor") and not y.call(e.constructor::, "isPrototypeOf") catch n return not 1 r = undefined for r of e r is t or y.call(e, r) isEmptyObject: (e) -> t = undefined for t of e return not 1 not 0 error: (e) -> throw Error(e) parseHTML: (e, t, n) -> return null if not e or "string" isnt typeof e "boolean" is typeof t and (n = t t = not 1 ) t = t or o r = C.exec(e) i = not n and [] (if r then [t.createElement(r[1])] else (r = b.buildFragment([e], t, i) i and b(i).remove() b.merge([], r.childNodes) )) parseJSON: (n) -> (if e.JSON and e.JSON.parse then e.JSON.parse(n) else (if null is n then n else (if "string" is typeof n and (n = b.trim(n) n and k.test(n.replace(S, "@").replace(A, "]").replace(E, "")) ) then Function("return " + n)() else (b.error("Invalid JSON: " + n) t )))) parseXML: (n) -> r = undefined i = undefined return null if not n or "string" isnt typeof n try (if e.DOMParser then (i = new DOMParser r = i.parseFromString(n, "text/xml") ) else (r = new ActiveXObject("Microsoft.XMLDOM") r.async = "false" r.loadXML(n) )) catch o r = t r and r.documentElement and not r.getElementsByTagName("parsererror").length or b.error("Invalid XML: " + n) r noop: -> globalEval: (t) -> t and b.trim(t) and (e.execScript or (t) -> e.eval.call e, t )(t) camelCase: (e) -> e.replace(j, "ms-").replace D, L nodeName: (e, t) -> e.nodeName and e.nodeName.toLowerCase() is t.toLowerCase() each: (e, t, n) -> r = undefined i = 0 o = e.length a = M(e) if n if a while o > i break if r = t.apply(e[i], n) r is not 1 i++ else for i of e break if r = t.apply(e[i], n) r is not 1 else if a while o > i break if r = t.call(e[i], i, e[i]) r is not 1 i++ else for i of e break if r = t.call(e[i], i, e[i]) r is not 1 e trim: (if v and not v.call(" ") then (e) -> (if null is e then "" else v.call(e)) else (e) -> (if null is e then "" else (e + "").replace(T, "")) ) makeArray: (e, t) -> n = t or [] null isnt e and ((if M(Object(e)) then b.merge(n, (if "string" is typeof e then [e] else e)) else d.call(n, e))) n inArray: (e, t, n) -> r = undefined if t return g.call(t, e, n) if g r = t.length n = (if n then (if 0 > n then Math.max(0, r + n) else n) else 0) while r > n return n if n of t and t[n] is e n++ -1 merge: (e, n) -> r = n.length i = e.length o = 0 if "number" is typeof r while r > o e[i++] = n[o] o++ else e[i++] = n[o++] while n[o] isnt t e.length = i e grep: (e, t, n) -> r = undefined i = [] o = 0 a = e.length n = !!n while a > o r = !!t(e[o], o) n isnt r and i.push(e[o]) o++ i map: (e, t, n) -> r = undefined i = 0 o = e.length a = M(e) s = [] if a while o > i r = t(e[i], i, n) null isnt r and (s[s.length] = r) i++ else for i of e r = t(e[i], i, n) null isnt r and (s[s.length] = r) f.apply [], s guid: 1 proxy: (e, n) -> r = undefined i = undefined o = undefined "string" is typeof n and (o = e[n] n = e e = o ) (if b.isFunction(e) then (r = h.call(arguments_, 2) i = -> e.apply n or this, r.concat(h.call(arguments_)) i.guid = e.guid = e.guid or b.guid++ i ) else t) access: (e, n, r, i, o, a, s) -> u = 0 l = e.length c = null is r if "object" is b.type(r) o = not 0 for u of r b.access e, n, u, r[u], not 0, a, s else if i isnt t and (o = not 0 b.isFunction(i) or (s = not 0) c and ((if s then (n.call(e, i) n = null ) else (c = n n = (e, t, n) -> c.call b(e), n ))) n ) while l > u n e[u], r, (if s then i else i.call(e[u], u, n(e[u], r))) u++ (if o then e else (if c then n.call(e) else (if l then n(e[0], r) else a))) now: -> (new Date).getTime() ) b.ready.promise = (t) -> unless n if n = b.Deferred() "complete" is o.readyState setTimeout b.ready else unless o.addEventListener o.attachEvent("onreadystatechange", H) e.attachEvent("onload", H) r = not 1 try r = null is e.frameElement and o.documentElement r and r.doScroll and a = -> unless b.isReady try r.doScroll "left" catch e return setTimeout(a, 50) q() b.ready() () n.promise t b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), (e, t) -> l["[object " + t + "]"] = t.toLowerCase() ) r = b(o) _ = {} b.Callbacks = (e) -> e = (if "string" is typeof e then _[e] or F(e) else b.extend({}, e)) n = undefined r = undefined i = undefined o = undefined a = undefined s = undefined u = [] l = not e.once and [] c = (t) -> r = e.memory and t i = not 0 a = s or 0 s = 0 o = u.length n = not 0 while u and o > a if u[a].apply(t[0], t[1]) is not 1 and e.stopOnFalse r = not 1 break a++ n = not 1 u and ((if l then l.length and c(l.shift()) else (if r then u = [] else p.disable()))) p = add: -> if u t = u.length (i = (t) -> b.each t, (t, n) -> r = b.type(n) (if "function" is r then e.unique and p.has(n) or u.push(n) else n and n.length and "string" isnt r and i(n)) )(arguments_) (if n then o = u.length else r and (s = t c(r) )) this remove: -> u and b.each(arguments_, (e, t) -> r = undefined while (r = b.inArray(t, u, r)) > -1 u.splice(r, 1) n and (o >= r and o-- a >= r and a-- ) ) this has: (e) -> (if e then b.inArray(e, u) > -1 else not (not u or not u.length)) empty: -> u = [] this disable: -> u = l = r = t this disabled: -> not u lock: -> l = t r or p.disable() this locked: -> not l fireWith: (e, t) -> t = t or [] t = [e, (if t.slice then t.slice() else t)] not u or i and not l or ((if n then l.push(t) else c(t))) this fire: -> p.fireWith(this, arguments_) this fired: -> !!i p b.extend( Deferred: (e) -> t = [["resolve", "done", b.Callbacks("once memory"), "resolved"], ["reject", "fail", b.Callbacks("once memory"), "rejected"], ["notify", "progress", b.Callbacks("memory")]] n = "pending" r = state: -> n always: -> i.done(arguments_).fail(arguments_) this then: -> e = arguments_ b.Deferred((n) -> b.each(t, (t, o) -> a = o[0] s = b.isFunction(e[t]) and e[t] i[o[1]] -> e = s and s.apply(this, arguments_) (if e and b.isFunction(e.promise) then e.promise().done(n.resolve).fail(n.reject).progress(n.notify) else n[a + "With"]((if this is r then n.promise() else this), (if s then [e] else arguments_))) ) e = null ).promise() promise: (e) -> (if null isnt e then b.extend(e, r) else r) i = {} r.pipe = r.then b.each(t, (e, o) -> a = o[2] s = o[3] r[o[1]] = a.add s and a.add(-> n = s , t[1 ^ e][2].disable, t[2][2].lock) i[o[0]] = -> i[o[0] + "With"]((if this is i then r else this), arguments_) this i[o[0] + "With"] = a.fireWith ) r.promise(i) e and e.call(i, i) i when: (e) -> t = 0 n = h.call(arguments_) r = n.length i = (if 1 isnt r or e and b.isFunction(e.promise) then r else 0) o = (if 1 is i then e else b.Deferred()) a = (e, t, n) -> (r) -> t[e] = this n[e] = (if arguments_.length > 1 then h.call(arguments_) else r) (if n is s then o.notifyWith(t, n) else --i or o.resolveWith(t, n)) s = undefined u = undefined l = undefined if r > 1 s = Array(r) u = Array(r) l = Array(r) while r > t (if n[t] and b.isFunction(n[t].promise) then n[t].promise().done(a(t, l, n)).fail(o.reject).progress(a(t, u, s)) else --i) t++ i or o.resolveWith(l, n) o.promise() ) b.support = -> t = undefined n = undefined r = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = undefined f = undefined d = o.createElement("div") return {} if d.setAttribute("className", "t") d.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>" n = d.getElementsByTagName("*") r = d.getElementsByTagName("a")[0] not n or not r or not n.length s = o.createElement("select") l = s.appendChild(o.createElement("option")) a = d.getElementsByTagName("input")[0] r.style.cssText = "top:1px;float:left;opacity:.5" t = getSetAttribute: "t" isnt d.className leadingWhitespace: 3 is d.firstChild.nodeType tbody: not d.getElementsByTagName("tbody").length htmlSerialize: !!d.getElementsByTagName("link").length style: /top/.test(r.getAttribute("style")) hrefNormalized: "/a" is r.getAttribute("href") opacity: /^0.5/.test(r.style.opacity) cssFloat: !!r.style.cssFloat checkOn: !!a.value optSelected: l.selected enctype: !!o.createElement("form").enctype html5Clone: "<:nav></:nav>" isnt o.createElement("nav").cloneNode(not 0).outerHTML boxModel: "CSS1Compat" is o.compatMode deleteExpando: not 0 noCloneEvent: not 0 inlineBlockNeedsLayout: not 1 shrinkWrapBlocks: not 1 reliableMarginRight: not 0 boxSizingReliable: not 0 pixelPosition: not 1 a.checked = not 0 t.noCloneChecked = a.cloneNode(not 0).checked s.disabled = not 0 t.optDisabled = not l.disabled try delete d.test catch h t.deleteExpando = not 1 a = o.createElement("input") a.setAttribute("value", "") t.input = "" is a.getAttribute("value") a.value = "t" a.setAttribute("type", "radio") t.radioValue = "t" is a.value a.setAttribute("checked", "t") a.setAttribute("name", "t") u = o.createDocumentFragment() u.appendChild(a) t.appendChecked = a.checked t.checkClone = u.cloneNode(not 0).cloneNode(not 0).lastChild.checked d.attachEvent and (d.attachEvent("onclick", -> t.noCloneEvent = not 1 ) d.cloneNode(not 0).click() ) for f of submit: not 0 change: not 0 focusin: not 0 d.setAttribute(c = "on" + f, "t") t[f + "Bubbles"] = c of e or d.attributes[c].expando is not 1 d.style.backgroundClip = "content-box" d.cloneNode(not 0).style.backgroundClip = "" t.clearCloneStyle = "content-box" is d.style.backgroundClip b(-> n = undefined r = undefined a = undefined s = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;" u = o.getElementsByTagName("body")[0] u and (n = o.createElement("div") n.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px" u.appendChild(n).appendChild(d) d.innerHTML = "<table><tr><td></td><td>t</td></tr></table>" a = d.getElementsByTagName("td") a[0].style.cssText = "padding:0;margin:0;border:0;display:none" p = 0 is a[0].offsetHeight a[0].style.display = "" a[1].style.display = "none" t.reliableHiddenOffsets = p and 0 is a[0].offsetHeight d.innerHTML = "" d.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;" t.boxSizing = 4 is d.offsetWidth t.doesNotIncludeMarginInBodyOffset = 1 isnt u.offsetTop e.getComputedStyle and (t.pixelPosition = "1%" isnt (e.getComputedStyle(d, null) or {}).top t.boxSizingReliable = "4px" is (e.getComputedStyle(d, null) or width: "4px").width r = d.appendChild(o.createElement("div")) r.style.cssText = d.style.cssText = s r.style.marginRight = r.style.width = "0" d.style.width = "1px" t.reliableMarginRight = not parseFloat((e.getComputedStyle(r, null) or {}).marginRight) ) typeof d.style.zoom isnt i and (d.innerHTML = "" d.style.cssText = s + "width:1px;padding:1px;display:inline;zoom:1" t.inlineBlockNeedsLayout = 3 is d.offsetWidth d.style.display = "block" d.innerHTML = "<div></div>" d.firstChild.style.width = "5px" t.shrinkWrapBlocks = 3 isnt d.offsetWidth t.inlineBlockNeedsLayout and (u.style.zoom = 1) ) u.removeChild(n) n = d = a = r = null ) ) n = s = u = l = r = a = null t () O = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/ B = /([A-Z])/g b.extend( cache: {} expando: "jQuery" + (p + Math.random()).replace(/\D/g, "") noData: embed: not 0 object: "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" applet: not 0 hasData: (e) -> e = (if e.nodeType then b.cache[e[b.expando]] else e[b.expando]) !!e and not $(e) data: (e, t, n) -> P e, t, n removeData: (e, t) -> R e, t _data: (e, t, n) -> P e, t, n, not 0 _removeData: (e, t) -> R e, t, not 0 acceptData: (e) -> return not 1 if e.nodeType and 1 isnt e.nodeType and 9 isnt e.nodeType t = e.nodeName and b.noData[e.nodeName.toLowerCase()] not t or t isnt not 0 and e.getAttribute("classid") is t ) b.fn.extend( data: (e, n) -> r = undefined i = undefined o = this[0] a = 0 s = null if e is t if @length and (s = b.data(o) 1 is o.nodeType and not b._data(o, "parsedAttrs") ) r = o.attributes while r.length > a i = r[a].name i.indexOf("data-") or (i = b.camelCase(i.slice(5)) W(o, i, s[i]) ) a++ b._data o, "parsedAttrs", not 0 return s (if "object" is typeof e then @each(-> b.data this, e ) else b.access(this, (n) -> (if n is t then (if o then W(o, e, b.data(o, e)) else null) else (@each(-> b.data this, e, n ) t )) , null, n, arguments_.length > 1, null, not 0)) removeData: (e) -> @each -> b.removeData this, e ) b.extend( queue: (e, n, r) -> i = undefined (if e then (n = (n or "fx") + "queue" i = b._data(e, n) r and ((if not i or b.isArray(r) then i = b._data(e, n, b.makeArray(r)) else i.push(r))) i or [] ) else t) dequeue: (e, t) -> t = t or "fx" n = b.queue(e, t) r = n.length i = n.shift() o = b._queueHooks(e, t) a = -> b.dequeue e, t "inprogress" is i and (i = n.shift() r-- ) o.cur = i i and ("fx" is t and n.unshift("inprogress") delete o.stop i.call(e, a, o) ) not r and o and o.empty.fire() _queueHooks: (e, t) -> n = t + "queueHooks" b._data(e, n) or b._data(e, n, empty: b.Callbacks("once memory").add(-> b._removeData(e, t + "queue") b._removeData(e, n) ) ) ) b.fn.extend( queue: (e, n) -> r = 2 "string" isnt typeof e and (n = e e = "fx" r-- ) (if r > arguments_.length then b.queue(this[0], e) else (if n is t then this else @each(-> t = b.queue(this, e, n) b._queueHooks(this, e) "fx" is e and "inprogress" isnt t[0] and b.dequeue(this, e) ))) dequeue: (e) -> @each -> b.dequeue this, e delay: (e, t) -> e = (if b.fx then b.fx.speeds[e] or e else e) t = t or "fx" @queue(t, (t, n) -> r = setTimeout(t, e) n.stop = -> clearTimeout r ) clearQueue: (e) -> @queue e or "fx", [] promise: (e, n) -> r = undefined i = 1 o = b.Deferred() a = this s = @length u = -> --i or o.resolveWith(a, [a]) "string" isnt typeof e and (n = e e = t ) e = e or "fx" while s-- r = b._data(a[s], e + "queueHooks") r and r.empty and (i++ r.empty.add(u) ) u() o.promise(n) ) I = undefined z = undefined X = /[\t\r\n]/g U = /\r/g V = /^(?:input|select|textarea|button|object)$/i Y = /^(?:a|area)$/i J = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i G = /^(?:checked|selected)$/i Q = b.support.getSetAttribute K = b.support.input b.fn.extend( attr: (e, t) -> b.access this, b.attr, e, t, arguments_.length > 1 removeAttr: (e) -> @each -> b.removeAttr this, e prop: (e, t) -> b.access this, b.prop, e, t, arguments_.length > 1 removeProp: (e) -> e = b.propFix[e] or e @each(-> try this[e] = t delete this[e] ) addClass: (e) -> t = undefined n = undefined r = undefined i = undefined o = undefined a = 0 s = @length u = "string" is typeof e and e if b.isFunction(e) return @each((t) -> b(this).addClass e.call(this, t, @className) ) if u t = (e or "").match(w) or [] while s > a if n = this[a] r = 1 is n.nodeType and ((if n.className then (" " + n.className + " ").replace(X, " ") else " ")) o = 0 0 > r.indexOf(" " + i + " ") and (r += i + " ") while i = t[o++] n.className = b.trim(r) a++ this removeClass: (e) -> t = undefined n = undefined r = undefined i = undefined o = undefined a = 0 s = @length u = 0 is arguments_.length or "string" is typeof e and e if b.isFunction(e) return @each((t) -> b(this).removeClass e.call(this, t, @className) ) if u t = (e or "").match(w) or [] while s > a if n = this[a] r = 1 is n.nodeType and ((if n.className then (" " + n.className + " ").replace(X, " ") else "")) o = 0 r = r.replace(" " + i + " ", " ") while r.indexOf(" " + i + " ") >= 0 while i = t[o++] n.className = (if e then b.trim(r) else "") a++ this toggleClass: (e, t) -> n = typeof e r = "boolean" is typeof t (if b.isFunction(e) then @each((n) -> b(this).toggleClass e.call(this, n, @className, t), t ) else @each(-> if "string" is n o = undefined a = 0 s = b(this) u = t l = e.match(w) or [] while o = l[a++] u = (if r then u else not s.hasClass(o)) s[(if u then "addClass" else "removeClass")](o) else (n is i or "boolean" is n) and (@className and b._data(this, "__className__", @className) @className = (if @className or e is not 1 then "" else b._data(this, "__className__") or "") ) )) hasClass: (e) -> t = " " + e + " " n = 0 r = @length while r > n return not 0 if 1 is this[n].nodeType and (" " + this[n].className + " ").replace(X, " ").indexOf(t) >= 0 n++ not 1 val: (e) -> n = undefined r = undefined i = undefined o = this[0] if arguments_.length return i = b.isFunction(e) @each((n) -> o = undefined a = b(this) 1 is @nodeType and (o = (if i then e.call(this, n, a.val()) else e) (if null is o then o = "" else (if "number" is typeof o then o += "" else b.isArray(o) and (o = b.map(o, (e) -> (if null is e then "" else e + "") )))) r = b.valHooks[@type] or b.valHooks[@nodeName.toLowerCase()] r and "set" of r and r.set(this, o, "value") isnt t or (@value = o) ) ) if o r = b.valHooks[o.type] or b.valHooks[o.nodeName.toLowerCase()] (if r and "get" of r and (n = r.get(o, "value")) isnt t then n else (n = o.value (if "string" is typeof n then n.replace(U, "") else (if null is n then "" else n)) )) ) b.extend( valHooks: option: get: (e) -> t = e.attributes.value (if not t or t.specified then e.value else e.text) select: get: (e) -> t = undefined n = undefined r = e.options i = e.selectedIndex o = "select-one" is e.type or 0 > i a = (if o then null else []) s = (if o then i + 1 else r.length) u = (if 0 > i then s else (if o then i else 0)) while s > u if n = r[u] not (not n.selected and u isnt i or ((if b.support.optDisabled then n.disabled else null isnt n.getAttribute("disabled"))) or n.parentNode.disabled and b.nodeName(n.parentNode, "optgroup")) return t if t = b(n).val() o a.push t u++ a set: (e, t) -> n = b.makeArray(t) b(e).find("option").each(-> @selected = b.inArray(b(this).val(), n) >= 0 ) n.length or (e.selectedIndex = -1) n attr: (e, n, r) -> o = undefined a = undefined s = undefined u = e.nodeType if e and 3 isnt u and 8 isnt u and 2 isnt u (if typeof e.getAttribute is i then b.prop(e, n, r) else (a = 1 isnt u or not b.isXMLDoc(e) a and (n = n.toLowerCase() o = b.attrHooks[n] or ((if J.test(n) then z else I)) ) (if r is t then (if o and a and "get" of o and null isnt (s = o.get(e, n)) then s else (typeof e.getAttribute isnt i and (s = e.getAttribute(n)) (if null is s then t else s) )) else (if null isnt r then (if o and a and "set" of o and (s = o.set(e, r, n)) isnt t then s else (e.setAttribute(n, r + "") r )) else (b.removeAttr(e, n) t ))) )) removeAttr: (e, t) -> n = undefined r = undefined i = 0 o = t and t.match(w) if o and 1 is e.nodeType while n = o[i++] r = b.propFix[n] or n (if J.test(n) then (if not Q and G.test(n) then e[b.camelCase("default-" + n)] = e[r] = not 1 else e[r] = not 1) else b.attr(e, n, "")) e.removeAttribute((if Q then n else r)) attrHooks: type: set: (e, t) -> if not b.support.radioValue and "radio" is t and b.nodeName(e, "input") n = e.value e.setAttribute("type", t) n and (e.value = n) t propFix: tabindex: "tabIndex" readonly: "readOnly" for: "htmlFor" class: "className" maxlength: "maxLength" cellspacing: "cellSpacing" cellpadding: "cellPadding" rowspan: "rowSpan" colspan: "colSpan" usemap: "useMap" frameborder: "frameBorder" contenteditable: "contentEditable" prop: (e, n, r) -> i = undefined o = undefined a = undefined s = e.nodeType if e and 3 isnt s and 8 isnt s and 2 isnt s a = 1 isnt s or not b.isXMLDoc(e) a and (n = b.propFix[n] or n o = b.propHooks[n] ) (if r isnt t then (if o and "set" of o and (i = o.set(e, r, n)) isnt t then i else e[n] = r) else (if o and "get" of o and null isnt (i = o.get(e, n)) then i else e[n])) propHooks: tabIndex: get: (e) -> n = e.getAttributeNode("tabindex") (if n and n.specified then parseInt(n.value, 10) else (if V.test(e.nodeName) or Y.test(e.nodeName) and e.href then 0 else t)) ) z = get: (e, n) -> r = b.prop(e, n) i = "boolean" is typeof r and e.getAttribute(n) o = (if "boolean" is typeof r then (if K and Q then null isnt i else (if G.test(n) then e[b.camelCase("default-" + n)] else !!i)) else e.getAttributeNode(n)) (if o and o.value isnt not 1 then n.toLowerCase() else t) set: (e, t, n) -> (if t is not 1 then b.removeAttr(e, n) else (if K and Q or not G.test(n) then e.setAttribute(not Q and b.propFix[n] or n, n) else e[b.camelCase("default-" + n)] = e[n] = not 0)) n K and Q or (b.attrHooks.value = get: (e, n) -> r = e.getAttributeNode(n) (if b.nodeName(e, "input") then e.defaultValue else (if r and r.specified then r.value else t)) set: (e, n, r) -> (if b.nodeName(e, "input") then (e.defaultValue = n t ) else I and I.set(e, n, r)) ) Q or (I = b.valHooks.button = get: (e, n) -> r = e.getAttributeNode(n) (if r and ((if "id" is n or "name" is n or "coords" is n then "" isnt r.value else r.specified)) then r.value else t) set: (e, n, r) -> i = e.getAttributeNode(r) i or e.setAttributeNode(i = e.ownerDocument.createAttribute(r)) i.value = n += "" (if "value" is r or n is e.getAttribute(r) then n else t) b.attrHooks.contenteditable = get: I.get set: (e, t, n) -> I.set e, (if "" is t then not 1 else t), n b.each(["width", "height"], (e, n) -> b.attrHooks[n] = b.extend(b.attrHooks[n], set: (e, r) -> (if "" is r then (e.setAttribute(n, "auto") r ) else t) ) ) ) b.support.hrefNormalized or (b.each(["href", "src", "width", "height"], (e, n) -> b.attrHooks[n] = b.extend(b.attrHooks[n], get: (e) -> r = e.getAttribute(n, 2) (if null is r then t else r) ) ) b.each(["href", "src"], (e, t) -> b.propHooks[t] = get: (e) -> e.getAttribute t, 4 ) ) b.support.style or (b.attrHooks.style = get: (e) -> e.style.cssText or t set: (e, t) -> e.style.cssText = t + "" ) b.support.optSelected or (b.propHooks.selected = b.extend(b.propHooks.selected, get: (e) -> t = e.parentNode t and (t.selectedIndex t.parentNode and t.parentNode.selectedIndex ) null )) b.support.enctype or (b.propFix.enctype = "encoding") b.support.checkOn or b.each(["radio", "checkbox"], -> b.valHooks[this] = get: (e) -> (if null is e.getAttribute("value") then "on" else e.value) ) b.each(["radio", "checkbox"], -> b.valHooks[this] = b.extend(b.valHooks[this], set: (e, n) -> (if b.isArray(n) then e.checked = b.inArray(b(e).val(), n) >= 0 else t) ) ) Z = /^(?:input|select|textarea)$/i et = /^key/ tt = /^(?:mouse|contextmenu)|click/ nt = /^(?:focusinfocus|focusoutblur)$/ rt = /^([^.]*)(?:\.(.+)|)$/ b.event = global: {} add: (e, n, r, o, a) -> s = undefined u = undefined l = undefined c = undefined p = undefined f = undefined d = undefined h = undefined g = undefined m = undefined y = undefined v = b._data(e) if v r.handler and (c = r r = c.handler a = c.selector ) r.guid or (r.guid = b.guid++) (u = v.events) or (u = v.events = {}) (f = v.handle) or (f = v.handle = (e) -> (if typeof b is i or e and b.event.triggered is e.type then t else b.event.dispatch.apply(f.elem, arguments_)) f.elem = e ) n = (n or "").match(w) or [""] l = n.length while l-- s = rt.exec(n[l]) or [] g = y = s[1] m = (s[2] or "").split(".").sort() p = b.event.special[g] or {} g = ((if a then p.delegateType else p.bindType)) or g p = b.event.special[g] or {} d = b.extend( type: g origType: y data: o handler: r guid: r.guid selector: a needsContext: a and b.expr.match.needsContext.test(a) namespace: m.join(".") , c) (h = u[g]) or (h = u[g] = [] h.delegateCount = 0 p.setup and p.setup.call(e, o, m, f) isnt not 1 or ((if e.addEventListener then e.addEventListener(g, f, not 1) else e.attachEvent and e.attachEvent("on" + g, f))) ) p.add and (p.add.call(e, d) d.handler.guid or (d.handler.guid = r.guid) ) (if a then h.splice(h.delegateCount++, 0, d) else h.push(d)) b.event.global[g] = not 0 e = null remove: (e, t, n, r, i) -> o = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = undefined f = undefined d = undefined h = undefined g = undefined m = b.hasData(e) and b._data(e) if m and (c = m.events) t = (t or "").match(w) or [""] l = t.length while l-- if s = rt.exec(t[l]) or [] d = g = s[1] h = (s[2] or "").split(".").sort() d p = b.event.special[d] or {} d = ((if r then p.delegateType else p.bindType)) or d f = c[d] or [] s = s[2] and RegExp("(^|\\.)" + h.join("\\.(?:.*\\.|)") + "(\\.|$)") u = o = f.length while o-- a = f[o] not i and g isnt a.origType or n and n.guid isnt a.guid or s and not s.test(a.namespace) or r and r isnt a.selector and ("**" isnt r or not a.selector) or (f.splice(o, 1) a.selector and f.delegateCount-- p.remove and p.remove.call(e, a) ) u and not f.length and (p.teardown and p.teardown.call(e, h, m.handle) isnt not 1 or b.removeEvent(e, d, m.handle) delete c[d] ) else for d of c b.event.remove e, d + t[l], n, r, not 0 b.isEmptyObject(c) and (delete m.handle b._removeData(e, "events") ) trigger: (n, r, i, a) -> s = undefined u = undefined l = undefined c = undefined p = undefined f = undefined d = undefined h = [i or o] g = (if y.call(n, "type") then n.type else n) m = (if y.call(n, "namespace") then n.namespace.split(".") else []) if l = f = i = i or o 3 isnt i.nodeType and 8 isnt i.nodeType and not nt.test(g + b.event.triggered) and (g.indexOf(".") >= 0 and (m = g.split(".") g = m.shift() m.sort() ) u = 0 > g.indexOf(":") and "on" + g n = (if n[b.expando] then n else new b.Event(g, "object" is typeof n and n)) n.isTrigger = not 0 n.namespace = m.join(".") n.namespace_re = (if n.namespace then RegExp("(^|\\.)" + m.join("\\.(?:.*\\.|)") + "(\\.|$)") else null) n.result = t n.target or (n.target = i) r = (if null is r then [n] else b.makeArray(r, [n])) p = b.event.special[g] or {} a or not p.trigger or p.trigger.apply(i, r) isnt not 1 ) if not a and not p.noBubble and not b.isWindow(i) c = p.delegateType or g nt.test(c + g) or (l = l.parentNode) while l h.push(l) f = l l = l.parentNode f is (i.ownerDocument or o) and h.push(f.defaultView or f.parentWindow or e) d = 0 while (l = h[d++]) and not n.isPropagationStopped() n.type = (if d > 1 then c else p.bindType or g) s = (b._data(l, "events") or {})[n.type] and b._data(l, "handle") s and s.apply(l, r) s = u and l[u] s and b.acceptData(l) and s.apply and s.apply(l, r) is not 1 and n.preventDefault() if n.type = g not (a or n.isDefaultPrevented() or p._default and p._default.apply(i.ownerDocument, r) isnt not 1 or "click" is g and b.nodeName(i, "a") or not b.acceptData(i) or not u or not i[g] or b.isWindow(i)) f = i[u] f and (i[u] = null) b.event.triggered = g try i[g]() b.event.triggered = t f and (i[u] = f) n.result dispatch: (e) -> e = b.event.fix(e) n = undefined r = undefined i = undefined o = undefined a = undefined s = [] u = h.call(arguments_) l = (b._data(this, "events") or {})[e.type] or [] c = b.event.special[e.type] or {} if u[0] = e e.delegateTarget = this not c.preDispatch or c.preDispatch.call(this, e) isnt not 1 s = b.event.handlers.call(this, e, l) n = 0 while (o = s[n++]) and not e.isPropagationStopped() e.currentTarget = o.elem a = 0 while (i = o.handlers[a++]) and not e.isImmediatePropagationStopped() (not e.namespace_re or e.namespace_re.test(i.namespace)) and (e.handleObj = i e.data = i.data r = ((b.event.special[i.origType] or {}).handle or i.handler).apply(o.elem, u) r isnt t and (e.result = r) is not 1 and (e.preventDefault() e.stopPropagation() ) ) c.postDispatch and c.postDispatch.call(this, e) e.result handlers: (e, n) -> r = undefined i = undefined o = undefined a = undefined s = [] u = n.delegateCount l = e.target if u and l.nodeType and (not e.button or "click" isnt e.type) while l isnt this if 1 is l.nodeType and (l.disabled isnt not 0 or "click" isnt e.type) o = [] a = 0 while u > a i = n[a] r = i.selector + " " o[r] is t and (o[r] = (if i.needsContext then b(r, this).index(l) >= 0 else b.find(r, this, null, [l]).length)) o[r] and o.push(i) a++ o.length and s.push( elem: l handlers: o ) l = l.parentNode or this n.length > u and s.push( elem: this handlers: n.slice(u) ) s fix: (e) -> return e if e[b.expando] t = undefined n = undefined r = undefined i = e.type a = e s = @fixHooks[i] s or (@fixHooks[i] = s = (if tt.test(i) then @mouseHooks else (if et.test(i) then @keyHooks else {}))) r = (if s.props then @props.concat(s.props) else @props) e = new b.Event(a) t = r.length while t-- n = r[t] e[n] = a[n] e.target or (e.target = a.srcElement or o) 3 is e.target.nodeType and (e.target = e.target.parentNode) e.metaKey = !!e.metaKey (if s.filter then s.filter(e, a) else e) props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" ") fixHooks: {} keyHooks: props: "char charCode key keyCode".split(" ") filter: (e, t) -> null is e.which and (e.which = (if null isnt t.charCode then t.charCode else t.keyCode)) e mouseHooks: props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" ") filter: (e, n) -> r = undefined i = undefined a = undefined s = n.button u = n.fromElement null is e.pageX and null isnt n.clientX and (i = e.target.ownerDocument or o a = i.documentElement r = i.body e.pageX = n.clientX + (a and a.scrollLeft or r and r.scrollLeft or 0) - (a and a.clientLeft or r and r.clientLeft or 0) e.pageY = n.clientY + (a and a.scrollTop or r and r.scrollTop or 0) - (a and a.clientTop or r and r.clientTop or 0) ) not e.relatedTarget and u and (e.relatedTarget = (if u is e.target then n.toElement else u)) e.which or s is t or (e.which = (if 1 & s then 1 else (if 2 & s then 3 else (if 4 & s then 2 else 0)))) e special: load: noBubble: not 0 click: trigger: -> (if b.nodeName(this, "input") and "checkbox" is @type and @click then (@click() not 1 ) else t) focus: trigger: -> if this isnt o.activeElement and @focus try return @focus() not 1 delegateType: "focusin" blur: trigger: -> (if this is o.activeElement and @blur then (@blur() not 1 ) else t) delegateType: "focusout" beforeunload: postDispatch: (e) -> e.result isnt t and (e.originalEvent.returnValue = e.result) simulate: (e, t, n, r) -> i = b.extend(new b.Event, n, type: e isSimulated: not 0 originalEvent: {} ) (if r then b.event.trigger(i, null, t) else b.event.dispatch.call(t, i)) i.isDefaultPrevented() and n.preventDefault() b.removeEvent = (if o.removeEventListener then (e, t, n) -> e.removeEventListener and e.removeEventListener(t, n, not 1) else (e, t, n) -> r = "on" + t e.detachEvent and (typeof e[r] is i and (e[r] = null) e.detachEvent(r, n) ) ) b.Event = (e, n) -> (if this instanceof b.Event then ((if e and e.type then (@originalEvent = e @type = e.type @isDefaultPrevented = (if e.defaultPrevented or e.returnValue is not 1 or e.getPreventDefault and e.getPreventDefault() then it else ot) ) else @type = e) n and b.extend(this, n) @timeStamp = e and e.timeStamp or b.now() this[b.expando] = not 0 t ) else new b.Event(e, n)) b.Event:: = isDefaultPrevented: ot isPropagationStopped: ot isImmediatePropagationStopped: ot preventDefault: -> e = @originalEvent @isDefaultPrevented = it e and ((if e.preventDefault then e.preventDefault() else e.returnValue = not 1)) stopPropagation: -> e = @originalEvent @isPropagationStopped = it e and (e.stopPropagation and e.stopPropagation() e.cancelBubble = not 0 ) stopImmediatePropagation: -> @isImmediatePropagationStopped = it @stopPropagation() b.each( mouseenter: "mouseover" mouseleave: "mouseout" , (e, t) -> b.event.special[e] = delegateType: t bindType: t handle: (e) -> n = undefined r = this i = e.relatedTarget o = e.handleObj (not i or i isnt r and not b.contains(r, i)) and (e.type = o.origType n = o.handler.apply(this, arguments_) e.type = t ) n ) b.support.submitBubbles or (b.event.special.submit = setup: -> (if b.nodeName(this, "form") then not 1 else (b.event.add(this, "click._submit keypress._submit", (e) -> n = e.target r = (if b.nodeName(n, "input") or b.nodeName(n, "button") then n.form else t) r and not b._data(r, "submitBubbles") and (b.event.add(r, "submit._submit", (e) -> e._submit_bubble = not 0 ) b._data(r, "submitBubbles", not 0) ) ) t )) postDispatch: (e) -> e._submit_bubble and (delete e._submit_bubble @parentNode and not e.isTrigger and b.event.simulate("submit", @parentNode, e, not 0) ) teardown: -> (if b.nodeName(this, "form") then not 1 else (b.event.remove(this, "._submit") t )) ) b.support.changeBubbles or (b.event.special.change = setup: -> (if Z.test(@nodeName) then (("checkbox" is @type or "radio" is @type) and (b.event.add(this, "propertychange._change", (e) -> "checked" is e.originalEvent.propertyName and (@_just_changed = not 0) ) b.event.add(this, "click._change", (e) -> @_just_changed and not e.isTrigger and (@_just_changed = not 1) b.event.simulate("change", this, e, not 0) ) ) not 1 ) else (b.event.add(this, "beforeactivate._change", (e) -> t = e.target Z.test(t.nodeName) and not b._data(t, "changeBubbles") and (b.event.add(t, "change._change", (e) -> not @parentNode or e.isSimulated or e.isTrigger or b.event.simulate("change", @parentNode, e, not 0) ) b._data(t, "changeBubbles", not 0) ) ) t )) handle: (e) -> n = e.target (if this isnt n or e.isSimulated or e.isTrigger or "radio" isnt n.type and "checkbox" isnt n.type then e.handleObj.handler.apply(this, arguments_) else t) teardown: -> b.event.remove(this, "._change") not Z.test(@nodeName) ) b.support.focusinBubbles or b.each( focus: "focusin" blur: "focusout" , (e, t) -> n = 0 r = (e) -> b.event.simulate t, e.target, b.event.fix(e), not 0 b.event.special[t] = setup: -> 0 is n++ and o.addEventListener(e, r, not 0) teardown: -> 0 is --n and o.removeEventListener(e, r, not 0) ) b.fn.extend( on: (e, n, r, i, o) -> a = undefined s = undefined if "object" is typeof e "string" isnt typeof n and (r = r or n n = t ) for a of e @on a, n, r, e[a], o return this if (if null is r and null is i then (i = n r = n = t ) else null is i and ((if "string" is typeof n then (i = r r = t ) else (i = r r = n n = t )))) i is not 1 i = ot else return this unless i 1 is o and (s = i i = (e) -> b().off(e) s.apply(this, arguments_) i.guid = s.guid or (s.guid = b.guid++) ) @each(-> b.event.add this, e, i, r, n ) one: (e, t, n, r) -> @on e, t, n, r, 1 off: (e, n, r) -> i = undefined o = undefined if e and e.preventDefault and e.handleObj return i = e.handleObj b(e.delegateTarget).off((if i.namespace then i.origType + "." + i.namespace else i.origType), i.selector, i.handler) this if "object" is typeof e for o of e @off o, n, e[o] return this (n is not 1 or "function" is typeof n) and (r = n n = t ) r is not 1 and (r = ot) @each(-> b.event.remove this, e, r, n ) bind: (e, t, n) -> @on e, null, t, n unbind: (e, t) -> @off e, null, t delegate: (e, t, n, r) -> @on t, e, n, r undelegate: (e, t, n) -> (if 1 is arguments_.length then @off(e, "**") else @off(t, e or "**", n)) trigger: (e, t) -> @each -> b.event.trigger e, t, this triggerHandler: (e, n) -> r = this[0] (if r then b.event.trigger(e, n, r, not 0) else t) ) (e, t) -> rt = (e) -> Y.test e + "" it = -> e = undefined t = [] e = (n, r) -> t.push(n += " ") > i.cacheLength and delete e[t.shift()] e[n] = r ot = (e) -> e[x] = not 0 e at = (e) -> t = p.createElement("div") try return e(t) catch n return not 1 finally t = null st = (e, t, n, r) -> i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined f = undefined g = undefined m = undefined v = undefined return n if ((if t then t.ownerDocument or t else w)) isnt p and c(t) t = t or p n = n or [] not e or "string" isnt typeof e return [] if 1 isnt (s = t.nodeType) and 9 isnt s if not d and not r if i = J.exec(e) if a = i[1] if 9 is s return n if o = t.getElementById(a) not o or not o.parentNode if o.id is a return n.push(o) n else if t.ownerDocument and (o = t.ownerDocument.getElementById(a)) and y(t, o) and o.id is a return n.push(o) n else if i[2] return H.apply(n, q.call(t.getElementsByTagName(e), 0)) n if (a = i[3]) and T.getByClassName and t.getElementsByClassName return H.apply(n, q.call(t.getElementsByClassName(a), 0)) n if T.qsa and not h.test(e) if f = not 0 g = x m = t v = 9 is s and e 1 is s and "object" isnt t.nodeName.toLowerCase() l = ft(e) (if (f = t.getAttribute("id")) then g = f.replace(K, "\\$&") else t.setAttribute("id", g)) g = "[id='" + g + "'] " u = l.length l[u] = g + dt(l[u]) while u-- m = V.test(e) and t.parentNode or t v = l.join(",") if v try return H.apply(n, q.call(m.querySelectorAll(v), 0)) n finally f or t.removeAttribute("id") wt e.replace(W, "$1"), t, n, r ut = (e, t) -> n = t and e r = n and (~t.sourceIndex or j) - (~e.sourceIndex or j) return r if r return -1 if n is t while n = n.nextSibling if n (if e then 1 else -1) lt = (e) -> (t) -> n = t.nodeName.toLowerCase() "input" is n and t.type is e ct = (e) -> (t) -> n = t.nodeName.toLowerCase() ("input" is n or "button" is n) and t.type is e pt = (e) -> ot (t) -> t = +t ot((n, r) -> i = undefined o = e([], n.length, t) a = o.length n[i = o[a]] and (n[i] = not (r[i] = n[i])) while a-- ) ft = (e, t) -> n = undefined r = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = E[e + " "] return (if t then 0 else c.slice(0)) if c s = e u = [] l = i.preFilter while s (not n or (r = $.exec(s))) and (r and (s = s.slice(r[0].length) or s) u.push(o = []) ) n = not 1 (r = I.exec(s)) and (n = r.shift() o.push( value: n type: r[0].replace(W, " ") ) s = s.slice(n.length) ) for a of i.filter not (r = U[a].exec(s)) or l[a] and not (r = l[a](r)) or (n = r.shift() o.push( value: n type: a matches: r ) s = s.slice(n.length) ) break unless n (if t then s.length else (if s then st.error(e) else E(e, u).slice(0))) dt = (e) -> t = 0 n = e.length r = "" while n > t r += e[t].value t++ r ht = (e, t, n) -> i = t.dir o = n and "parentNode" is i a = C++ (if t.first then (t, n, r) -> return e(t, n, r) if 1 is t.nodeType or o while t = t[i] else (t, n, s) -> u = undefined l = undefined c = undefined p = N + " " + a if s return not 0 if (1 is t.nodeType or o) and e(t, n, s) while t = t[i] else while t = t[i] if 1 is t.nodeType or o if c = t[x] or (t[x] = {}) (l = c[i]) and l[0] is p return u is not 0 if (u = l[1]) is not 0 or u is r else return not 0 if l = c[i] = [p] l[1] = e(t, n, s) or r l[1] is not 0 ) gt = (e) -> (if e.length > 1 then (t, n, r) -> i = e.length return not 1 unless e[i](t, n, r) while i-- not 0 else e[0]) mt = (e, t, n, r, i) -> o = undefined a = [] s = 0 u = e.length l = null isnt t while u > s (o = e[s]) and (not n or n(o, r, i)) and (a.push(o) l and t.push(s) ) s++ a yt = (e, t, n, r, i, o) -> r and not r[x] and (r = yt(r)) i and not i[x] and (i = yt(i, o)) ot((o, a, s, u) -> l = undefined c = undefined p = undefined f = [] d = [] h = a.length g = o or xt(t or "*", (if s.nodeType then [s] else s), []) m = (if not e or not o and t then g else mt(g, f, e, s, u)) y = (if n then (if i or ((if o then e else h or r)) then [] else a) else m) if n and n(m, y, s, u) r l = mt(y, d) r(l, [], s, u) c = l.length (p = l[c]) and (y[d[c]] = not (m[d[c]] = p)) while c-- if o if i or e if i l = [] c = y.length (p = y[c]) and l.push(m[c] = p) while c-- i null, y = [], l, u c = y.length (p = y[c]) and (l = (if i then M.call(o, p) else f[c])) > -1 and (o[l] = not (a[l] = p)) while c-- else y = mt((if y is a then y.splice(h, y.length) else y)) (if i then i(null, a, y, u) else H.apply(a, y)) ) vt = (e) -> t = undefined n = undefined r = undefined o = e.length a = i.relative[e[0].type] s = a or i.relative[" "] u = (if a then 1 else 0) c = ht((e) -> e is t , s, not 0) p = ht((e) -> M.call(t, e) > -1 , s, not 0) f = [(e, n, r) -> not a and (r or n isnt l) or ((if (t = n).nodeType then c(e, n, r) else p(e, n, r))) ] while o > u unless n = i.relative[e[u].type] if n = i.filter[e[u].type].apply(null, e[u].matches) n[x] r = ++u while o > r break if i.relative[e[r].type] r++ return yt(u > 1 and gt(f), u > 1 and dt(e.slice(0, u - 1)).replace(W, "$1"), n, r > u and vt(e.slice(u, r)), o > r and vt(e = e.slice(r)), o > r and dt(e)) f.push n u++ gt f bt = (e, t) -> n = 0 o = t.length > 0 a = e.length > 0 s = (s, u, c, f, d) -> h = undefined g = undefined m = undefined y = [] v = 0 b = "0" x = s and [] w = null isnt d T = l C = s or a and i.find.TAG("*", d and u.parentNode or u) k = N += (if null is T then 1 else Math.random() or .1) w and (l = u isnt p and u r = n ) while null isnt (h = C[b]) if a and h g = 0 while m = e[g++] if m(h, u, c) f.push h break w and (N = k r = ++n ) o and ((h = not m and h) and v-- s and x.push(h) ) b++ if v += b o and b isnt v g = 0 m x, y, u, c while m = t[g++] if s x[b] or y[b] or (y[b] = L.call(f)) while b-- if v > 0 y = mt(y) H.apply(f, y) w and not s and y.length > 0 and v + t.length > 1 and st.uniqueSort(f) w and (N = k l = T ) x (if o then ot(s) else s) xt = (e, t, n) -> r = 0 i = t.length while i > r st e, t[r], n r++ n wt = (e, t, n, r) -> o = undefined a = undefined u = undefined l = undefined c = undefined p = ft(e) if not r and 1 is p.length if a = p[0] = p[0].slice(0) a.length > 2 and "ID" is (u = a[0]).type and 9 is t.nodeType and not d and i.relative[a[1].type] return n if t = i.find.ID(u.matches[0].replace(et, tt), t)[0] not t e = e.slice(a.shift().value.length) o = (if U.needsContext.test(e) then 0 else a.length) while o-- break if u = a[o] i.relative[l = u.type] if (c = i.find[l]) and (r = c(u.matches[0].replace(et, tt), V.test(a[0].type) and t.parentNode or t)) if a.splice(o, 1) e = r.length and dt(a) not e return H.apply(n, q.call(r, 0)) n break s(e, p)(r, t, d, n, V.test(e)) n Tt = -> n = undefined r = undefined i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = undefined f = undefined d = undefined h = undefined g = undefined m = undefined y = undefined v = undefined x = "sizzle" + -new Date w = e.document T = {} N = 0 C = 0 k = it() E = it() S = it() A = typeof t j = 1 << 31 D = [] L = D.pop H = D.push q = D.slice M = D.indexOf or (e) -> t = 0 n = @length while n > t return t if this[t] is e t++ -1 _ = "[\\x20\\t\\r\\n\\f]" F = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+" O = F.replace("w", "w#") B = "([*^$|!~]?=)" P = "\\[" + _ + "*(" + F + ")" + _ + "*(?:" + B + _ + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + O + ")|)|)" + _ + "*\\]" R = ":(" + F + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + P.replace(3, 8) + ")*)|.*)\\)|)" W = RegExp("^" + _ + "+|((?:^|[^\\\\])(?:\\\\.)*)" + _ + "+$", "g") $ = RegExp("^" + _ + "*," + _ + "*") I = RegExp("^" + _ + "*([\\x20\\t\\r\\n\\f>+~])" + _ + "*") z = RegExp(R) X = RegExp("^" + O + "$") U = ID: RegExp("^#(" + F + ")") CLASS: RegExp("^\\.(" + F + ")") NAME: RegExp("^\\[name=['\"]?(" + F + ")['\"]?\\]") TAG: RegExp("^(" + F.replace("w", "w*") + ")") ATTR: RegExp("^" + P) PSEUDO: RegExp("^" + R) CHILD: RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + _ + "*(even|odd|(([+-]|)(\\d*)n|)" + _ + "*(?:([+-]|)" + _ + "*(\\d+)|))" + _ + "*\\)|)", "i") needsContext: RegExp("^" + _ + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + _ + "*((?:-\\d)?\\d*)" + _ + "*\\)|)(?=[^-]|$)", "i") V = /[\x20\t\r\n\f]*[+~]/ Y = /^[^{]+\{\s*\[native code/ J = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/ G = /^(?:input|select|textarea|button)$/i Q = /^h\d$/i K = /'|\\/g Z = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g et = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g tt = (e, t) -> n = "0x" + t - 65536 (if n isnt n then t else (if 0 > n then String.fromCharCode(n + 65536) else String.fromCharCode(55296 | n >> 10, 56320 | 1023 & n))) try q.call(w.documentElement.childNodes, 0)[0].nodeType catch nt q = (e) -> t = undefined n = [] n.push t while t = this[e++] n a = st.isXML = (e) -> t = e and (e.ownerDocument or e).documentElement (if t then "HTML" isnt t.nodeName else not 1) c = st.setDocument = (e) -> n = (if e then e.ownerDocument or e else w) (if n isnt p and 9 is n.nodeType and n.documentElement then (p = n f = n.documentElement d = a(n) T.tagNameNoComments = at((e) -> e.appendChild(n.createComment("")) not e.getElementsByTagName("*").length ) T.attributes = at((e) -> e.innerHTML = "<select></select>" t = typeof e.lastChild.getAttribute("multiple") "boolean" isnt t and "string" isnt t ) T.getByClassName = at((e) -> e.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>" (if e.getElementsByClassName and e.getElementsByClassName("e").length then (e.lastChild.className = "e" 2 is e.getElementsByClassName("e").length ) else not 1) ) T.getByName = at((e) -> e.id = x + 0 e.innerHTML = "<a name='" + x + "'></a><div name='" + x + "'></div>" f.insertBefore(e, f.firstChild) t = n.getElementsByName and n.getElementsByName(x).length is 2 + n.getElementsByName(x + 0).length T.getIdNotName = not n.getElementById(x) f.removeChild(e) t ) i.attrHandle = (if at((e) -> e.innerHTML = "<a href='#'></a>" e.firstChild and typeof e.firstChild.getAttribute isnt A and "#" is e.firstChild.getAttribute("href") ) then {} else href: (e) -> e.getAttribute "href", 2 type: (e) -> e.getAttribute "type" ) (if T.getIdNotName then (i.find.ID = (e, t) -> if typeof t.getElementById isnt A and not d n = t.getElementById(e) (if n and n.parentNode then [n] else []) i.filter.ID = (e) -> t = e.replace(et, tt) (e) -> e.getAttribute("id") is t ) else (i.find.ID = (e, n) -> if typeof n.getElementById isnt A and not d r = n.getElementById(e) (if r then (if r.id is e or typeof r.getAttributeNode isnt A and r.getAttributeNode("id").value is e then [r] else t) else []) i.filter.ID = (e) -> t = e.replace(et, tt) (e) -> n = typeof e.getAttributeNode isnt A and e.getAttributeNode("id") n and n.value is t )) i.find.TAG = (if T.tagNameNoComments then (e, n) -> (if typeof n.getElementsByTagName isnt A then n.getElementsByTagName(e) else t) else (e, t) -> n = undefined r = [] i = 0 o = t.getElementsByTagName(e) if "*" is e 1 is n.nodeType and r.push(n) while n = o[i++] return r o ) i.find.NAME = T.getByName and (e, n) -> (if typeof n.getElementsByName isnt A then n.getElementsByName(name) else t) i.find.CLASS = T.getByClassName and (e, n) -> (if typeof n.getElementsByClassName is A or d then t else n.getElementsByClassName(e)) g = [] h = [":focus"] (T.qsa = rt(n.querySelectorAll)) and (at((e) -> e.innerHTML = "<select><option selected=''></option></select>" e.querySelectorAll("[selected]").length or h.push("\\[" + _ + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)") e.querySelectorAll(":checked").length or h.push(":checked") ) at((e) -> e.innerHTML = "<input type='hidden' i=''/>" e.querySelectorAll("[i^='']").length and h.push("[*^$]=" + _ + "*(?:\"\"|'')") e.querySelectorAll(":enabled").length or h.push(":enabled", ":disabled") e.querySelectorAll("*,:x") h.push(",.*:") ) ) (T.matchesSelector = rt(m = f.matchesSelector or f.mozMatchesSelector or f.webkitMatchesSelector or f.oMatchesSelector or f.msMatchesSelector)) and at((e) -> T.disconnectedMatch = m.call(e, "div") m.call(e, "[s!='']:x") g.push("!=", R) ) h = RegExp(h.join("|")) g = RegExp(g.join("|")) y = (if rt(f.contains) or f.compareDocumentPosition then (e, t) -> n = (if 9 is e.nodeType then e.documentElement else e) r = t and t.parentNode e is r or not (not r or 1 isnt r.nodeType or not ((if n.contains then n.contains(r) else e.compareDocumentPosition and 16 & e.compareDocumentPosition(r)))) else (e, t) -> return not 0 if t is e while t = t.parentNode if t not 1 ) v = (if f.compareDocumentPosition then (e, t) -> r = undefined (if e is t then (u = not 0 0 ) else (if (r = t.compareDocumentPosition and e.compareDocumentPosition and e.compareDocumentPosition(t)) then (if 1 & r or e.parentNode and 11 is e.parentNode.nodeType then (if e is n or y(w, e) then -1 else (if t is n or y(w, t) then 1 else 0)) else (if 4 & r then -1 else 1)) else (if e.compareDocumentPosition then -1 else 1))) else (e, t) -> r = undefined i = 0 o = e.parentNode a = t.parentNode s = [e] l = [t] if e is t return u = not 0 0 return (if e is n then -1 else (if t is n then 1 else (if o then -1 else (if a then 1 else 0)))) if not o or not a return ut(e, t) if o is a r = e s.unshift r while r = r.parentNode r = t l.unshift r while r = r.parentNode i++ while s[i] is l[i] (if i then ut(s[i], l[i]) else (if s[i] is w then -1 else (if l[i] is w then 1 else 0))) ) u = not 1 [0, 0].sort(v) T.detectDuplicates = u p ) else p) st.matches = (e, t) -> st e, null, null, t st.matchesSelector = (e, t) -> if (e.ownerDocument or e) isnt p and c(e) t = t.replace(Z, "='$1']") not (not T.matchesSelector or d or g and g.test(t) or h.test(t)) try n = m.call(e, t) return n if n or T.disconnectedMatch or e.document and 11 isnt e.document.nodeType st(t, p, null, [e]).length > 0 st.contains = (e, t) -> (e.ownerDocument or e) isnt p and c(e) y(e, t) st.attr = (e, t) -> n = undefined (e.ownerDocument or e) isnt p and c(e) d or (t = t.toLowerCase()) (if (n = i.attrHandle[t]) then n(e) else (if d or T.attributes then e.getAttribute(t) else (if ((n = e.getAttributeNode(t)) or e.getAttribute(t)) and e[t] is not 0 then t else (if n and n.specified then n.value else null)))) st.error = (e) -> throw Error("Syntax error, unrecognized expression: " + e) st.uniqueSort = (e) -> t = undefined n = [] r = 1 i = 0 if u = not T.detectDuplicates e.sort(v) u while t = e[r] t is e[r - 1] and (i = n.push(r)) r++ e.splice n[i], 1 while i-- e o = st.getText = (e) -> t = undefined n = "" r = 0 i = e.nodeType if i if 1 is i or 9 is i or 11 is i return e.textContent if "string" is typeof e.textContent e = e.firstChild while e n += o(e) e = e.nextSibling else return e.nodeValue if 3 is i or 4 is i else while t = e[r] n += o(t) r++ n i = st.selectors = cacheLength: 50 createPseudo: ot match: U find: {} relative: ">": dir: "parentNode" first: not 0 " ": dir: "parentNode" "+": dir: "previousSibling" first: not 0 "~": dir: "previousSibling" preFilter: ATTR: (e) -> e[1] = e[1].replace(et, tt) e[3] = (e[4] or e[5] or "").replace(et, tt) "~=" is e[2] and (e[3] = " " + e[3] + " ") e.slice(0, 4) CHILD: (e) -> e[1] = e[1].toLowerCase() (if "nth" is e[1].slice(0, 3) then (e[3] or st.error(e[0]) e[4] = +((if e[4] then e[5] + (e[6] or 1) else 2 * ("even" is e[3] or "odd" is e[3]))) e[5] = +(e[7] + e[8] or "odd" is e[3]) ) else e[3] and st.error(e[0])) e PSEUDO: (e) -> t = undefined n = not e[5] and e[2] (if U.CHILD.test(e[0]) then null else ((if e[4] then e[2] = e[4] else n and z.test(n) and (t = ft(n, not 0)) and (t = n.indexOf(")", n.length - t) - n.length) and (e[0] = e[0].slice(0, t) e[2] = n.slice(0, t) )) e.slice(0, 3) )) filter: TAG: (e) -> (if "*" is e then -> not 0 else (e = e.replace(et, tt).toLowerCase() (t) -> t.nodeName and t.nodeName.toLowerCase() is e )) CLASS: (e) -> t = k[e + " "] t or (t = RegExp("(^|" + _ + ")" + e + "(" + _ + "|$)")) and k(e, (e) -> t.test e.className or typeof e.getAttribute isnt A and e.getAttribute("class") or "" ) ATTR: (e, t, n) -> (r) -> i = st.attr(r, e) (if null is i then "!=" is t else (if t then (i += "" (if "=" is t then i is n else (if "!=" is t then i isnt n else (if "^=" is t then n and 0 is i.indexOf(n) else (if "*=" is t then n and i.indexOf(n) > -1 else (if "$=" is t then n and i.slice(-n.length) is n else (if "~=" is t then (" " + i + " ").indexOf(n) > -1 else (if "|=" is t then i is n or i.slice(0, n.length + 1) is n + "-" else not 1))))))) ) else not 0)) CHILD: (e, t, n, r, i) -> o = "nth" isnt e.slice(0, 3) a = "last" isnt e.slice(-4) s = "of-type" is t (if 1 is r and 0 is i then (e) -> !!e.parentNode else (t, n, u) -> l = undefined c = undefined p = undefined f = undefined d = undefined h = undefined g = (if o isnt a then "nextSibling" else "previousSibling") m = t.parentNode y = s and t.nodeName.toLowerCase() v = not u and not s if m if o while g p = t return not 1 if (if s then p.nodeName.toLowerCase() is y else 1 is p.nodeType) while p = p[g] h = g = "only" is e and not h and "nextSibling" return not 0 if h = [(if a then m.firstChild else m.lastChild)] a and v c = m[x] or (m[x] = {}) l = c[e] or [] d = l[0] is N and l[1] f = l[0] is N and l[2] p = d and m.childNodes[d] while p = ++d and p and p[g] or (f = d = 0) or h.pop() if 1 is p.nodeType and ++f and p is t c[e] = [N, d, f] break else if v and (l = (t[x] or (t[x] = {}))[e]) and l[0] is N f = l[1] else while p = ++d and p and p[g] or (f = d = 0) or h.pop() break if ((if s then p.nodeName.toLowerCase() is y else 1 is p.nodeType)) and ++f and (v and ((p[x] or (p[x] = {}))[e] = [N, f]) p is t ) f -= i f is r or 0 is f % r and f / r >= 0 ) PSEUDO: (e, t) -> n = undefined r = i.pseudos[e] or i.setFilters[e.toLowerCase()] or st.error("unsupported pseudo: " + e) (if r[x] then r(t) else (if r.length > 1 then (n = [e, e, "", t] (if i.setFilters.hasOwnProperty(e.toLowerCase()) then ot((e, n) -> i = undefined o = r(e, t) a = o.length while a-- i = M.call(e, o[a]) e[i] = not (n[i] = o[a]) ) else (e) -> r e, 0, n ) ) else r)) pseudos: not: ot((e) -> t = [] n = [] r = s(e.replace(W, "$1")) (if r[x] then ot((e, t, n, i) -> o = undefined a = r(e, null, i, []) s = e.length (o = a[s]) and (e[s] = not (t[s] = o)) while s-- ) else (e, i, o) -> t[0] = e r(t, null, o, n) not n.pop() ) ) has: ot((e) -> (t) -> st(e, t).length > 0 ) contains: ot((e) -> (t) -> (t.textContent or t.innerText or o(t)).indexOf(e) > -1 ) lang: ot((e) -> X.test(e or "") or st.error("unsupported lang: " + e) e = e.replace(et, tt).toLowerCase() (t) -> n = undefined loop if n = (if d then t.getAttribute("xml:lang") or t.getAttribute("lang") else t.lang) return n = n.toLowerCase() n is e or 0 is n.indexOf(e + "-") break unless (t = t.parentNode) and 1 is t.nodeType not 1 ) target: (t) -> n = e.location and e.location.hash n and n.slice(1) is t.id root: (e) -> e is f focus: (e) -> e is p.activeElement and (not p.hasFocus or p.hasFocus()) and !!(e.type or e.href or ~e.tabIndex) enabled: (e) -> e.disabled is not 1 disabled: (e) -> e.disabled is not 0 checked: (e) -> t = e.nodeName.toLowerCase() "input" is t and !!e.checked or "option" is t and !!e.selected selected: (e) -> e.parentNode and e.parentNode.selectedIndex e.selected is not 0 empty: (e) -> e = e.firstChild while e return not 1 if e.nodeName > "@" or 3 is e.nodeType or 4 is e.nodeType e = e.nextSibling not 0 parent: (e) -> not i.pseudos.empty(e) header: (e) -> Q.test e.nodeName input: (e) -> G.test e.nodeName button: (e) -> t = e.nodeName.toLowerCase() "input" is t and "button" is e.type or "button" is t text: (e) -> t = undefined "input" is e.nodeName.toLowerCase() and "text" is e.type and (null is (t = e.getAttribute("type")) or t.toLowerCase() is e.type) first: pt(-> [0] ) last: pt((e, t) -> [t - 1] ) eq: pt((e, t, n) -> [(if 0 > n then n + t else n)] ) even: pt((e, t) -> n = 0 while t > n e.push n n += 2 e ) odd: pt((e, t) -> n = 1 while t > n e.push n n += 2 e ) lt: pt((e, t, n) -> r = (if 0 > n then n + t else n) while --r >= 0 e.push r e ) gt: pt((e, t, n) -> r = (if 0 > n then n + t else n) while t > ++r e.push r e ) for n of radio: not 0 checkbox: not 0 file: not 0 password: PI:PASSWORD:<PASSWORD>END_PI image: not 0 i.pseudos[n] = lt(n) for n of submit: not 0 reset: not 0 i.pseudos[n] = ct(n) s = st.compile = (e, t) -> n = undefined r = [] i = [] o = S[e + " "] unless o t or (t = ft(e)) n = t.length while n-- o = vt(t[n]) (if o[x] then r.push(o) else i.push(o)) o = S(e, bt(i, r)) o i.pseudos.nth = i.pseudos.eq i.filters = Tt:: = i.pseudos i.setFilters = new Tt c() st.attr = b.attr b.find = st b.expr = st.selectors b.expr[":"] = b.expr.pseudos b.unique = st.uniqueSort b.text = st.getText b.isXMLDoc = st.isXML b.contains = st.contains (e) at = /Until$/ st = /^(?:parents|prev(?:Until|All))/ ut = /^.[^:#\[\.,]*$/ lt = b.expr.match.needsContext ct = children: not 0 contents: not 0 next: not 0 prev: not 0 b.fn.extend( find: (e) -> t = undefined n = undefined r = undefined i = @length unless "string" is typeof e return r = this @pushStack(b(e).filter(-> t = 0 while i > t return not 0 if b.contains(r[t], this) t++ )) n = [] t = 0 while i > t b.find e, this[t], n t++ n = @pushStack((if i > 1 then b.unique(n) else n)) n.selector = ((if @selector then @selector + " " else "")) + e n has: (e) -> t = undefined n = b(e, this) r = n.length @filter -> t = 0 while r > t return not 0 if b.contains(this, n[t]) t++ not: (e) -> @pushStack ft(this, e, not 1) filter: (e) -> @pushStack ft(this, e, not 0) is: (e) -> !!e and ((if "string" is typeof e then (if lt.test(e) then b(e, @context).index(this[0]) >= 0 else b.filter(e, this).length > 0) else @filter(e).length > 0)) closest: (e, t) -> n = undefined r = 0 i = @length o = [] a = (if lt.test(e) or "string" isnt typeof e then b(e, t or @context) else 0) while i > r n = this[r] while n and n.ownerDocument and n isnt t and 11 isnt n.nodeType if (if a then a.index(n) > -1 else b.find.matchesSelector(n, e)) o.push n break n = n.parentNode r++ @pushStack (if o.length > 1 then b.unique(o) else o) index: (e) -> (if e then (if "string" is typeof e then b.inArray(this[0], b(e)) else b.inArray((if e.jquery then e[0] else e), this)) else (if this[0] and this[0].parentNode then @first().prevAll().length else -1)) add: (e, t) -> n = (if "string" is typeof e then b(e, t) else b.makeArray((if e and e.nodeType then [e] else e))) r = b.merge(@get(), n) @pushStack b.unique(r) addBack: (e) -> @add (if null is e then @prevObject else @prevObject.filter(e)) ) b.fn.andSelf = b.fn.addBack b.each( parent: (e) -> t = e.parentNode (if t and 11 isnt t.nodeType then t else null) parents: (e) -> b.dir e, "parentNode" parentsUntil: (e, t, n) -> b.dir e, "parentNode", n next: (e) -> pt e, "nextSibling" prev: (e) -> pt e, "previousSibling" nextAll: (e) -> b.dir e, "nextSibling" prevAll: (e) -> b.dir e, "previousSibling" nextUntil: (e, t, n) -> b.dir e, "nextSibling", n prevUntil: (e, t, n) -> b.dir e, "previousSibling", n siblings: (e) -> b.sibling (e.parentNode or {}).firstChild, e children: (e) -> b.sibling e.firstChild contents: (e) -> (if b.nodeName(e, "iframe") then e.contentDocument or e.contentWindow.document else b.merge([], e.childNodes)) , (e, t) -> b.fn[e] = (n, r) -> i = b.map(this, t, n) at.test(e) or (r = n) r and "string" is typeof r and (i = b.filter(r, i)) i = (if @length > 1 and not ct[e] then b.unique(i) else i) @length > 1 and st.test(e) and (i = i.reverse()) @pushStack(i) ) b.extend( filter: (e, t, n) -> n and (e = ":not(" + e + ")") (if 1 is t.length then (if b.find.matchesSelector(t[0], e) then [t[0]] else []) else b.find.matches(e, t)) dir: (e, n, r) -> i = [] o = e[n] while o and 9 isnt o.nodeType and (r is t or 1 isnt o.nodeType or not b(o).is(r)) 1 is o.nodeType and i.push(o) o = o[n] i sibling: (e, t) -> n = [] while e 1 is e.nodeType and e isnt t and n.push(e) e = e.nextSibling n ) ht = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video" gt = RegExp(" jQuery\\d+=\"(?:null|\\d+)\"", "g") mt = RegExp("<(?:" + ht + ")[\\s/>]", "i") yt = /^\s+/ vt = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/g bt = /<([\w:]+)/ xt = /<tbody/i wt = /<|&#?\w+;/ Tt = /<(?:script|style|link)/i Nt = /^(?:checkbox|radio)$/i Ct = /checked\s*(?:[^=]|=\s*.checked.)/i kt = /^$|\/(?:java|ecma)script/i Et = /^true\/(.*)/ St = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g At = option: [1, "<select multiple='multiple'>", "</select>"] legend: [1, "<fieldset>", "</fieldset>"] area: [1, "<map>", "</map>"] param: [1, "<object>", "</object>"] thead: [1, "<table>", "</table>"] tr: [2, "<table><tbody>", "</tbody></table>"] col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"] td: [3, "<table><tbody><tr>", "</tr></tbody></table>"] _default: (if b.support.htmlSerialize then [0, "", ""] else [1, "X<div>", "</div>"]) jt = dt(o) Dt = jt.appendChild(o.createElement("div")) At.optgroup = At.option At.tbody = At.tfoot = At.colgroup = At.caption = At.thead At.th = At.td b.fn.extend( text: (e) -> b.access this, ((e) -> (if e is t then b.text(this) else @empty().append((this[0] and this[0].ownerDocument or o).createTextNode(e))) ), null, e, arguments_.length wrapAll: (e) -> if b.isFunction(e) return @each((t) -> b(this).wrapAll e.call(this, t) ) if this[0] t = b(e, this[0].ownerDocument).eq(0).clone(not 0) this[0].parentNode and t.insertBefore(this[0]) t.map(-> e = this e = e.firstChild while e.firstChild and 1 is e.firstChild.nodeType e ).append(this) this wrapInner: (e) -> (if b.isFunction(e) then @each((t) -> b(this).wrapInner e.call(this, t) ) else @each(-> t = b(this) n = t.contents() (if n.length then n.wrapAll(e) else t.append(e)) )) wrap: (e) -> t = b.isFunction(e) @each (n) -> b(this).wrapAll (if t then e.call(this, n) else e) unwrap: -> @parent().each(-> b.nodeName(this, "body") or b(this).replaceWith(@childNodes) ).end() append: -> @domManip arguments_, not 0, (e) -> (1 is @nodeType or 11 is @nodeType or 9 is @nodeType) and @appendChild(e) prepend: -> @domManip arguments_, not 0, (e) -> (1 is @nodeType or 11 is @nodeType or 9 is @nodeType) and @insertBefore(e, @firstChild) before: -> @domManip arguments_, not 1, (e) -> @parentNode and @parentNode.insertBefore(e, this) after: -> @domManip arguments_, not 1, (e) -> @parentNode and @parentNode.insertBefore(e, @nextSibling) remove: (e, t) -> n = undefined r = 0 while null isnt (n = this[r]) (not e or b.filter(e, [n]).length > 0) and (t or 1 isnt n.nodeType or b.cleanData(Ot(n)) n.parentNode and (t and b.contains(n.ownerDocument, n) and Mt(Ot(n, "script")) n.parentNode.removeChild(n) ) ) r++ this empty: -> e = undefined t = 0 while null isnt (e = this[t]) 1 is e.nodeType and b.cleanData(Ot(e, not 1)) e.removeChild e.firstChild while e.firstChild e.options and b.nodeName(e, "select") and (e.options.length = 0) t++ this clone: (e, t) -> e = (if null is e then not 1 else e) t = (if null is t then e else t) @map(-> b.clone this, e, t ) html: (e) -> b.access this, ((e) -> n = this[0] or {} r = 0 i = @length return (if 1 is n.nodeType then n.innerHTML.replace(gt, "") else t) if e is t unless "string" isnt typeof e or Tt.test(e) or not b.support.htmlSerialize and mt.test(e) or not b.support.leadingWhitespace and yt.test(e) or At[(bt.exec(e) or ["", ""])[1].toLowerCase()] e = e.replace(vt, "<$1></$2>") try while i > r n = this[r] or {} 1 is n.nodeType and (b.cleanData(Ot(n, not 1)) n.innerHTML = e ) r++ n = 0 n and @empty().append(e) ), null, e, arguments_.length replaceWith: (e) -> t = b.isFunction(e) t or "string" is typeof e or (e = b(e).not(this).detach()) @domManip([e], not 0, (e) -> t = @nextSibling n = @parentNode n and (b(this).remove() n.insertBefore(e, t) ) ) detach: (e) -> @remove e, not 0 domManip: (e, n, r) -> e = f.apply([], e) i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = 0 p = @length d = this h = p - 1 g = e[0] m = b.isFunction(g) if m or not (1 >= p or "string" isnt typeof g or b.support.checkClone) and Ct.test(g) return @each((i) -> o = d.eq(i) m and (e[0] = g.call(this, i, (if n then o.html() else t))) o.domManip(e, n, r) ) if p and (l = b.buildFragment(e, this[0].ownerDocument, not 1, this) i = l.firstChild 1 is l.childNodes.length and (l = i) i ) n = n and b.nodeName(i, "tr") s = b.map(Ot(l, "script"), Ht) a = s.length while p > c o = l c isnt h and (o = b.clone(o, not 0, not 0) a and b.merge(s, Ot(o, "script")) ) r.call((if n and b.nodeName(this[c], "table") then Lt(this[c], "tbody") else this[c]), o, c) c++ if a u = s[s.length - 1].ownerDocument b.map(s, qt) c = 0 while a > c o = s[c] kt.test(o.type or "") and not b._data(o, "globalEval") and b.contains(u, o) and ((if o.src then b.ajax( url: o.src type: "GET" dataType: "script" async: not 1 global: not 1 throws: not 0 ) else b.globalEval((o.text or o.textContent or o.innerHTML or "").replace(St, "")))) c++ l = i = null this ) b.each appendTo: "append" prependTo: "prepend" insertBefore: "before" insertAfter: "after" replaceAll: "replaceWith" , (e, t) -> b.fn[e] = (e) -> n = undefined r = 0 i = [] o = b(e) a = o.length - 1 while a >= r n = (if r is a then this else @clone(not 0)) b(o[r])[t](n) d.apply(i, n.get()) r++ @pushStack i b.extend clone: (e, t, n) -> r = undefined i = undefined o = undefined a = undefined s = undefined u = b.contains(e.ownerDocument, e) if (if b.support.html5Clone or b.isXMLDoc(e) or not mt.test("<" + e.nodeName + ">") then o = e.cloneNode(not 0) else (Dt.innerHTML = e.outerHTML Dt.removeChild(o = Dt.firstChild) )) not (b.support.noCloneEvent and b.support.noCloneChecked or 1 isnt e.nodeType and 11 isnt e.nodeType or b.isXMLDoc(e)) r = Ot(o) s = Ot(e) a = 0 while null isnt (i = s[a]) r[a] and Ft(i, r[a]) ++a if t if n s = s or Ot(e) r = r or Ot(o) a = 0 while null isnt (i = s[a]) _t i, r[a] a++ else _t e, o r = Ot(o, "script") r.length > 0 and Mt(r, not u and Ot(e, "script")) r = s = i = null o buildFragment: (e, t, n, r) -> i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = e.length f = dt(t) d = [] h = 0 while p > h if o = e[h] o or 0 is o if "object" is b.type(o) b.merge d, (if o.nodeType then [o] else o) else if wt.test(o) s = s or f.appendChild(t.createElement("div")) u = (bt.exec(o) or ["", ""])[1].toLowerCase() c = At[u] or At._default s.innerHTML = c[1] + o.replace(vt, "<$1></$2>") + c[2] i = c[0] s = s.lastChild while i-- if not b.support.leadingWhitespace and yt.test(o) and d.push(t.createTextNode(yt.exec(o)[0])) not b.support.tbody o = (if "table" isnt u or xt.test(o) then (if "<table>" isnt c[1] or xt.test(o) then 0 else s) else s.firstChild) i = o and o.childNodes.length b.nodeName(l = o.childNodes[i], "tbody") and not l.childNodes.length and o.removeChild(l) while i-- b.merge(d, s.childNodes) s.textContent = "" s.removeChild s.firstChild while s.firstChild s = f.lastChild else d.push t.createTextNode(o) h++ s and f.removeChild(s) b.support.appendChecked or b.grep(Ot(d, "input"), Bt) h = 0 while o = d[h++] if (not r or -1 is b.inArray(o, r)) and (a = b.contains(o.ownerDocument, o) s = Ot(f.appendChild(o), "script") a and Mt(s) n ) i = 0 kt.test(o.type or "") and n.push(o) while o = s[i++] s = null f cleanData: (e, t) -> n = undefined r = undefined o = undefined a = undefined s = 0 u = b.expando l = b.cache p = b.support.deleteExpando f = b.event.special while null isnt (n = e[s]) if (t or b.acceptData(n)) and (o = n[u] a = o and l[o] ) if a.events for r of a.events (if f[r] then b.event.remove(n, r) else b.removeEvent(n, r, a.handle)) l[o] and (delete l[o] (if p then delete n[u] else (if typeof n.removeAttribute isnt i then n.removeAttribute(u) else n[u] = null)) c.push(o) ) s++ Pt = undefined Rt = undefined Wt = undefined $t = /alpha\([^)]*\)/i It = /opacity\s*=\s*([^)]*)/ zt = /^(top|right|bottom|left)$/ Xt = /^(none|table(?!-c[ea]).+)/ Ut = /^margin/ Vt = RegExp("^(" + x + ")(.*)$", "i") Yt = RegExp("^(" + x + ")(?!px)[a-z%]+$", "i") Jt = RegExp("^([+-])=(" + x + ")", "i") Gt = BODY: "block" Qt = position: "absolute" visibility: "hidden" display: "block" Kt = letterSpacing: 0 fontWeight: 400 Zt = ["Top", "Right", "Bottom", "Left"] en = ["Webkit", "O", "Moz", "ms"] b.fn.extend( css: (e, n) -> b.access this, ((e, n, r) -> i = undefined o = undefined a = {} s = 0 if b.isArray(n) o = Rt(e) i = n.length while i > s a[n[s]] = b.css(e, n[s], not 1, o) s++ return a (if r isnt t then b.style(e, n, r) else b.css(e, n)) ), e, n, arguments_.length > 1 show: -> rn this, not 0 hide: -> rn this toggle: (e) -> t = "boolean" is typeof e @each -> (if ((if t then e else nn(this))) then b(this).show() else b(this).hide()) ) b.extend( cssHooks: opacity: get: (e, t) -> if t n = Wt(e, "opacity") (if "" is n then "1" else n) cssNumber: columnCount: not 0 fillOpacity: not 0 fontWeight: not 0 lineHeight: not 0 opacity: not 0 orphans: not 0 widows: not 0 zIndex: not 0 zoom: not 0 cssProps: float: (if b.support.cssFloat then "cssFloat" else "styleFloat") style: (e, n, r, i) -> if e and 3 isnt e.nodeType and 8 isnt e.nodeType and e.style o = undefined a = undefined s = undefined u = b.camelCase(n) l = e.style return (if s and "get" of s and (o = s.get(e, not 1, i)) isnt t then o else l[n]) if n = b.cssProps[u] or (b.cssProps[u] = tn(l, u)) s = b.cssHooks[n] or b.cssHooks[u] r is t if a = typeof r "string" is a and (o = Jt.exec(r)) and (r = (o[1] + 1) * o[2] + parseFloat(b.css(e, n)) a = "number" ) not (null is r or "number" is a and isNaN(r) or ("number" isnt a or b.cssNumber[u] or (r += "px") b.support.clearCloneStyle or "" isnt r or 0 isnt n.indexOf("background") or (l[n] = "inherit") s and "set" of s and (r = s.set(e, r, i)) is t )) try l[n] = r css: (e, n, r, i) -> o = undefined a = undefined s = undefined u = b.camelCase(n) n = b.cssProps[u] or (b.cssProps[u] = tn(e.style, u)) s = b.cssHooks[n] or b.cssHooks[u] s and "get" of s and (a = s.get(e, not 0, r)) a is t and (a = Wt(e, n, i)) "normal" is a and n of Kt and (a = Kt[n]) (if "" is r or r then (o = parseFloat(a) (if r is not 0 or b.isNumeric(o) then o or 0 else a) ) else a) swap: (e, t, n, r) -> i = undefined o = undefined a = {} for o of t a[o] = e.style[o] e.style[o] = t[o] i = n.apply(e, r or []) for o of t e.style[o] = a[o] i ) (if e.getComputedStyle then (Rt = (t) -> e.getComputedStyle t, null Wt = (e, n, r) -> i = undefined o = undefined a = undefined s = r or Rt(e) u = (if s then s.getPropertyValue(n) or s[n] else t) l = e.style s and ("" isnt u or b.contains(e.ownerDocument, e) or (u = b.style(e, n)) Yt.test(u) and Ut.test(n) and (i = l.width o = l.minWidth a = l.maxWidth l.minWidth = l.maxWidth = l.width = u u = s.width l.width = i l.minWidth = o l.maxWidth = a ) ) u ) else o.documentElement.currentStyle and (Rt = (e) -> e.currentStyle Wt = (e, n, r) -> i = undefined o = undefined a = undefined s = r or Rt(e) u = (if s then s[n] else t) l = e.style null is u and l and l[n] and (u = l[n]) Yt.test(u) and not zt.test(n) and (i = l.left o = e.runtimeStyle a = o and o.left a and (o.left = e.currentStyle.left) l.left = (if "fontSize" is n then "1em" else u) u = l.pixelLeft + "px" l.left = i a and (o.left = a) ) (if "" is u then "auto" else u) )) b.each(["height", "width"], (e, n) -> b.cssHooks[n] = get: (e, r, i) -> (if r then (if 0 is e.offsetWidth and Xt.test(b.css(e, "display")) then b.swap(e, Qt, -> sn e, n, i ) else sn(e, n, i)) else t) set: (e, t, r) -> i = r and Rt(e) on_ e, t, (if r then an(e, n, r, b.support.boxSizing and "border-box" is b.css(e, "boxSizing", not 1, i), i) else 0) ) b.support.opacity or (b.cssHooks.opacity = get: (e, t) -> (if It.test(((if t and e.currentStyle then e.currentStyle.filter else e.style.filter)) or "") then .01 * parseFloat(RegExp.$1) + "" else (if t then "1" else "")) set: (e, t) -> n = e.style r = e.currentStyle i = (if b.isNumeric(t) then "alpha(opacity=" + 100 * t + ")" else "") o = r and r.filter or n.filter or "" n.zoom = 1 (t >= 1 or "" is t) and "" is b.trim(o.replace($t, "")) and n.removeAttribute and (n.removeAttribute("filter") "" is t or r and not r.filter ) or (n.filter = (if $t.test(o) then o.replace($t, i) else o + " " + i)) ) b(-> b.support.reliableMarginRight or (b.cssHooks.marginRight = get: (e, n) -> (if n then b.swap(e, display: "inline-block" , Wt, [e, "marginRight"]) else t) ) not b.support.pixelPosition and b.fn.position and b.each(["top", "left"], (e, n) -> b.cssHooks[n] = get: (e, r) -> (if r then (r = Wt(e, n) (if Yt.test(r) then b(e).position()[n] + "px" else r) ) else t) ) ) b.expr and b.expr.filters and (b.expr.filters.hidden = (e) -> 0 >= e.offsetWidth and 0 >= e.offsetHeight or not b.support.reliableHiddenOffsets and "none" is (e.style and e.style.display or b.css(e, "display")) b.expr.filters.visible = (e) -> not b.expr.filters.hidden(e) ) b.each( margin: "" padding: "" border: "Width" , (e, t) -> b.cssHooks[e + t] = expand: (n) -> r = 0 i = {} o = (if "string" is typeof n then n.split(" ") else [n]) while 4 > r i[e + Zt[r] + t] = o[r] or o[r - 2] or o[0] r++ i Ut.test(e) or (b.cssHooks[e + t].set = on_) ) cn = /%20/g pn = /\[\]$/ fn = /\r?\n/g dn = /^(?:submit|button|image|reset|file)$/i hn = /^(?:input|select|textarea|keygen)/i b.fn.extend( serialize: -> b.param @serializeArray() serializeArray: -> @map(-> e = b.prop(this, "elements") (if e then b.makeArray(e) else this) ).filter(-> e = @type @name and not b(this).is(":disabled") and hn.test(@nodeName) and not dn.test(e) and (@checked or not Nt.test(e)) ).map((e, t) -> n = b(this).val() (if null is n then null else (if b.isArray(n) then b.map(n, (e) -> name: t.name value: e.replace(fn, "\r\n") ) else name: t.name value: n.replace(fn, "\r\n") )) ).get() ) b.param = (e, n) -> r = undefined i = [] o = (e, t) -> t = (if b.isFunction(t) then t() else (if null is t then "" else t)) i[i.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t) if n is t and (n = b.ajaxSettings and b.ajaxSettings.traditional) b.isArray(e) or e.jquery and not b.isPlainObject(e) b.each e, -> o @name, @value else for r of e gn r, e[r], n, o i.join("&").replace cn, "+" b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "), (e, t) -> b.fn[t] = (e, n) -> (if arguments_.length > 0 then @on(t, null, e, n) else @trigger(t)) ) b.fn.hover = (e, t) -> @mouseenter(e).mouseleave t or e mn = undefined yn = undefined vn = b.now() bn = /\?/ xn = /#.*$/ wn = /([?&])_=[^&]*/ Tn = /^(.*?):[ \t]*([^\r\n]*)\r?$/g Nn = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/ Cn = /^(?:GET|HEAD)$/ kn = /^\/\// En = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/ Sn = b.fn.load An = {} jn = {} Dn = "*/".concat("*") try yn = a.href catch Ln yn = o.createElement("a") yn.href = "" yn = yn.href mn = En.exec(yn.toLowerCase()) or [] b.fn.load = (e, n, r) -> return Sn.apply(this, arguments_) if "string" isnt typeof e and Sn i = undefined o = undefined a = undefined s = this u = e.indexOf(" ") u >= 0 and (i = e.slice(u, e.length) e = e.slice(0, u) ) (if b.isFunction(n) then (r = n n = t ) else n and "object" is typeof n and (a = "POST")) s.length > 0 and b.ajax( url: e type: a dataType: "html" data: n ).done((e) -> o = arguments_ s.html((if i then b("<div>").append(b.parseHTML(e)).find(i) else e)) ).complete(r and (e, t) -> s.each r, o or [e.responseText, t, e] ) this b.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], (e, t) -> b.fn[t] = (e) -> @on t, e ) b.each(["get", "post"], (e, n) -> b[n] = (e, r, i, o) -> b.isFunction(r) and (o = o or i i = r r = t ) b.ajax( url: e type: n dataType: o data: r success: i ) ) b.extend( active: 0 lastModified: {} etag: {} ajaxSettings: url: yn type: "GET" isLocal: Nn.test(mn[1]) global: not 0 processData: not 0 async: not 0 contentType: "application/x-www-form-urlencoded; charset=UTF-8" accepts: "*": Dn text: "text/plain" html: "text/html" xml: "application/xml, text/xml" json: "application/json, text/javascript" contents: xml: /xml/ html: /html/ json: /json/ responseFields: xml: "responseXML" text: "responseText" converters: "* text": e.String "text html": not 0 "text json": b.parseJSON "text xml": b.parseXML flatOptions: url: not 0 context: not 0 ajaxSetup: (e, t) -> (if t then Mn(Mn(e, b.ajaxSettings), t) else Mn(b.ajaxSettings, e)) ajaxPrefilter: Hn(An) ajaxTransport: Hn(jn) ajax: (e, n) -> k = (e, n, r, i) -> c = undefined y = undefined v = undefined w = undefined T = undefined C = n 2 isnt x and (x = 2 s and clearTimeout(s) l = t a = i or "" N.readyState = (if e > 0 then 4 else 0) r and (w = _n(p, N, r)) (if e >= 200 and 300 > e or 304 is e then (p.ifModified and (T = N.getResponseHeader("Last-Modified") T and (b.lastModified[o] = T) T = N.getResponseHeader("etag") T and (b.etag[o] = T) ) (if 204 is e then (c = not 0 C = "nocontent" ) else (if 304 is e then (c = not 0 C = "notmodified" ) else (c = Fn(p, w) C = c.state y = c.data v = c.error c = not v ))) ) else (v = C (e or not C) and (C = "error" 0 > e and (e = 0) ) )) N.status = e N.statusText = (n or C) + "" (if c then h.resolveWith(f, [y, C, N]) else h.rejectWith(f, [N, C, v])) N.statusCode(m) m = t u and d.trigger((if c then "ajaxSuccess" else "ajaxError"), [N, p, (if c then y else v)]) g.fireWith(f, [N, C]) u and (d.trigger("ajaxComplete", [N, p]) --b.active or b.event.trigger("ajaxStop") ) ) "object" is typeof e and (n = e e = t ) n = n or {} r = undefined i = undefined o = undefined a = undefined s = undefined u = undefined l = undefined c = undefined p = b.ajaxSetup({}, n) f = p.context or p d = (if p.context and (f.nodeType or f.jquery) then b(f) else b.event) h = b.Deferred() g = b.Callbacks("once memory") m = p.statusCode or {} y = {} v = {} x = 0 T = "canceled" N = readyState: 0 getResponseHeader: (e) -> t = undefined if 2 is x unless c c = {} c[t[1].toLowerCase()] = t[2] while t = Tn.exec(a) t = c[e.toLowerCase()] (if null is t then null else t) getAllResponseHeaders: -> (if 2 is x then a else null) setRequestHeader: (e, t) -> n = e.toLowerCase() x or (e = v[n] = v[n] or e y[e] = t ) this overrideMimeType: (e) -> x or (p.mimeType = e) this statusCode: (e) -> t = undefined if e if 2 > x for t of e m[t] = [m[t], e[t]] else N.always e[N.status] this abort: (e) -> t = e or T l and l.abort(t) k(0, t) this return N if h.promise(N).complete = g.add N.success = N.done N.error = N.fail p.url = ((e or p.url or yn) + "").replace(xn, "").replace(kn, mn[1] + "//") p.type = n.method or n.type or p.method or p.type p.dataTypes = b.trim(p.dataType or "*").toLowerCase().match(w) or [""] null is p.crossDomain and (r = En.exec(p.url.toLowerCase()) p.crossDomain = not (not r or r[1] is mn[1] and r[2] is mn[2] and (r[3] or ((if "http:" is r[1] then 80 else 443))) is (mn[3] or ((if "http:" is mn[1] then 80 else 443)))) ) p.data and p.processData and "string" isnt typeof p.data and (p.data = b.param(p.data, p.traditional)) qn(An, p, n, N) 2 is x u = p.global u and 0 is b.active++ and b.event.trigger("ajaxStart") p.type = p.type.toUpperCase() p.hasContent = not Cn.test(p.type) o = p.url p.hasContent or (p.data and (o = p.url += ((if bn.test(o) then "&" else "?")) + p.data delete p.data ) p.cache is not 1 and (p.url = (if wn.test(o) then o.replace(wn, "$1_=" + vn++) else o + ((if bn.test(o) then "&" else "?")) + "_=" + vn++)) ) p.ifModified and (b.lastModified[o] and N.setRequestHeader("If-Modified-Since", b.lastModified[o]) b.etag[o] and N.setRequestHeader("If-None-Match", b.etag[o]) ) (p.data and p.hasContent and p.contentType isnt not 1 or n.contentType) and N.setRequestHeader("Content-Type", p.contentType) N.setRequestHeader("Accept", (if p.dataTypes[0] and p.accepts[p.dataTypes[0]] then p.accepts[p.dataTypes[0]] + ((if "*" isnt p.dataTypes[0] then ", " + Dn + "; q=0.01" else "")) else p.accepts["*"])) for i of p.headers N.setRequestHeader i, p.headers[i] return N.abort() if p.beforeSend and (p.beforeSend.call(f, N, p) is not 1 or 2 is x) T = "abort" for i of success: 1 error: 1 complete: 1 N[i] p[i] if l = qn(jn, p, n, N) N.readyState = 1 u and d.trigger("ajaxSend", [N, p]) p.async and p.timeout > 0 and (s = setTimeout(-> N.abort "timeout" , p.timeout)) try x = 1 l.send(y, k) catch C throw C unless 2 > x k -1, C else k -1, "No Transport" N getScript: (e, n) -> b.get e, t, n, "script" getJSON: (e, t, n) -> b.get e, t, n, "json" ) b.ajaxSetup( accepts: script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" contents: script: /(?:java|ecma)script/ converters: "text script": (e) -> b.globalEval(e) e ) b.ajaxPrefilter("script", (e) -> e.cache is t and (e.cache = not 1) e.crossDomain and (e.type = "GET" e.global = not 1 ) ) b.ajaxTransport("script", (e) -> if e.crossDomain n = undefined r = o.head or b("head")[0] or o.documentElement send: (t, i) -> n = o.createElement("script") n.async = not 0 e.scriptCharset and (n.charset = e.scriptCharset) n.src = e.url n.onload = n.onreadystatechange = (e, t) -> (t or not n.readyState or /loaded|complete/.test(n.readyState)) and (n.onload = n.onreadystatechange = null n.parentNode and n.parentNode.removeChild(n) n = null t or i(200, "success") ) r.insertBefore(n, r.firstChild) abort: -> n and n.onload(t, not 0) ) On = [] Bn = /(=)\?(?=&|$)|\?\?/ b.ajaxSetup( jsonp: "callback" jsonpCallback: -> e = On.pop() or b.expando + "_" + vn++ this[e] = not 0 e ) b.ajaxPrefilter("json jsonp", (n, r, i) -> o = undefined a = undefined s = undefined u = n.jsonp isnt not 1 and ((if Bn.test(n.url) then "url" else "string" is typeof n.data and not (n.contentType or "").indexOf("application/x-www-form-urlencoded") and Bn.test(n.data) and "data")) (if u or "jsonp" is n.dataTypes[0] then (o = n.jsonpCallback = (if b.isFunction(n.jsonpCallback) then n.jsonpCallback() else n.jsonpCallback) (if u then n[u] = n[u].replace(Bn, "$1" + o) else n.jsonp isnt not 1 and (n.url += ((if bn.test(n.url) then "&" else "?")) + n.jsonp + "=" + o)) n.converters["script json"] = -> s or b.error(o + " was not called") s[0] n.dataTypes[0] = "json" a = e[o] e[o] = -> s = arguments_ i.always(-> e[o] = a n[o] and (n.jsonpCallback = r.jsonpCallback On.push(o) ) s and b.isFunction(a) and a(s[0]) s = a = t ) "script" ) else t) ) Pn = undefined Rn = undefined Wn = 0 $n = e.ActiveXObject and -> e = undefined for e of Pn Pn[e] t, not 0 b.ajaxSettings.xhr = (if e.ActiveXObject then -> not @isLocal and In() or zn() else In) Rn = b.ajaxSettings.xhr() b.support.cors = !!Rn and "withCredentials" of Rn Rn = b.support.ajax = !!Rn Rn and b.ajaxTransport((n) -> if not n.crossDomain or b.support.cors r = undefined send: (i, o) -> a = undefined s = undefined u = n.xhr() if (if n.username then u.open(n.type, n.url, n.async, n.username, n.password) else u.open(n.type, n.url, n.async)) n.xhrFields for s of n.xhrFields u[s] = n.xhrFields[s] n.mimeType and u.overrideMimeType and u.overrideMimeType(n.mimeType) n.crossDomain or i["X-Requested-With"] or (i["X-Requested-With"] = "XMLHttpRequest") try for s of i u.setRequestHeader s, i[s] u.send(n.hasContent and n.data or null) r = (e, i) -> s = undefined l = undefined c = undefined p = undefined try if r and (i or 4 is u.readyState) unless r = t a and (u.onreadystatechange = b.noop $n and delete Pn[a] ) i p = {} s = u.status l = u.getAllResponseHeaders() "string" is typeof u.responseText and (p.text = u.responseText) try c = u.statusText catch f c = "" (if s or not n.isLocal or n.crossDomain then 1223 is s and (s = 204) else s = (if p.text then 200 else 404)) catch d i or o(-1, d) p and o(s, c, p, l) (if n.async then (if 4 is u.readyState then setTimeout(r) else (a = ++Wn $n and (Pn or (Pn = {} b(e).unload($n) ) Pn[a] = r ) u.onreadystatechange = r )) else r()) abort: -> r and r(t, not 0) ) Xn = undefined Un = undefined Vn = /^(?:toggle|show|hide)$/ Yn = RegExp("^(?:([+-])=|)(" + x + ")([a-z%]*)$", "i") Jn = /queueHooks$/ Gn = [nr] Qn = "*": [(e, t) -> n = undefined r = undefined i = @createTween(e, t) o = Yn.exec(t) a = i.cur() s = +a or 0 u = 1 l = 20 if o if n = +o[2] r = o[3] or ((if b.cssNumber[e] then "" else "px")) "px" isnt r and s s = b.css(i.elem, e, not 0) or n or 1 loop u = u or ".5" s /= u b.style(i.elem, e, s + r) break unless u isnt (u = i.cur() / a) and 1 isnt u and --l i.unit = r i.start = s i.end = (if o[1] then s + (o[1] + 1) * n else n) i ] b.Animation = b.extend(er, tweener: (e, t) -> (if b.isFunction(e) then (t = e e = ["*"] ) else e = e.split(" ")) n = undefined r = 0 i = e.length while i > r n = e[r] Qn[n] = Qn[n] or [] Qn[n].unshift(t) r++ prefilter: (e, t) -> (if t then Gn.unshift(e) else Gn.push(e)) ) b.Tween = rr rr:: = constructor: rr init: (e, t, n, r, i, o) -> @elem = e @prop = n @easing = i or "swing" @options = t @start = @now = @cur() @end = r @unit = o or ((if b.cssNumber[n] then "" else "px")) cur: -> e = rr.propHooks[@prop] (if e and e.get then e.get(this) else rr.propHooks._default.get(this)) run: (e) -> t = undefined n = rr.propHooks[@prop] @pos = t = (if @options.duration then b.easing[@easing](e, @options.duration * e, 0, 1, @options.duration) else e) @now = (@end - @start) * t + @start @options.step and @options.step.call(@elem, @now, this) (if n and n.set then n.set(this) else rr.propHooks._default.set(this)) this rr::init:: = rr:: rr.propHooks = _default: get: (e) -> t = undefined (if null is e.elem[e.prop] or e.elem.style and null isnt e.elem.style[e.prop] then (t = b.css(e.elem, e.prop, "") (if t and "auto" isnt t then t else 0) ) else e.elem[e.prop]) set: (e) -> (if b.fx.step[e.prop] then b.fx.step[e.prop](e) else (if e.elem.style and (null isnt e.elem.style[b.cssProps[e.prop]] or b.cssHooks[e.prop]) then b.style(e.elem, e.prop, e.now + e.unit) else e.elem[e.prop] = e.now)) rr.propHooks.scrollTop = rr.propHooks.scrollLeft = set: (e) -> e.elem.nodeType and e.elem.parentNode and (e.elem[e.prop] = e.now) b.each(["toggle", "show", "hide"], (e, t) -> n = b.fn[t] b.fn[t] = (e, r, i) -> (if null is e or "boolean" is typeof e then n.apply(this, arguments_) else @animate(ir(t, not 0), e, r, i)) ) b.fn.extend( fadeTo: (e, t, n, r) -> @filter(nn).css("opacity", 0).show().end().animate opacity: t , e, n, r animate: (e, t, n, r) -> i = b.isEmptyObject(e) o = b.speed(t, n, r) a = -> t = er(this, b.extend({}, e), o) a.finish = -> t.stop not 0 (i or b._data(this, "finish")) and t.stop(not 0) a.finish = a (if i or o.queue is not 1 then @each(a) else @queue(o.queue, a)) stop: (e, n, r) -> i = (e) -> t = e.stop delete e.stop t(r) "string" isnt typeof e and (r = n n = e e = t ) n and e isnt not 1 and @queue(e or "fx", []) @each(-> t = not 0 n = null isnt e and e + "queueHooks" o = b.timers a = b._data(this) if n a[n] and a[n].stop and i(a[n]) else for n of a a[n] and a[n].stop and Jn.test(n) and i(a[n]) n = o.length while n-- o[n].elem isnt this or null isnt e and o[n].queue isnt e or (o[n].anim.stop(r) t = not 1 o.splice(n, 1) ) (t or not r) and b.dequeue(this, e) ) finish: (e) -> e isnt not 1 and (e = e or "fx") @each(-> t = undefined n = b._data(this) r = n[e + "queue"] i = n[e + "queueHooks"] o = b.timers a = (if r then r.length else 0) n.finish = not 0 b.queue(this, e, []) i and i.cur and i.cur.finish and i.cur.finish.call(this) t = o.length while t-- o[t].elem is this and o[t].queue is e and (o[t].anim.stop(not 0) o.splice(t, 1) ) t = 0 while a > t r[t] and r[t].finish and r[t].finish.call(this) t++ delete n.finish ) ) b.each( slideDown: ir("show") slideUp: ir("hide") slideToggle: ir("toggle") fadeIn: opacity: "show" fadeOut: opacity: "hide" fadeToggle: opacity: "toggle" , (e, t) -> b.fn[e] = (e, n, r) -> @animate t, e, n, r ) b.speed = (e, t, n) -> r = (if e and "object" is typeof e then b.extend({}, e) else complete: n or not n and t or b.isFunction(e) and e duration: e easing: n and t or t and not b.isFunction(t) and t ) r.duration = (if b.fx.off then 0 else (if "number" is typeof r.duration then r.duration else (if r.duration of b.fx.speeds then b.fx.speeds[r.duration] else b.fx.speeds._default))) (null is r.queue or r.queue is not 0) and (r.queue = "fx") r.old = r.complete r.complete = -> b.isFunction(r.old) and r.old.call(this) r.queue and b.dequeue(this, r.queue) r b.easing = linear: (e) -> e swing: (e) -> .5 - Math.cos(e * Math.PI) / 2 b.timers = [] b.fx = rr::init b.fx.tick = -> e = undefined n = b.timers r = 0 Xn = b.now() while n.length > r e = n[r] e() or n[r] isnt e or n.splice(r--, 1) r++ n.length or b.fx.stop() Xn = t b.fx.timer = (e) -> e() and b.timers.push(e) and b.fx.start() b.fx.interval = 13 b.fx.start = -> Un or (Un = setInterval(b.fx.tick, b.fx.interval)) b.fx.stop = -> clearInterval(Un) Un = null b.fx.speeds = slow: 600 fast: 200 _default: 400 b.fx.step = {} b.expr and b.expr.filters and (b.expr.filters.animated = (e) -> b.grep(b.timers, (t) -> e is t.elem ).length ) b.fn.offset = (e) -> if arguments_.length return (if e is t then this else @each((t) -> b.offset.setOffset this, e, t )) n = undefined r = undefined o = top: 0 left: 0 a = this[0] s = a and a.ownerDocument if s n = s.documentElement (if b.contains(n, a) then (typeof a.getBoundingClientRect isnt i and (o = a.getBoundingClientRect()) r = or_(s) top: o.top + (r.pageYOffset or n.scrollTop) - (n.clientTop or 0) left: o.left + (r.pageXOffset or n.scrollLeft) - (n.clientLeft or 0) ) else o) b.offset = setOffset: (e, t, n) -> r = b.css(e, "position") "static" is r and (e.style.position = "relative") i = b(e) o = i.offset() a = b.css(e, "top") s = b.css(e, "left") u = ("absolute" is r or "fixed" is r) and b.inArray("auto", [a, s]) > -1 l = {} c = {} p = undefined f = undefined (if u then (c = i.position() p = c.top f = c.left ) else (p = parseFloat(a) or 0 f = parseFloat(s) or 0 )) b.isFunction(t) and (t = t.call(e, n, o)) null isnt t.top and (l.top = t.top - o.top + p) null isnt t.left and (l.left = t.left - o.left + f) (if "using" of t then t.using.call(e, l) else i.css(l)) b.fn.extend( position: -> if this[0] e = undefined t = undefined n = top: 0 left: 0 r = this[0] (if "fixed" is b.css(r, "position") then t = r.getBoundingClientRect() else (e = @offsetParent() t = @offset() b.nodeName(e[0], "html") or (n = e.offset()) n.top += b.css(e[0], "borderTopWidth", not 0) n.left += b.css(e[0], "borderLeftWidth", not 0) )) top: t.top - n.top - b.css(r, "marginTop", not 0) left: t.left - n.left - b.css(r, "marginLeft", not 0) offsetParent: -> @map -> e = @offsetParent or o.documentElement e = e.offsetParent while e and not b.nodeName(e, "html") and "static" is b.css(e, "position") e or o.documentElement ) b.each( scrollLeft: "pageXOffset" scrollTop: "pageYOffset" , (e, n) -> r = /Y/.test(n) b.fn[e] = (i) -> b.access this, ((e, i, o) -> a = or_(e) (if o is t then (if a then (if n of a then a[n] else a.document.documentElement[i]) else e[i]) else ((if a then a.scrollTo((if r then b(a).scrollLeft() else o), (if r then o else b(a).scrollTop())) else e[i] = o) t )) ), e, i, arguments_.length, null ) b.each( Height: "height" Width: "width" , (e, n) -> b.each padding: "inner" + e content: n "": "outer" + e , (r, i) -> b.fn[i] = (i, o) -> a = arguments_.length and (r or "boolean" isnt typeof i) s = r or ((if i is not 0 or o is not 0 then "margin" else "border")) b.access this, ((n, r, i) -> o = undefined (if b.isWindow(n) then n.document.documentElement["client" + e] else (if 9 is n.nodeType then (o = n.documentElement Math.max(n.body["scroll" + e], o["scroll" + e], n.body["offset" + e], o["offset" + e], o["client" + e]) ) else (if i is t then b.css(n, r, s) else b.style(n, r, i, s)))) ), n, (if a then i else t), a, null ) e.jQuery = e.$ = b "function" is typeof define and define.amd and define.amd.jQuery and define("jquery", [], -> b ) ) window
[ { "context": "en who have a future and women who have a past.” - Oscar Wilde'), '1gmfFH'\n\t\t\tit.eq jhash.hash('芝兰生于深谷,不以无人而不芳。'", "end": 295, "score": 0.9993144273757935, "start": 284, "tag": "NAME", "value": "Oscar Wilde" } ]
test/basic.coffee
ysmood/jhash
5
jhash = require '../src/jhash' kit = require 'nokit' {Promise} = kit module.exports = (it) -> stringTest = () -> Promise.all [ it.eq jhash.hash('test'), '349o' it.eq jhash.hash('1234'), '343E' it.eq jhash.hash('“I like men who have a future and women who have a past.” - Oscar Wilde'), '1gmfFH' it.eq jhash.hash('芝兰生于深谷,不以无人而不芳。'), '1QVoF2' it.eq jhash.hash('信じることから始まるのが宗教なら、疑うことから始めるのが科学です。'), '276j!6' ] arrTest = -> it.eq jhash.hash([1, 2, 3, 4]), '33*M' bufTest = -> buf = kit.readFileSync 'test/rand_file.bin' it.eq jhash.hash(buf), '1GC3Um' it.describe '# hash', (it) -> it 'Should works with string', stringTest it 'Should works with array', arrTest it 'Should works with buffer', bufTest it.describe '# hashStr', (it) -> it 'Should works with string', stringTest it.describe '# hashArr', (it) -> it 'Should works with array', arrTest it 'Should works with buffer', bufTest it.describe '# setSymbols', (it) -> it 'Should works properly', -> jhash.setSymbols 'abc' it.eq jhash.hash('test'), 'bcccaccaccacb' it.describe '# setMaskLen', (it) -> it 'Should works properly', -> jhash.setMaskLen 10 it.eq jhash.hash('test'), 'caabb'
3422
jhash = require '../src/jhash' kit = require 'nokit' {Promise} = kit module.exports = (it) -> stringTest = () -> Promise.all [ it.eq jhash.hash('test'), '349o' it.eq jhash.hash('1234'), '343E' it.eq jhash.hash('“I like men who have a future and women who have a past.” - <NAME>'), '1gmfFH' it.eq jhash.hash('芝兰生于深谷,不以无人而不芳。'), '1QVoF2' it.eq jhash.hash('信じることから始まるのが宗教なら、疑うことから始めるのが科学です。'), '276j!6' ] arrTest = -> it.eq jhash.hash([1, 2, 3, 4]), '33*M' bufTest = -> buf = kit.readFileSync 'test/rand_file.bin' it.eq jhash.hash(buf), '1GC3Um' it.describe '# hash', (it) -> it 'Should works with string', stringTest it 'Should works with array', arrTest it 'Should works with buffer', bufTest it.describe '# hashStr', (it) -> it 'Should works with string', stringTest it.describe '# hashArr', (it) -> it 'Should works with array', arrTest it 'Should works with buffer', bufTest it.describe '# setSymbols', (it) -> it 'Should works properly', -> jhash.setSymbols 'abc' it.eq jhash.hash('test'), 'bcccaccaccacb' it.describe '# setMaskLen', (it) -> it 'Should works properly', -> jhash.setMaskLen 10 it.eq jhash.hash('test'), 'caabb'
true
jhash = require '../src/jhash' kit = require 'nokit' {Promise} = kit module.exports = (it) -> stringTest = () -> Promise.all [ it.eq jhash.hash('test'), '349o' it.eq jhash.hash('1234'), '343E' it.eq jhash.hash('“I like men who have a future and women who have a past.” - PI:NAME:<NAME>END_PI'), '1gmfFH' it.eq jhash.hash('芝兰生于深谷,不以无人而不芳。'), '1QVoF2' it.eq jhash.hash('信じることから始まるのが宗教なら、疑うことから始めるのが科学です。'), '276j!6' ] arrTest = -> it.eq jhash.hash([1, 2, 3, 4]), '33*M' bufTest = -> buf = kit.readFileSync 'test/rand_file.bin' it.eq jhash.hash(buf), '1GC3Um' it.describe '# hash', (it) -> it 'Should works with string', stringTest it 'Should works with array', arrTest it 'Should works with buffer', bufTest it.describe '# hashStr', (it) -> it 'Should works with string', stringTest it.describe '# hashArr', (it) -> it 'Should works with array', arrTest it 'Should works with buffer', bufTest it.describe '# setSymbols', (it) -> it 'Should works properly', -> jhash.setSymbols 'abc' it.eq jhash.hash('test'), 'bcccaccaccacb' it.describe '# setMaskLen', (it) -> it 'Should works properly', -> jhash.setMaskLen 10 it.eq jhash.hash('test'), 'caabb'
[ { "context": "response)-> \n sgMail.send(\n to: ['jamesd@betrefinery.com', 'jamesm@betrefinery.com', 'jasonw@betrefinery.c", "end": 2868, "score": 0.9999316334724426, "start": 2846, "tag": "EMAIL", "value": "jamesd@betrefinery.com" }, { "context": "l.send(\n ...
src/functions/newsLetterSignup.coffee
jdrucza/bet-refinery
0
sgMail = require("@sendgrid/mail") client = require("@sendgrid/client") eBookData = require('./ebook').data addSendgridRecipient = (client, email, countryCode)-> console.log "adding recipient", { email, countryCode } new Promise((fulfill, reject) -> data = { contacts: [ { email: email country: countryCode } ] } request = { method: "PUT" url: "/v3/marketing/contacts" body: data } console.log "ADDING RECIPIENT", { request, client } client.request(request).then(([response, body]) -> console.log "ADD RECIPIENT finished." console.log(response.statusCode) console.log({body}) fulfill(response) ).catch((error)-> console.log "ADD RECIPIEENT failed.", {error} reject(error) ) ) sendWelcomeEmail = (client, email, senderEmail, senderName, templateID, eBookFileName)-> new Promise((fulfill, reject) -> data = from: email: senderEmail, name: senderName reply_to: email: senderEmail personalizations: [ { to: [ { email: email } ] } ] template_id: templateID if eBookFileName? and eBookFileName.length > 0 console.log "Attaching EBOOK to email" data.attachments = [ { content: eBookData filename: eBookFileName type: "application/pdf" disposition: "attachment" } ] request = method: "POST", url: "/v3/mail/send", body: data client.request(request).then(([response, body]) -> console.log "SEND WELCOME finished" console.log(response.statusCode); console.log(body); fulfill(response); ).catch((error)-> reject(error)); ) module.exports = { handler: (event, context, callback)-> { SENDGRID_API_KEY, SENDGRID_WELCOME_SENDER_EMAIL, SENDGRID_WELCOME_SENDER_NAME, SENDGRID_WELCOME_TEMPLATE_ID } = process.env body = JSON.parse(event.body) email = body.email eBookFileName = body.eBookFileName countryCode = body.countryCode # welcomeEmail = event.queryStringParameters.welcome_email == "true" sgMail.setApiKey(SENDGRID_API_KEY) client.setApiKey(SENDGRID_API_KEY) console.log({ client email SENDGRID_WELCOME_SENDER_EMAIL SENDGRID_WELCOME_SENDER_NAME SENDGRID_WELCOME_TEMPLATE_ID eBookFileName }) addSendgridRecipient(client, email, countryCode) .then((response, body)-> sendWelcomeEmail( client email SENDGRID_WELCOME_SENDER_EMAIL SENDGRID_WELCOME_SENDER_NAME SENDGRID_WELCOME_TEMPLATE_ID eBookFileName ) .then((response)-> sgMail.send( to: ['jamesd@betrefinery.com', 'jamesm@betrefinery.com', 'jasonw@betrefinery.com'] from: 'jamesd@betrefinery.com' subject: 'New Newsletter Subscriber!!' text: "#{email} from #{countryCode}" ) callback(null, { statusCode: response.statusCode, body: email + " added" }) ) .catch((err)->callback(err, null)) ) .catch((err)-> callback(err, null)) }
96653
sgMail = require("@sendgrid/mail") client = require("@sendgrid/client") eBookData = require('./ebook').data addSendgridRecipient = (client, email, countryCode)-> console.log "adding recipient", { email, countryCode } new Promise((fulfill, reject) -> data = { contacts: [ { email: email country: countryCode } ] } request = { method: "PUT" url: "/v3/marketing/contacts" body: data } console.log "ADDING RECIPIENT", { request, client } client.request(request).then(([response, body]) -> console.log "ADD RECIPIENT finished." console.log(response.statusCode) console.log({body}) fulfill(response) ).catch((error)-> console.log "ADD RECIPIEENT failed.", {error} reject(error) ) ) sendWelcomeEmail = (client, email, senderEmail, senderName, templateID, eBookFileName)-> new Promise((fulfill, reject) -> data = from: email: senderEmail, name: senderName reply_to: email: senderEmail personalizations: [ { to: [ { email: email } ] } ] template_id: templateID if eBookFileName? and eBookFileName.length > 0 console.log "Attaching EBOOK to email" data.attachments = [ { content: eBookData filename: eBookFileName type: "application/pdf" disposition: "attachment" } ] request = method: "POST", url: "/v3/mail/send", body: data client.request(request).then(([response, body]) -> console.log "SEND WELCOME finished" console.log(response.statusCode); console.log(body); fulfill(response); ).catch((error)-> reject(error)); ) module.exports = { handler: (event, context, callback)-> { SENDGRID_API_KEY, SENDGRID_WELCOME_SENDER_EMAIL, SENDGRID_WELCOME_SENDER_NAME, SENDGRID_WELCOME_TEMPLATE_ID } = process.env body = JSON.parse(event.body) email = body.email eBookFileName = body.eBookFileName countryCode = body.countryCode # welcomeEmail = event.queryStringParameters.welcome_email == "true" sgMail.setApiKey(SENDGRID_API_KEY) client.setApiKey(SENDGRID_API_KEY) console.log({ client email SENDGRID_WELCOME_SENDER_EMAIL SENDGRID_WELCOME_SENDER_NAME SENDGRID_WELCOME_TEMPLATE_ID eBookFileName }) addSendgridRecipient(client, email, countryCode) .then((response, body)-> sendWelcomeEmail( client email SENDGRID_WELCOME_SENDER_EMAIL SENDGRID_WELCOME_SENDER_NAME SENDGRID_WELCOME_TEMPLATE_ID eBookFileName ) .then((response)-> sgMail.send( to: ['<EMAIL>', '<EMAIL>', '<EMAIL>'] from: '<EMAIL>' subject: 'New Newsletter Subscriber!!' text: "#{email} from #{countryCode}" ) callback(null, { statusCode: response.statusCode, body: email + " added" }) ) .catch((err)->callback(err, null)) ) .catch((err)-> callback(err, null)) }
true
sgMail = require("@sendgrid/mail") client = require("@sendgrid/client") eBookData = require('./ebook').data addSendgridRecipient = (client, email, countryCode)-> console.log "adding recipient", { email, countryCode } new Promise((fulfill, reject) -> data = { contacts: [ { email: email country: countryCode } ] } request = { method: "PUT" url: "/v3/marketing/contacts" body: data } console.log "ADDING RECIPIENT", { request, client } client.request(request).then(([response, body]) -> console.log "ADD RECIPIENT finished." console.log(response.statusCode) console.log({body}) fulfill(response) ).catch((error)-> console.log "ADD RECIPIEENT failed.", {error} reject(error) ) ) sendWelcomeEmail = (client, email, senderEmail, senderName, templateID, eBookFileName)-> new Promise((fulfill, reject) -> data = from: email: senderEmail, name: senderName reply_to: email: senderEmail personalizations: [ { to: [ { email: email } ] } ] template_id: templateID if eBookFileName? and eBookFileName.length > 0 console.log "Attaching EBOOK to email" data.attachments = [ { content: eBookData filename: eBookFileName type: "application/pdf" disposition: "attachment" } ] request = method: "POST", url: "/v3/mail/send", body: data client.request(request).then(([response, body]) -> console.log "SEND WELCOME finished" console.log(response.statusCode); console.log(body); fulfill(response); ).catch((error)-> reject(error)); ) module.exports = { handler: (event, context, callback)-> { SENDGRID_API_KEY, SENDGRID_WELCOME_SENDER_EMAIL, SENDGRID_WELCOME_SENDER_NAME, SENDGRID_WELCOME_TEMPLATE_ID } = process.env body = JSON.parse(event.body) email = body.email eBookFileName = body.eBookFileName countryCode = body.countryCode # welcomeEmail = event.queryStringParameters.welcome_email == "true" sgMail.setApiKey(SENDGRID_API_KEY) client.setApiKey(SENDGRID_API_KEY) console.log({ client email SENDGRID_WELCOME_SENDER_EMAIL SENDGRID_WELCOME_SENDER_NAME SENDGRID_WELCOME_TEMPLATE_ID eBookFileName }) addSendgridRecipient(client, email, countryCode) .then((response, body)-> sendWelcomeEmail( client email SENDGRID_WELCOME_SENDER_EMAIL SENDGRID_WELCOME_SENDER_NAME SENDGRID_WELCOME_TEMPLATE_ID eBookFileName ) .then((response)-> sgMail.send( to: ['PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI'] from: 'PI:EMAIL:<EMAIL>END_PI' subject: 'New Newsletter Subscriber!!' text: "#{email} from #{countryCode}" ) callback(null, { statusCode: response.statusCode, body: email + " added" }) ) .catch((err)->callback(err, null)) ) .catch((err)-> callback(err, null)) }
[ { "context": " group_level: 2\n startkey: ['uid', '']\n endkey: ['uid', \"\\uFFFF\"]\n ", "end": 1868, "score": 0.9773534536361694, "start": 1865, "tag": "KEY", "value": "uid" }, { "context": " startkey: ['uid', '']\n endkey: ['uid'...
server/processes/orphan_removal.coffee
cozy-labs/emails
58
ramStore = require '../models/store_account_and_boxes' Message = require '../models/message' Mailbox = require '../models/mailbox' safeLoop = require '../utils/safeloop' Process = require './_base' RemoveAllMessagesFromMailbox = require './message_remove_by_mailbox' Scheduler = require './_scheduler' log = require('../utils/logging')('process:removeorphans') async = require 'async' module.exports = class OrphanRemoval extends Process code: 'orphan-removal' initialize: (options, callback) -> async.series [ @removeMailboxOrphans @forgetDestroyedBoxes @getOrphanMessageMailboxesIDs @removeOrphansMessageFromMailboxes @destroyNoBoxMessages ], callback # Public: remove mailboxes linked to an account that doesn't exist # in cozy. # # Returns (callback) at completion removeMailboxOrphans: (callback) -> log.debug "removeOrphans" safeLoop ramStore.getOrphanBoxes(), (box, next) -> box.destroy next , (errors) -> for err in errors when -1 is err.message.indexOf 'not found' log.error 'failed to delete box', err callback null forgetDestroyedBoxes: (callback) -> toForget = [] for account in ramStore.getAllAccounts() for boxid in account.getReferencedBoxes() unless ramStore.getMailbox boxid toForget.push {account, boxid} safeLoop toForget, ({account, boxid}, next) -> account.forgetBox boxid, next , (errors) -> log.error "failed to forget box", err for err in errors callback null getOrphanMessageMailboxesIDs: (callback) => Message.rawRequest 'byMailboxRequest', reduce: true group_level: 2 startkey: ['uid', ''] endkey: ['uid', "\uFFFF"] , (err, rows) => return callback err if err mailboxIDs = rows.map (row) -> row.key[1] existingMailboxes = ramStore.getMailboxesID() @toDestroyMailboxIDs = mailboxIDs.filter (id) -> id not in existingMailboxes callback null removeOrphansMessageFromMailboxes: (callback) => safeLoop @toDestroyMailboxIDs, (mailboxID, next) => log.debug "removeOrphans - found orphan from box", mailboxID options = {mailboxID, @toDestroyMailboxIDs} removal = new RemoveAllMessagesFromMailbox options removal.run next , (errors) -> log.error "failed to remove message", err for err in errors callback null destroyNoBoxMessages: (callback) -> options = key: ['nobox'] reduce: false Message.rawRequest 'byMailboxRequest', options, (err, rows) -> return callback err if err safeLoop rows, (row, next) -> Message.destroy row.id, next , (errors) -> log.error 'fail to destroy orphan msg', err for err in errors callback null
13712
ramStore = require '../models/store_account_and_boxes' Message = require '../models/message' Mailbox = require '../models/mailbox' safeLoop = require '../utils/safeloop' Process = require './_base' RemoveAllMessagesFromMailbox = require './message_remove_by_mailbox' Scheduler = require './_scheduler' log = require('../utils/logging')('process:removeorphans') async = require 'async' module.exports = class OrphanRemoval extends Process code: 'orphan-removal' initialize: (options, callback) -> async.series [ @removeMailboxOrphans @forgetDestroyedBoxes @getOrphanMessageMailboxesIDs @removeOrphansMessageFromMailboxes @destroyNoBoxMessages ], callback # Public: remove mailboxes linked to an account that doesn't exist # in cozy. # # Returns (callback) at completion removeMailboxOrphans: (callback) -> log.debug "removeOrphans" safeLoop ramStore.getOrphanBoxes(), (box, next) -> box.destroy next , (errors) -> for err in errors when -1 is err.message.indexOf 'not found' log.error 'failed to delete box', err callback null forgetDestroyedBoxes: (callback) -> toForget = [] for account in ramStore.getAllAccounts() for boxid in account.getReferencedBoxes() unless ramStore.getMailbox boxid toForget.push {account, boxid} safeLoop toForget, ({account, boxid}, next) -> account.forgetBox boxid, next , (errors) -> log.error "failed to forget box", err for err in errors callback null getOrphanMessageMailboxesIDs: (callback) => Message.rawRequest 'byMailboxRequest', reduce: true group_level: 2 startkey: ['<KEY>', ''] endkey: ['<KEY>', <KEY>"] , (err, rows) => return callback err if err mailboxIDs = rows.map (row) -> row.key[1] existingMailboxes = ramStore.getMailboxesID() @toDestroyMailboxIDs = mailboxIDs.filter (id) -> id not in existingMailboxes callback null removeOrphansMessageFromMailboxes: (callback) => safeLoop @toDestroyMailboxIDs, (mailboxID, next) => log.debug "removeOrphans - found orphan from box", mailboxID options = {mailboxID, @toDestroyMailboxIDs} removal = new RemoveAllMessagesFromMailbox options removal.run next , (errors) -> log.error "failed to remove message", err for err in errors callback null destroyNoBoxMessages: (callback) -> options = key: ['<KEY>'] reduce: false Message.rawRequest 'byMailboxRequest', options, (err, rows) -> return callback err if err safeLoop rows, (row, next) -> Message.destroy row.id, next , (errors) -> log.error 'fail to destroy orphan msg', err for err in errors callback null
true
ramStore = require '../models/store_account_and_boxes' Message = require '../models/message' Mailbox = require '../models/mailbox' safeLoop = require '../utils/safeloop' Process = require './_base' RemoveAllMessagesFromMailbox = require './message_remove_by_mailbox' Scheduler = require './_scheduler' log = require('../utils/logging')('process:removeorphans') async = require 'async' module.exports = class OrphanRemoval extends Process code: 'orphan-removal' initialize: (options, callback) -> async.series [ @removeMailboxOrphans @forgetDestroyedBoxes @getOrphanMessageMailboxesIDs @removeOrphansMessageFromMailboxes @destroyNoBoxMessages ], callback # Public: remove mailboxes linked to an account that doesn't exist # in cozy. # # Returns (callback) at completion removeMailboxOrphans: (callback) -> log.debug "removeOrphans" safeLoop ramStore.getOrphanBoxes(), (box, next) -> box.destroy next , (errors) -> for err in errors when -1 is err.message.indexOf 'not found' log.error 'failed to delete box', err callback null forgetDestroyedBoxes: (callback) -> toForget = [] for account in ramStore.getAllAccounts() for boxid in account.getReferencedBoxes() unless ramStore.getMailbox boxid toForget.push {account, boxid} safeLoop toForget, ({account, boxid}, next) -> account.forgetBox boxid, next , (errors) -> log.error "failed to forget box", err for err in errors callback null getOrphanMessageMailboxesIDs: (callback) => Message.rawRequest 'byMailboxRequest', reduce: true group_level: 2 startkey: ['PI:KEY:<KEY>END_PI', ''] endkey: ['PI:KEY:<KEY>END_PI', PI:KEY:<KEY>END_PI"] , (err, rows) => return callback err if err mailboxIDs = rows.map (row) -> row.key[1] existingMailboxes = ramStore.getMailboxesID() @toDestroyMailboxIDs = mailboxIDs.filter (id) -> id not in existingMailboxes callback null removeOrphansMessageFromMailboxes: (callback) => safeLoop @toDestroyMailboxIDs, (mailboxID, next) => log.debug "removeOrphans - found orphan from box", mailboxID options = {mailboxID, @toDestroyMailboxIDs} removal = new RemoveAllMessagesFromMailbox options removal.run next , (errors) -> log.error "failed to remove message", err for err in errors callback null destroyNoBoxMessages: (callback) -> options = key: ['PI:KEY:<KEY>END_PI'] reduce: false Message.rawRequest 'byMailboxRequest', options, (err, rows) -> return callback err if err safeLoop rows, (row, next) -> Message.destroy row.id, next , (errors) -> log.error 'fail to destroy orphan msg', err for err in errors callback null
[ { "context": "pin/#{trackingNumber}/detail.xml\"\n auth: {user: @username, pass: @password}\n\n\nmodule.exports = {CanadaPostC", "end": 2999, "score": 0.9990960359573364, "start": 2990, "tag": "USERNAME", "value": "@username" }, { "context": "ber}/detail.xml\"\n auth: {user: @u...
src/canada_post.coffee
humm64/ship_new
0
{Parser} = require 'xml2js' {find} = require 'underscore' moment = require 'moment-timezone' {titleCase} = require 'change-case' {ShipperClient} = require './shipper' class CanadaPostClient extends ShipperClient constructor: ({@username, @password}, @options) -> super @parser = new Parser() validateResponse: (response, cb) -> handleResponse = (xmlErr, trackResult) -> return cb(xmlErr) if xmlErr? or !trackResult? details = trackResult['tracking-detail'] return cb('response not recognized') unless details? cb null, details @parser.reset() @parser.parseString response, handleResponse STATUS_MAP = 'in transit': ShipperClient.STATUS_TYPES.EN_ROUTE 'processed': ShipperClient.STATUS_TYPES.EN_ROUTE 'information submitted': ShipperClient.STATUS_TYPES.SHIPPING 'Shipment picked up': ShipperClient.STATUS_TYPES.SHIPPING 'Shipment received': ShipperClient.STATUS_TYPES.EN_ROUTE 'delivered': ShipperClient.STATUS_TYPES.DELIVERED 'out for delivery': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'item released': ShipperClient.STATUS_TYPES.EN_ROUTE 'arrived': ShipperClient.STATUS_TYPES.EN_ROUTE 'departed': ShipperClient.STATUS_TYPES.EN_ROUTE 'is en route': ShipperClient.STATUS_TYPES.EN_ROUTE 'item mailed': ShipperClient.STATUS_TYPES.SHIPPING 'available for pickup': ShipperClient.STATUS_TYPES.DELAYED 'Attempted delivery': ShipperClient.STATUS_TYPES.DELAYED findStatusFromMap: (statusText) -> status = ShipperClient.STATUS_TYPES.UNKNOWN return status unless statusText?.length for text, statusCode of STATUS_MAP regex = new RegExp text, 'i' if regex.test statusText status = statusCode break status getStatus: (lastEvent) -> @findStatusFromMap lastEvent?.details getActivitiesAndStatus: (shipment) -> activities = [] status = null events = shipment['significant-events']?[0]?['occurrence'] for event in events or [] city = event['event-site']?[0] stateCode = event['event-province']?[0] location = @presentLocation({city, stateCode}) timestamp = "#{event['event-date']?[0]}T#{event['event-time']?[0]}Z" timestamp = moment(timestamp).toDate() details = event['event-description']?[0] if details? and timestamp? activity = {timestamp, location, details} activities.push activity activities: activities, status: @getStatus activities?[0] getEta: (shipment) -> ts = shipment['changed-expected-date']?[0] or shipment['expected-delivery-date']?[0] return unless ts?.length moment("#{ts}T00:00:00Z").toDate() if ts?.length getService: (shipment) -> shipment['service-name']?[0] getWeight: (shipment) -> getDestination: (shipment) -> shipment['destination-postal-id']?[0] requestOptions: ({trackingNumber}) -> method: 'GET' uri: "https://soa-gw.canadapost.ca/vis/track/pin/#{trackingNumber}/detail.xml" auth: {user: @username, pass: @password} module.exports = {CanadaPostClient}
183748
{Parser} = require 'xml2js' {find} = require 'underscore' moment = require 'moment-timezone' {titleCase} = require 'change-case' {ShipperClient} = require './shipper' class CanadaPostClient extends ShipperClient constructor: ({@username, @password}, @options) -> super @parser = new Parser() validateResponse: (response, cb) -> handleResponse = (xmlErr, trackResult) -> return cb(xmlErr) if xmlErr? or !trackResult? details = trackResult['tracking-detail'] return cb('response not recognized') unless details? cb null, details @parser.reset() @parser.parseString response, handleResponse STATUS_MAP = 'in transit': ShipperClient.STATUS_TYPES.EN_ROUTE 'processed': ShipperClient.STATUS_TYPES.EN_ROUTE 'information submitted': ShipperClient.STATUS_TYPES.SHIPPING 'Shipment picked up': ShipperClient.STATUS_TYPES.SHIPPING 'Shipment received': ShipperClient.STATUS_TYPES.EN_ROUTE 'delivered': ShipperClient.STATUS_TYPES.DELIVERED 'out for delivery': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'item released': ShipperClient.STATUS_TYPES.EN_ROUTE 'arrived': ShipperClient.STATUS_TYPES.EN_ROUTE 'departed': ShipperClient.STATUS_TYPES.EN_ROUTE 'is en route': ShipperClient.STATUS_TYPES.EN_ROUTE 'item mailed': ShipperClient.STATUS_TYPES.SHIPPING 'available for pickup': ShipperClient.STATUS_TYPES.DELAYED 'Attempted delivery': ShipperClient.STATUS_TYPES.DELAYED findStatusFromMap: (statusText) -> status = ShipperClient.STATUS_TYPES.UNKNOWN return status unless statusText?.length for text, statusCode of STATUS_MAP regex = new RegExp text, 'i' if regex.test statusText status = statusCode break status getStatus: (lastEvent) -> @findStatusFromMap lastEvent?.details getActivitiesAndStatus: (shipment) -> activities = [] status = null events = shipment['significant-events']?[0]?['occurrence'] for event in events or [] city = event['event-site']?[0] stateCode = event['event-province']?[0] location = @presentLocation({city, stateCode}) timestamp = "#{event['event-date']?[0]}T#{event['event-time']?[0]}Z" timestamp = moment(timestamp).toDate() details = event['event-description']?[0] if details? and timestamp? activity = {timestamp, location, details} activities.push activity activities: activities, status: @getStatus activities?[0] getEta: (shipment) -> ts = shipment['changed-expected-date']?[0] or shipment['expected-delivery-date']?[0] return unless ts?.length moment("#{ts}T00:00:00Z").toDate() if ts?.length getService: (shipment) -> shipment['service-name']?[0] getWeight: (shipment) -> getDestination: (shipment) -> shipment['destination-postal-id']?[0] requestOptions: ({trackingNumber}) -> method: 'GET' uri: "https://soa-gw.canadapost.ca/vis/track/pin/#{trackingNumber}/detail.xml" auth: {user: @username, pass: <PASSWORD>} module.exports = {CanadaPostClient}
true
{Parser} = require 'xml2js' {find} = require 'underscore' moment = require 'moment-timezone' {titleCase} = require 'change-case' {ShipperClient} = require './shipper' class CanadaPostClient extends ShipperClient constructor: ({@username, @password}, @options) -> super @parser = new Parser() validateResponse: (response, cb) -> handleResponse = (xmlErr, trackResult) -> return cb(xmlErr) if xmlErr? or !trackResult? details = trackResult['tracking-detail'] return cb('response not recognized') unless details? cb null, details @parser.reset() @parser.parseString response, handleResponse STATUS_MAP = 'in transit': ShipperClient.STATUS_TYPES.EN_ROUTE 'processed': ShipperClient.STATUS_TYPES.EN_ROUTE 'information submitted': ShipperClient.STATUS_TYPES.SHIPPING 'Shipment picked up': ShipperClient.STATUS_TYPES.SHIPPING 'Shipment received': ShipperClient.STATUS_TYPES.EN_ROUTE 'delivered': ShipperClient.STATUS_TYPES.DELIVERED 'out for delivery': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'item released': ShipperClient.STATUS_TYPES.EN_ROUTE 'arrived': ShipperClient.STATUS_TYPES.EN_ROUTE 'departed': ShipperClient.STATUS_TYPES.EN_ROUTE 'is en route': ShipperClient.STATUS_TYPES.EN_ROUTE 'item mailed': ShipperClient.STATUS_TYPES.SHIPPING 'available for pickup': ShipperClient.STATUS_TYPES.DELAYED 'Attempted delivery': ShipperClient.STATUS_TYPES.DELAYED findStatusFromMap: (statusText) -> status = ShipperClient.STATUS_TYPES.UNKNOWN return status unless statusText?.length for text, statusCode of STATUS_MAP regex = new RegExp text, 'i' if regex.test statusText status = statusCode break status getStatus: (lastEvent) -> @findStatusFromMap lastEvent?.details getActivitiesAndStatus: (shipment) -> activities = [] status = null events = shipment['significant-events']?[0]?['occurrence'] for event in events or [] city = event['event-site']?[0] stateCode = event['event-province']?[0] location = @presentLocation({city, stateCode}) timestamp = "#{event['event-date']?[0]}T#{event['event-time']?[0]}Z" timestamp = moment(timestamp).toDate() details = event['event-description']?[0] if details? and timestamp? activity = {timestamp, location, details} activities.push activity activities: activities, status: @getStatus activities?[0] getEta: (shipment) -> ts = shipment['changed-expected-date']?[0] or shipment['expected-delivery-date']?[0] return unless ts?.length moment("#{ts}T00:00:00Z").toDate() if ts?.length getService: (shipment) -> shipment['service-name']?[0] getWeight: (shipment) -> getDestination: (shipment) -> shipment['destination-postal-id']?[0] requestOptions: ({trackingNumber}) -> method: 'GET' uri: "https://soa-gw.canadapost.ca/vis/track/pin/#{trackingNumber}/detail.xml" auth: {user: @username, pass: PI:PASSWORD:<PASSWORD>END_PI} module.exports = {CanadaPostClient}
[ { "context": "lish: {},\n githubRelease:\n repo: \"mar10/grunt-yabs-test\", #// 'owner/repo'\n auth", "end": 1032, "score": 0.9979847073554993, "start": 1027, "tag": "USERNAME", "value": "mar10" }, { "context": "B_OAUTH_TOKEN'},\n # auth: {usernameVa...
Gruntfile.coffee
mar10/grunt-yabs-test
0
### Build scripts for yabs-test ### # jshint directives for the generated JS: ###jshint node: true, unused: false ### "use strict" module.exports = (grunt) -> grunt.initConfig pkg: grunt.file.readJSON("package.json") jshint: all: [ 'Gruntfile.js' 'tasks/*.js' '<%= nodeunit.tests %>' ] options: jshintrc: '.jshintrc' # Before generating any new files, remove any previously-created files. clean: tests: ['tmp'] # Options for the 'yabs' task. yabs: { # options: { # common: { // defaults for all tools # manifests: ['package.json', 'testbower.json'], # }, # }, release: # common: { // defaults for all tools # }, run: {tasks: ['jshint'] } check: { clean: true, branch: ['master'] } bump: {} commit: {} tag: {} push: { tags: true, useFollowTags: false } # npmPublish: {}, githubRelease: repo: "mar10/grunt-yabs-test", #// 'owner/repo' auth: {oauthTokenVar: 'GITHUB_OAUTH_TOKEN'}, # auth: {usernameVar: 'GITHUB_USERNAME', passwordVar: 'GITHUB_PASSWORD'}, # tagName: 'v1.0.0', # targetCommitish: null, //'master', # // name: 'v{%= version %}', # // body: 'Released {%= version %}', draft: false # prerelease: false, bump_develop: inc: 'prepatch' commit_develop: message: 'Bump for prerelease ({%= version %}) [ci skip]' push_develop: {} }, # gr: { # // check: { clean: true, branch: ['master'] }, # bump_develop: { inc: 'zero' }, # githubRelease: { # repo: "mar10/yabs-test", // 'owner/repo' # // auth: {usernameVar: 'GITHUB_USERNAME', passwordVar: 'GITHUB_PASSWORD'}, # // tagName: 'v1.0.0', # // targetCommitish: null, //'master', # // name: 'v{%= version %}', # // body: 'Released {%= version %}', # draft: false, # prerelease: true, # }, # } # }, # Unit tests. nodeunit: tests: ['test/*_test.js'] # Load "grunt*" dependencies for key of grunt.file.readJSON("package.json").devDependencies grunt.loadNpmTasks key if key isnt "grunt" and key.indexOf("grunt") is 0 # Actually load this plugin's task(s). grunt.loadTasks 'tasks'; # Whenever the "test" task is run, first clean the "tmp" dir, then run this # plugin's task(s), then test the result. grunt.registerTask 'test', ['clean', 'yabs', 'nodeunit'] # By default, lint and run all tests. grunt.registerTask "default", ["jshint", "test"] # grunt.registerTask('build', [ # 'yabs:build', # ]); #
181829
### Build scripts for yabs-test ### # jshint directives for the generated JS: ###jshint node: true, unused: false ### "use strict" module.exports = (grunt) -> grunt.initConfig pkg: grunt.file.readJSON("package.json") jshint: all: [ 'Gruntfile.js' 'tasks/*.js' '<%= nodeunit.tests %>' ] options: jshintrc: '.jshintrc' # Before generating any new files, remove any previously-created files. clean: tests: ['tmp'] # Options for the 'yabs' task. yabs: { # options: { # common: { // defaults for all tools # manifests: ['package.json', 'testbower.json'], # }, # }, release: # common: { // defaults for all tools # }, run: {tasks: ['jshint'] } check: { clean: true, branch: ['master'] } bump: {} commit: {} tag: {} push: { tags: true, useFollowTags: false } # npmPublish: {}, githubRelease: repo: "mar10/grunt-yabs-test", #// 'owner/repo' auth: {oauthTokenVar: 'GITHUB_OAUTH_TOKEN'}, # auth: {usernameVar: 'GITHUB_USERNAME', passwordVar: '<PASSWORD>'}, # tagName: 'v1.0.0', # targetCommitish: null, //'master', # // name: 'v{%= version %}', # // body: 'Released {%= version %}', draft: false # prerelease: false, bump_develop: inc: 'prepatch' commit_develop: message: 'Bump for prerelease ({%= version %}) [ci skip]' push_develop: {} }, # gr: { # // check: { clean: true, branch: ['master'] }, # bump_develop: { inc: 'zero' }, # githubRelease: { # repo: "mar10/yabs-test", // 'owner/repo' # // auth: {usernameVar: 'GITHUB_USERNAME', passwordVar: '<PASSWORD>'}, # // tagName: 'v1.0.0', # // targetCommitish: null, //'master', # // name: 'v{%= version %}', # // body: 'Released {%= version %}', # draft: false, # prerelease: true, # }, # } # }, # Unit tests. nodeunit: tests: ['test/*_test.js'] # Load "grunt*" dependencies for key of grunt.file.readJSON("package.json").devDependencies grunt.loadNpmTasks key if key isnt "grunt" and key.indexOf("grunt") is 0 # Actually load this plugin's task(s). grunt.loadTasks 'tasks'; # Whenever the "test" task is run, first clean the "tmp" dir, then run this # plugin's task(s), then test the result. grunt.registerTask 'test', ['clean', 'yabs', 'nodeunit'] # By default, lint and run all tests. grunt.registerTask "default", ["jshint", "test"] # grunt.registerTask('build', [ # 'yabs:build', # ]); #
true
### Build scripts for yabs-test ### # jshint directives for the generated JS: ###jshint node: true, unused: false ### "use strict" module.exports = (grunt) -> grunt.initConfig pkg: grunt.file.readJSON("package.json") jshint: all: [ 'Gruntfile.js' 'tasks/*.js' '<%= nodeunit.tests %>' ] options: jshintrc: '.jshintrc' # Before generating any new files, remove any previously-created files. clean: tests: ['tmp'] # Options for the 'yabs' task. yabs: { # options: { # common: { // defaults for all tools # manifests: ['package.json', 'testbower.json'], # }, # }, release: # common: { // defaults for all tools # }, run: {tasks: ['jshint'] } check: { clean: true, branch: ['master'] } bump: {} commit: {} tag: {} push: { tags: true, useFollowTags: false } # npmPublish: {}, githubRelease: repo: "mar10/grunt-yabs-test", #// 'owner/repo' auth: {oauthTokenVar: 'GITHUB_OAUTH_TOKEN'}, # auth: {usernameVar: 'GITHUB_USERNAME', passwordVar: 'PI:PASSWORD:<PASSWORD>END_PI'}, # tagName: 'v1.0.0', # targetCommitish: null, //'master', # // name: 'v{%= version %}', # // body: 'Released {%= version %}', draft: false # prerelease: false, bump_develop: inc: 'prepatch' commit_develop: message: 'Bump for prerelease ({%= version %}) [ci skip]' push_develop: {} }, # gr: { # // check: { clean: true, branch: ['master'] }, # bump_develop: { inc: 'zero' }, # githubRelease: { # repo: "mar10/yabs-test", // 'owner/repo' # // auth: {usernameVar: 'GITHUB_USERNAME', passwordVar: 'PI:PASSWORD:<PASSWORD>END_PI'}, # // tagName: 'v1.0.0', # // targetCommitish: null, //'master', # // name: 'v{%= version %}', # // body: 'Released {%= version %}', # draft: false, # prerelease: true, # }, # } # }, # Unit tests. nodeunit: tests: ['test/*_test.js'] # Load "grunt*" dependencies for key of grunt.file.readJSON("package.json").devDependencies grunt.loadNpmTasks key if key isnt "grunt" and key.indexOf("grunt") is 0 # Actually load this plugin's task(s). grunt.loadTasks 'tasks'; # Whenever the "test" task is run, first clean the "tmp" dir, then run this # plugin's task(s), then test the result. grunt.registerTask 'test', ['clean', 'yabs', 'nodeunit'] # By default, lint and run all tests. grunt.registerTask "default", ["jshint", "test"] # grunt.registerTask('build', [ # 'yabs:build', # ]); #
[ { "context": "\n (next) ->\n bill = new Person name: 'Bill'\n bill.save next\n ], done\n\n after (don", "end": 1182, "score": 0.9998577237129211, "start": 1178, "tag": "NAME", "value": "Bill" }, { "context": " expectFat (cb) ->\n Person.create name: 'B...
test/mongoose_lean.test.coffee
goodeggs/mongoose-lean
4
mongoose = require 'mongoose' patchMongoose = require '..' patchMongoose(mongoose) async = require 'async' {expect} = require 'chai' schema = new mongoose.Schema name: String Person = mongoose.model 'Person', schema describe 'mongoose-lean', -> {bill} = {} expectFat = (fn, cb) -> async.waterfall [ fn (person, next) -> expect(person).to.be.an.instanceof Person expect(person._id).to.be.an.instanceof mongoose.Types.ObjectId expect(person.id).to.equals person._id.toString() expect(person.name).to.be.a 'string' next() ], cb expectLean = (fn, cb) -> async.waterfall [ fn (person, next) -> expect(person).not.to.be.an.instanceof Person expect(person.save).not.be.defined expect(person._id).to.be.an.instanceof mongoose.Types.ObjectId expect(person.id).to.equals person._id.toString() expect(person.name).to.be.a 'string' next() ], cb before (done) -> async.series [ (next) -> mongoose.connect (process.env.MONGO_URL or 'mongodb://localhost/mongoose_lean-test'), next (next) -> bill = new Person name: 'Bill' bill.save next ], done after (done) -> mongoose.disconnect done describe 'create', -> it 'returns fat models', (done) -> expectFat (cb) -> Person.create name: 'Bob', cb , done describe 'findById', -> it 'returns lean models', (done) -> expectLean (cb) -> Person.findById bill._id, cb , done describe 'findOne', -> it 'returns lean models', (done) -> expectLean (cb) -> Person.findOne _id: bill._id, cb , done describe 'find', -> it 'returns lean models', (done) -> expectLean (cb) -> Person.find _id: bill._id, (err, people) -> cb err, people?[0] , done describe 'exec', -> it 'returns lean models', (done) -> expectLean (cb) -> Person.findOne(_id: bill._id).limit(1).exec cb , done describe 'fat', -> it 'returns fat models'
114244
mongoose = require 'mongoose' patchMongoose = require '..' patchMongoose(mongoose) async = require 'async' {expect} = require 'chai' schema = new mongoose.Schema name: String Person = mongoose.model 'Person', schema describe 'mongoose-lean', -> {bill} = {} expectFat = (fn, cb) -> async.waterfall [ fn (person, next) -> expect(person).to.be.an.instanceof Person expect(person._id).to.be.an.instanceof mongoose.Types.ObjectId expect(person.id).to.equals person._id.toString() expect(person.name).to.be.a 'string' next() ], cb expectLean = (fn, cb) -> async.waterfall [ fn (person, next) -> expect(person).not.to.be.an.instanceof Person expect(person.save).not.be.defined expect(person._id).to.be.an.instanceof mongoose.Types.ObjectId expect(person.id).to.equals person._id.toString() expect(person.name).to.be.a 'string' next() ], cb before (done) -> async.series [ (next) -> mongoose.connect (process.env.MONGO_URL or 'mongodb://localhost/mongoose_lean-test'), next (next) -> bill = new Person name: '<NAME>' bill.save next ], done after (done) -> mongoose.disconnect done describe 'create', -> it 'returns fat models', (done) -> expectFat (cb) -> Person.create name: '<NAME>', cb , done describe 'findById', -> it 'returns lean models', (done) -> expectLean (cb) -> Person.findById bill._id, cb , done describe 'findOne', -> it 'returns lean models', (done) -> expectLean (cb) -> Person.findOne _id: bill._id, cb , done describe 'find', -> it 'returns lean models', (done) -> expectLean (cb) -> Person.find _id: bill._id, (err, people) -> cb err, people?[0] , done describe 'exec', -> it 'returns lean models', (done) -> expectLean (cb) -> Person.findOne(_id: bill._id).limit(1).exec cb , done describe 'fat', -> it 'returns fat models'
true
mongoose = require 'mongoose' patchMongoose = require '..' patchMongoose(mongoose) async = require 'async' {expect} = require 'chai' schema = new mongoose.Schema name: String Person = mongoose.model 'Person', schema describe 'mongoose-lean', -> {bill} = {} expectFat = (fn, cb) -> async.waterfall [ fn (person, next) -> expect(person).to.be.an.instanceof Person expect(person._id).to.be.an.instanceof mongoose.Types.ObjectId expect(person.id).to.equals person._id.toString() expect(person.name).to.be.a 'string' next() ], cb expectLean = (fn, cb) -> async.waterfall [ fn (person, next) -> expect(person).not.to.be.an.instanceof Person expect(person.save).not.be.defined expect(person._id).to.be.an.instanceof mongoose.Types.ObjectId expect(person.id).to.equals person._id.toString() expect(person.name).to.be.a 'string' next() ], cb before (done) -> async.series [ (next) -> mongoose.connect (process.env.MONGO_URL or 'mongodb://localhost/mongoose_lean-test'), next (next) -> bill = new Person name: 'PI:NAME:<NAME>END_PI' bill.save next ], done after (done) -> mongoose.disconnect done describe 'create', -> it 'returns fat models', (done) -> expectFat (cb) -> Person.create name: 'PI:NAME:<NAME>END_PI', cb , done describe 'findById', -> it 'returns lean models', (done) -> expectLean (cb) -> Person.findById bill._id, cb , done describe 'findOne', -> it 'returns lean models', (done) -> expectLean (cb) -> Person.findOne _id: bill._id, cb , done describe 'find', -> it 'returns lean models', (done) -> expectLean (cb) -> Person.find _id: bill._id, (err, people) -> cb err, people?[0] , done describe 'exec', -> it 'returns lean models', (done) -> expectLean (cb) -> Person.findOne(_id: bill._id).limit(1).exec cb , done describe 'fat', -> it 'returns fat models'
[ { "context": " options = \n userName: dbConfig.user\n password: dbConfig.password\n ", "end": 2490, "score": 0.5940790176391602, "start": 2486, "tag": "USERNAME", "value": "user" }, { "context": " userName: dbConfig.user\n password:...
src/cli.coffee
assignittous/knodeo_sql
1
program = require "commander" logger = require("knodeo-logger").Logger pkg = require "./package.json" fs = require "fs" cson = require "cson" config = require('knodeo-configuration').Configuration path = require("path") # db support postgresql = require("./lib/postgresql").postgresql mssql = require("./lib/mssql").mssql sqlite = require("./lib/sqlite").sqlite noOp = ()-> console.log "Nothing ran, couldn't understand your command" writeDataFile = (data, outputPath)-> dataType = path.extname(program.data) switch dataType when ".cson" output = cson.createString(data) else output = JSON.stringify(data, null, 2) fs.writeFileSync outputPath, output, "UTF-8" # this is because fs.existsSync is getting deprecated fileExists = (filePath)-> try # Query the entry stats = fs.lstatSync(filePath) # Is it a directory? if stats.isDirectory() # Yes it is return false else return true catch e return false # version program .version(pkg.version, "-v, --version") .option("-s, --sql <sqlfile>", "SQL File") .option("-d, --database <database>", "Database") .option("-o, --output <outputfile>", "Output file") # todo, not implemented yet .option("-r, --root <attribute>", "Attribute") .option("-f, --first", "First record only") .parse(process.argv) if program.sql? && program.database? && program.output? # Validate config configFile = 'config.sql.cson' if fileExists(configFile) config.load 'config.sql.cson' else logger.error 'config.sql.cson could not be found in the current working directory' return # Check sql file if fileExists(program.sql) sql = fs.readFileSync(program.sql,'utf8') else logger.error "SQL file does not exist" return if program.database if config.current.databases[program.database]? console.log "database: #{program.database} OK" dbConfig = config.current.databases[program.database] console.log "Root: #{program.root}" console.log "First: #{program.first}" callback = (data)-> logger.info "Writing to #{program.output}" if program.first? data = data[0] if program.root? root = {} root[program.root] = data data = root writeDataFile data, program.output switch dbConfig.type when "mssql" logger.info "MSSQL Database" options = userName: dbConfig.user password: dbConfig.password server: dbConfig.host options: port: dbConfig.port database: program.database rowCollectionOnDone: true mssql.execute sql, options, callback when "postgresql" options = dbConfig options.database = program.database logger.info "Postgresql Database" postgresql.execute sql, options, callback when "sqlite" options = dbConfig logger.info "Sqlite Database" sqlite.execute sql, options, callback else logger.error "Database type #{dbConfig.type} is not supported" return else logger.error "Database #{program.database} is not specified in config.sql.cson" return else logger.error "sql (-s), database (-d) and output (-o) parameters are required."
135993
program = require "commander" logger = require("knodeo-logger").Logger pkg = require "./package.json" fs = require "fs" cson = require "cson" config = require('knodeo-configuration').Configuration path = require("path") # db support postgresql = require("./lib/postgresql").postgresql mssql = require("./lib/mssql").mssql sqlite = require("./lib/sqlite").sqlite noOp = ()-> console.log "Nothing ran, couldn't understand your command" writeDataFile = (data, outputPath)-> dataType = path.extname(program.data) switch dataType when ".cson" output = cson.createString(data) else output = JSON.stringify(data, null, 2) fs.writeFileSync outputPath, output, "UTF-8" # this is because fs.existsSync is getting deprecated fileExists = (filePath)-> try # Query the entry stats = fs.lstatSync(filePath) # Is it a directory? if stats.isDirectory() # Yes it is return false else return true catch e return false # version program .version(pkg.version, "-v, --version") .option("-s, --sql <sqlfile>", "SQL File") .option("-d, --database <database>", "Database") .option("-o, --output <outputfile>", "Output file") # todo, not implemented yet .option("-r, --root <attribute>", "Attribute") .option("-f, --first", "First record only") .parse(process.argv) if program.sql? && program.database? && program.output? # Validate config configFile = 'config.sql.cson' if fileExists(configFile) config.load 'config.sql.cson' else logger.error 'config.sql.cson could not be found in the current working directory' return # Check sql file if fileExists(program.sql) sql = fs.readFileSync(program.sql,'utf8') else logger.error "SQL file does not exist" return if program.database if config.current.databases[program.database]? console.log "database: #{program.database} OK" dbConfig = config.current.databases[program.database] console.log "Root: #{program.root}" console.log "First: #{program.first}" callback = (data)-> logger.info "Writing to #{program.output}" if program.first? data = data[0] if program.root? root = {} root[program.root] = data data = root writeDataFile data, program.output switch dbConfig.type when "mssql" logger.info "MSSQL Database" options = userName: dbConfig.user password: <PASSWORD> server: dbConfig.host options: port: dbConfig.port database: program.database rowCollectionOnDone: true mssql.execute sql, options, callback when "postgresql" options = dbConfig options.database = program.database logger.info "Postgresql Database" postgresql.execute sql, options, callback when "sqlite" options = dbConfig logger.info "Sqlite Database" sqlite.execute sql, options, callback else logger.error "Database type #{dbConfig.type} is not supported" return else logger.error "Database #{program.database} is not specified in config.sql.cson" return else logger.error "sql (-s), database (-d) and output (-o) parameters are required."
true
program = require "commander" logger = require("knodeo-logger").Logger pkg = require "./package.json" fs = require "fs" cson = require "cson" config = require('knodeo-configuration').Configuration path = require("path") # db support postgresql = require("./lib/postgresql").postgresql mssql = require("./lib/mssql").mssql sqlite = require("./lib/sqlite").sqlite noOp = ()-> console.log "Nothing ran, couldn't understand your command" writeDataFile = (data, outputPath)-> dataType = path.extname(program.data) switch dataType when ".cson" output = cson.createString(data) else output = JSON.stringify(data, null, 2) fs.writeFileSync outputPath, output, "UTF-8" # this is because fs.existsSync is getting deprecated fileExists = (filePath)-> try # Query the entry stats = fs.lstatSync(filePath) # Is it a directory? if stats.isDirectory() # Yes it is return false else return true catch e return false # version program .version(pkg.version, "-v, --version") .option("-s, --sql <sqlfile>", "SQL File") .option("-d, --database <database>", "Database") .option("-o, --output <outputfile>", "Output file") # todo, not implemented yet .option("-r, --root <attribute>", "Attribute") .option("-f, --first", "First record only") .parse(process.argv) if program.sql? && program.database? && program.output? # Validate config configFile = 'config.sql.cson' if fileExists(configFile) config.load 'config.sql.cson' else logger.error 'config.sql.cson could not be found in the current working directory' return # Check sql file if fileExists(program.sql) sql = fs.readFileSync(program.sql,'utf8') else logger.error "SQL file does not exist" return if program.database if config.current.databases[program.database]? console.log "database: #{program.database} OK" dbConfig = config.current.databases[program.database] console.log "Root: #{program.root}" console.log "First: #{program.first}" callback = (data)-> logger.info "Writing to #{program.output}" if program.first? data = data[0] if program.root? root = {} root[program.root] = data data = root writeDataFile data, program.output switch dbConfig.type when "mssql" logger.info "MSSQL Database" options = userName: dbConfig.user password: PI:PASSWORD:<PASSWORD>END_PI server: dbConfig.host options: port: dbConfig.port database: program.database rowCollectionOnDone: true mssql.execute sql, options, callback when "postgresql" options = dbConfig options.database = program.database logger.info "Postgresql Database" postgresql.execute sql, options, callback when "sqlite" options = dbConfig logger.info "Sqlite Database" sqlite.execute sql, options, callback else logger.error "Database type #{dbConfig.type} is not supported" return else logger.error "Database #{program.database} is not specified in config.sql.cson" return else logger.error "sql (-s), database (-d) and output (-o) parameters are required."
[ { "context": " q: name\n api_key: \"n3ppab9xdhpnq5udzn3f7wxt\"\n .success (data) ->\n m", "end": 858, "score": 0.9997032284736633, "start": 834, "tag": "KEY", "value": "n3ppab9xdhpnq5udzn3f7wxt" } ]
app/scripts/providers/rotten.coffee
dackmin/Gummy
3
'use strict' ###* # @ngdoc function # @name gummyApp.provider:$rotten # @description # # $trakt # Rotten Tomatoes API provider ### angular .module 'gummyApp' .service '$rotten', ($http, $q) -> ###* # Api method # @attribute API_METHOD ### @API_METHOD = "http://" ###* # Api root url # @attribute API_ROOT ### @API_ROOT = "api.rottentomatoes.com/api/public/v1.0" ###* # Find a movie # @method search # @param {String} name - Movie name ### @search = (name) -> q = $q.defer() $http method: "GET" url: "#{@API_METHOD}#{@API_ROOT}/movies.json" params: q: name api_key: "n3ppab9xdhpnq5udzn3f7wxt" .success (data) -> movies = [] movies.push @toSimpleJSON(obj) for obj in data.movies q.resolve movies .error (e) -> q.reject e q.promise ###* # Get movie infos # @method get # @param {String|int} id - Movie id/slug # @param {Object} infos - Additional infos # @return {Object} - $q promise ### @get = (id, infos) -> infos.cast = @cast infos.raw.abridged_cast @toJSON infos.raw ###* # Get cast members # @method cast # @param {String|int} id - Movie slug/id # @return {Object} - $q promise ### @cast = (raw) -> cast = [] cast.push person.name for person in raw cast ###* # Return movie as simple json object # @method toSimpleJSON # @param {Object} raw - Raw data from movie # @return {Object} - simply parsed json object ### @toSimpleJSON = (raw) -> id: raw.id rating: raw.ratings.audience_score title: raw.title synopsis: raw.synopsis year: raw.year cover: small: raw.posters.thumbnail medium: raw.posters.detailed large: raw.posters.original background: small: "" medium: "" large: "" raw: raw ###* # Return movie as a normal json object # @method toJSON # @param {Object} raw - Raw movie data # @return {Object} - parsed json object ### @toJSON = (raw) -> id: raw.id rating: raw.ratings.audience_score title: raw.title synopsis: raw.synopsis year: raw.year cast: raw.cast cover: small: raw.posters.thumbnail medium: raw.posters.detailed large: raw.posters.original background: small: "" medium: "" large: "" ###* # Generate an empty object when movie is not recognized # @method toEmpty # @param {String} filename - Sanitized filename (the.best.movie.ever.720p.HDTV.mkv becomes "The best movie ever") # @param {String} path - original filepath # @return {Object} ### @toEmpty = (filename, path) -> id: "" rating: 0 title: filename path: path synopsis: "" year: (new Date()).getFullYear() cover: small: "" medium: "" large: "" background: small: "" medium: "" large: "" raw: {} @
114091
'use strict' ###* # @ngdoc function # @name gummyApp.provider:$rotten # @description # # $trakt # Rotten Tomatoes API provider ### angular .module 'gummyApp' .service '$rotten', ($http, $q) -> ###* # Api method # @attribute API_METHOD ### @API_METHOD = "http://" ###* # Api root url # @attribute API_ROOT ### @API_ROOT = "api.rottentomatoes.com/api/public/v1.0" ###* # Find a movie # @method search # @param {String} name - Movie name ### @search = (name) -> q = $q.defer() $http method: "GET" url: "#{@API_METHOD}#{@API_ROOT}/movies.json" params: q: name api_key: "<KEY>" .success (data) -> movies = [] movies.push @toSimpleJSON(obj) for obj in data.movies q.resolve movies .error (e) -> q.reject e q.promise ###* # Get movie infos # @method get # @param {String|int} id - Movie id/slug # @param {Object} infos - Additional infos # @return {Object} - $q promise ### @get = (id, infos) -> infos.cast = @cast infos.raw.abridged_cast @toJSON infos.raw ###* # Get cast members # @method cast # @param {String|int} id - Movie slug/id # @return {Object} - $q promise ### @cast = (raw) -> cast = [] cast.push person.name for person in raw cast ###* # Return movie as simple json object # @method toSimpleJSON # @param {Object} raw - Raw data from movie # @return {Object} - simply parsed json object ### @toSimpleJSON = (raw) -> id: raw.id rating: raw.ratings.audience_score title: raw.title synopsis: raw.synopsis year: raw.year cover: small: raw.posters.thumbnail medium: raw.posters.detailed large: raw.posters.original background: small: "" medium: "" large: "" raw: raw ###* # Return movie as a normal json object # @method toJSON # @param {Object} raw - Raw movie data # @return {Object} - parsed json object ### @toJSON = (raw) -> id: raw.id rating: raw.ratings.audience_score title: raw.title synopsis: raw.synopsis year: raw.year cast: raw.cast cover: small: raw.posters.thumbnail medium: raw.posters.detailed large: raw.posters.original background: small: "" medium: "" large: "" ###* # Generate an empty object when movie is not recognized # @method toEmpty # @param {String} filename - Sanitized filename (the.best.movie.ever.720p.HDTV.mkv becomes "The best movie ever") # @param {String} path - original filepath # @return {Object} ### @toEmpty = (filename, path) -> id: "" rating: 0 title: filename path: path synopsis: "" year: (new Date()).getFullYear() cover: small: "" medium: "" large: "" background: small: "" medium: "" large: "" raw: {} @
true
'use strict' ###* # @ngdoc function # @name gummyApp.provider:$rotten # @description # # $trakt # Rotten Tomatoes API provider ### angular .module 'gummyApp' .service '$rotten', ($http, $q) -> ###* # Api method # @attribute API_METHOD ### @API_METHOD = "http://" ###* # Api root url # @attribute API_ROOT ### @API_ROOT = "api.rottentomatoes.com/api/public/v1.0" ###* # Find a movie # @method search # @param {String} name - Movie name ### @search = (name) -> q = $q.defer() $http method: "GET" url: "#{@API_METHOD}#{@API_ROOT}/movies.json" params: q: name api_key: "PI:KEY:<KEY>END_PI" .success (data) -> movies = [] movies.push @toSimpleJSON(obj) for obj in data.movies q.resolve movies .error (e) -> q.reject e q.promise ###* # Get movie infos # @method get # @param {String|int} id - Movie id/slug # @param {Object} infos - Additional infos # @return {Object} - $q promise ### @get = (id, infos) -> infos.cast = @cast infos.raw.abridged_cast @toJSON infos.raw ###* # Get cast members # @method cast # @param {String|int} id - Movie slug/id # @return {Object} - $q promise ### @cast = (raw) -> cast = [] cast.push person.name for person in raw cast ###* # Return movie as simple json object # @method toSimpleJSON # @param {Object} raw - Raw data from movie # @return {Object} - simply parsed json object ### @toSimpleJSON = (raw) -> id: raw.id rating: raw.ratings.audience_score title: raw.title synopsis: raw.synopsis year: raw.year cover: small: raw.posters.thumbnail medium: raw.posters.detailed large: raw.posters.original background: small: "" medium: "" large: "" raw: raw ###* # Return movie as a normal json object # @method toJSON # @param {Object} raw - Raw movie data # @return {Object} - parsed json object ### @toJSON = (raw) -> id: raw.id rating: raw.ratings.audience_score title: raw.title synopsis: raw.synopsis year: raw.year cast: raw.cast cover: small: raw.posters.thumbnail medium: raw.posters.detailed large: raw.posters.original background: small: "" medium: "" large: "" ###* # Generate an empty object when movie is not recognized # @method toEmpty # @param {String} filename - Sanitized filename (the.best.movie.ever.720p.HDTV.mkv becomes "The best movie ever") # @param {String} path - original filepath # @return {Object} ### @toEmpty = (filename, path) -> id: "" rating: 0 title: filename path: path synopsis: "" year: (new Date()).getFullYear() cover: small: "" medium: "" large: "" background: small: "" medium: "" large: "" raw: {} @
[ { "context": "cs/#info.info\n\nFramer.Info =\n\ttitle: \"\"\n\tauthor: \"Tony\"\n\ttwitter: \"\"\n\tdescription: \"\"\n\n\n# Kevyn Arnott: ", "end": 146, "score": 0.9998199939727783, "start": 142, "tag": "NAME", "value": "Tony" }, { "context": "\n\tauthor: \"Tony\"\n\ttwitter: \"\"\n...
64backButton.framer/app.coffee
gremjua-forks/100daysofframer
26
# Project Info # This info is presented in a widget when you share. # http://framerjs.com/docs/#info.info Framer.Info = title: "" author: "Tony" twitter: "" description: "" # Kevyn Arnott: "You can use window.location.hash to do your state management. Then you move through the prototype manipulating the URL and relying on a state management function. Then just listen to the back button to call the state manager. Here's a quick example -> http://share.framerjs.com/7o9i6rthv7aa/" msg1 = "First Page<br>Click anywhere to view the next page." msg2 = "Second Page<br>Click to view the last page." msg3 = "Third Page<br>Click the browser back button go back." layerStyle = fontFamily: "monospace", textAlign: "center" fontSize: "1.2rem", lineHeight: "10rem" fadeIn = time: 0.3 first = new Layer html: msg1, opacity: 0 backgroundColor: "black" size: Screen, style: layerStyle first.states.add on: opacity: 1 first.states.animationOptions = fadeIn second = new Layer html: msg2, opacity: 0 backgroundColor: "maroon" size: Screen, style: layerStyle second.states.add on: opacity: 1 second.states.animationOptions = fadeIn third = new Layer html: msg3, opacity: 0 backgroundColor: "indigo" size: Screen, style: layerStyle third.states.add on: opacity: 1 third.states.animationOptions = fadeIn first.bringToFront() state = (hash) -> window.location.hash = hash #These are the different states you'd switch between switch hash when "#third" third.states.switch("on") second.states.switch("default") when "#second" second.bringToFront() third.states.switch("default") first.states.switch("default") second.states.switch("on") else first.bringToFront() second.states.switch("default") first.states.switch("on") #Start with your initial state state("") # You can move through the states using the state function first.on Events.TouchEnd, -> state("#second") second.on Events.TouchEnd, -> state("#third") #You won't need to change these. They listen to the back button & go to the previous state. goBack = () -> state(window.location.hash) window.onpopstate = goBack
150397
# Project Info # This info is presented in a widget when you share. # http://framerjs.com/docs/#info.info Framer.Info = title: "" author: "<NAME>" twitter: "" description: "" # <NAME>: "You can use window.location.hash to do your state management. Then you move through the prototype manipulating the URL and relying on a state management function. Then just listen to the back button to call the state manager. Here's a quick example -> http://share.framerjs.com/7o9i6rthv7aa/" msg1 = "First Page<br>Click anywhere to view the next page." msg2 = "Second Page<br>Click to view the last page." msg3 = "Third Page<br>Click the browser back button go back." layerStyle = fontFamily: "monospace", textAlign: "center" fontSize: "1.2rem", lineHeight: "10rem" fadeIn = time: 0.3 first = new Layer html: msg1, opacity: 0 backgroundColor: "black" size: Screen, style: layerStyle first.states.add on: opacity: 1 first.states.animationOptions = fadeIn second = new Layer html: msg2, opacity: 0 backgroundColor: "maroon" size: Screen, style: layerStyle second.states.add on: opacity: 1 second.states.animationOptions = fadeIn third = new Layer html: msg3, opacity: 0 backgroundColor: "indigo" size: Screen, style: layerStyle third.states.add on: opacity: 1 third.states.animationOptions = fadeIn first.bringToFront() state = (hash) -> window.location.hash = hash #These are the different states you'd switch between switch hash when "#third" third.states.switch("on") second.states.switch("default") when "#second" second.bringToFront() third.states.switch("default") first.states.switch("default") second.states.switch("on") else first.bringToFront() second.states.switch("default") first.states.switch("on") #Start with your initial state state("") # You can move through the states using the state function first.on Events.TouchEnd, -> state("#second") second.on Events.TouchEnd, -> state("#third") #You won't need to change these. They listen to the back button & go to the previous state. goBack = () -> state(window.location.hash) window.onpopstate = goBack
true
# Project Info # This info is presented in a widget when you share. # http://framerjs.com/docs/#info.info Framer.Info = title: "" author: "PI:NAME:<NAME>END_PI" twitter: "" description: "" # PI:NAME:<NAME>END_PI: "You can use window.location.hash to do your state management. Then you move through the prototype manipulating the URL and relying on a state management function. Then just listen to the back button to call the state manager. Here's a quick example -> http://share.framerjs.com/7o9i6rthv7aa/" msg1 = "First Page<br>Click anywhere to view the next page." msg2 = "Second Page<br>Click to view the last page." msg3 = "Third Page<br>Click the browser back button go back." layerStyle = fontFamily: "monospace", textAlign: "center" fontSize: "1.2rem", lineHeight: "10rem" fadeIn = time: 0.3 first = new Layer html: msg1, opacity: 0 backgroundColor: "black" size: Screen, style: layerStyle first.states.add on: opacity: 1 first.states.animationOptions = fadeIn second = new Layer html: msg2, opacity: 0 backgroundColor: "maroon" size: Screen, style: layerStyle second.states.add on: opacity: 1 second.states.animationOptions = fadeIn third = new Layer html: msg3, opacity: 0 backgroundColor: "indigo" size: Screen, style: layerStyle third.states.add on: opacity: 1 third.states.animationOptions = fadeIn first.bringToFront() state = (hash) -> window.location.hash = hash #These are the different states you'd switch between switch hash when "#third" third.states.switch("on") second.states.switch("default") when "#second" second.bringToFront() third.states.switch("default") first.states.switch("default") second.states.switch("on") else first.bringToFront() second.states.switch("default") first.states.switch("on") #Start with your initial state state("") # You can move through the states using the state function first.on Events.TouchEnd, -> state("#second") second.on Events.TouchEnd, -> state("#third") #You won't need to change these. They listen to the back button & go to the previous state. goBack = () -> state(window.location.hash) window.onpopstate = goBack
[ { "context": "# Bing photo background created by Sam Roach 1/21/2016\n# Unsplash photo background added by Mi", "end": 44, "score": 0.9998545050621033, "start": 35, "tag": "NAME", "value": "Sam Roach" }, { "context": "ach 1/21/2016\n# Unsplash photo background added by Michael Fleet ...
ubersicht/widgets/background.widget/unsplash-background.coffee
f1337/macos-dev-box
4
# Bing photo background created by Sam Roach 1/21/2016 # Unsplash photo background added by Michael Fleet 3/3/2020 # api key accessKey = "" # time of day hour = new Date().getHours() if (hour > 5 && hour < 12) time_query = 'morning' else if (hour > 11 && hour < 20) time_query = 'day' else time_query = 'night' # https://unsplash.com/documentation#get-a-random-photo query = "beach,ocean,nature,#{time_query}" # search terms collections = "" # Public collection ID(‘s) to filter selection. If multiple, comma-separated # Filter search results by photo orientation. Valid values are landscape, portrait, and squarish. orientation = "landscape" command: """ curl -H 'Authorization: Client-ID #{accessKey}' -s 'https://api.unsplash.com/photos/random?query=#{query}&orientation=#{orientation}&collections=#{collections}' """ # Set the refresh frequency. refreshFrequency: '1h' style: """ position: absolute; margin: 0 top: 0 left: 0 color: #fff .wallpaper position: absolute z-index: -10000 width: 100% .background width: 100% position: absolute z-index: -10000 .myimage position: absolute z-index: -10000 object-fit: cover height: 100vh """ render: -> """ <div id='background'></div> """ # Update the rendered output. update: (output, domEl) -> if (output == '') return data = JSON.parse(output) size = "width: " + window.screen.availWidth + "px;" url = data.urls.regular if (url) mydiv = $(domEl).find('#background') html = '' html += '<div class="wallpaper"> ' html += '<img src="' + url + '" class="myimage" style="' + size + '">' html += '</div>' # Set the output mydiv.html(html)
224501
# Bing photo background created by <NAME> 1/21/2016 # Unsplash photo background added by <NAME> 3/3/2020 # api key accessKey = "" # time of day hour = new Date().getHours() if (hour > 5 && hour < 12) time_query = 'morning' else if (hour > 11 && hour < 20) time_query = 'day' else time_query = 'night' # https://unsplash.com/documentation#get-a-random-photo query = "beach,ocean,nature,#{time_query}" # search terms collections = "" # Public collection ID(‘s) to filter selection. If multiple, comma-separated # Filter search results by photo orientation. Valid values are landscape, portrait, and squarish. orientation = "landscape" command: """ curl -H 'Authorization: Client-ID #{accessKey}' -s 'https://api.unsplash.com/photos/random?query=#{query}&orientation=#{orientation}&collections=#{collections}' """ # Set the refresh frequency. refreshFrequency: '1h' style: """ position: absolute; margin: 0 top: 0 left: 0 color: #fff .wallpaper position: absolute z-index: -10000 width: 100% .background width: 100% position: absolute z-index: -10000 .myimage position: absolute z-index: -10000 object-fit: cover height: 100vh """ render: -> """ <div id='background'></div> """ # Update the rendered output. update: (output, domEl) -> if (output == '') return data = JSON.parse(output) size = "width: " + window.screen.availWidth + "px;" url = data.urls.regular if (url) mydiv = $(domEl).find('#background') html = '' html += '<div class="wallpaper"> ' html += '<img src="' + url + '" class="myimage" style="' + size + '">' html += '</div>' # Set the output mydiv.html(html)
true
# Bing photo background created by PI:NAME:<NAME>END_PI 1/21/2016 # Unsplash photo background added by PI:NAME:<NAME>END_PI 3/3/2020 # api key accessKey = "" # time of day hour = new Date().getHours() if (hour > 5 && hour < 12) time_query = 'morning' else if (hour > 11 && hour < 20) time_query = 'day' else time_query = 'night' # https://unsplash.com/documentation#get-a-random-photo query = "beach,ocean,nature,#{time_query}" # search terms collections = "" # Public collection ID(‘s) to filter selection. If multiple, comma-separated # Filter search results by photo orientation. Valid values are landscape, portrait, and squarish. orientation = "landscape" command: """ curl -H 'Authorization: Client-ID #{accessKey}' -s 'https://api.unsplash.com/photos/random?query=#{query}&orientation=#{orientation}&collections=#{collections}' """ # Set the refresh frequency. refreshFrequency: '1h' style: """ position: absolute; margin: 0 top: 0 left: 0 color: #fff .wallpaper position: absolute z-index: -10000 width: 100% .background width: 100% position: absolute z-index: -10000 .myimage position: absolute z-index: -10000 object-fit: cover height: 100vh """ render: -> """ <div id='background'></div> """ # Update the rendered output. update: (output, domEl) -> if (output == '') return data = JSON.parse(output) size = "width: " + window.screen.availWidth + "px;" url = data.urls.regular if (url) mydiv = $(domEl).find('#background') html = '' html += '<div class="wallpaper"> ' html += '<img src="' + url + '" class="myimage" style="' + size + '">' html += '</div>' # Set the output mydiv.html(html)
[ { "context": "Each ->\n co =>\n yield @room.user.say 'alice', '@hubot hi'\n yield @room.user.say 'bob',", "end": 368, "score": 0.8009129166603088, "start": 363, "tag": "NAME", "value": "alice" }, { "context": " co =>\n yield @room.user.say 'alice', '@hubot h...
test/hello-world_test.coffee
Davlis/hubot-test-helper
111
Helper = require('../src/index') helper = new Helper('./scripts/hello-world.coffee') co = require('co') expect = require('chai').expect describe 'hello-world', -> beforeEach -> @room = helper.createRoom(httpd: false) afterEach -> @room.destroy() context 'user says hi to hubot', -> beforeEach -> co => yield @room.user.say 'alice', '@hubot hi' yield @room.user.say 'bob', '@hubot hi' it 'should reply to user', -> expect(@room.messages).to.eql [ ['alice', '@hubot hi'] ['hubot', '@alice hi'] ['bob', '@hubot hi'] ['hubot', '@bob hi'] ]
211412
Helper = require('../src/index') helper = new Helper('./scripts/hello-world.coffee') co = require('co') expect = require('chai').expect describe 'hello-world', -> beforeEach -> @room = helper.createRoom(httpd: false) afterEach -> @room.destroy() context 'user says hi to hubot', -> beforeEach -> co => yield @room.user.say '<NAME>', '@hubot hi' yield @room.user.say '<NAME>', '@hubot hi' it 'should reply to user', -> expect(@room.messages).to.eql [ ['alice', '@hubot hi'] ['hubot', '@alice hi'] ['bob', '@hubot hi'] ['hubot', '@bob hi'] ]
true
Helper = require('../src/index') helper = new Helper('./scripts/hello-world.coffee') co = require('co') expect = require('chai').expect describe 'hello-world', -> beforeEach -> @room = helper.createRoom(httpd: false) afterEach -> @room.destroy() context 'user says hi to hubot', -> beforeEach -> co => yield @room.user.say 'PI:NAME:<NAME>END_PI', '@hubot hi' yield @room.user.say 'PI:NAME:<NAME>END_PI', '@hubot hi' it 'should reply to user', -> expect(@room.messages).to.eql [ ['alice', '@hubot hi'] ['hubot', '@alice hi'] ['bob', '@hubot hi'] ['hubot', '@bob hi'] ]
[ { "context": "embedded: {\n tests: [\n { id: 'foorbar', name: 'Foobar' }\n ]\n }\n }\n", "end": 1256, "score": 0.9729177951812744, "start": 1249, "tag": "USERNAME", "value": "foorbar" }, { "context": " tests: [\n { id: 'foorbar'...
src/desktop/components/inquiry_questionnaire/test/views/affliated.test.coffee
jo-rs/force
0
benv = require 'benv' sinon = require 'sinon' rewire = require 'rewire' Backbone = require 'backbone' { setup } = require './setup' Affiliated = null ResultsView = null TypeaheadView = null ResultsListView = null describe 'Affiliated', setup -> beforeEach -> $.fn.typeahead = -> this benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') window.jQuery = $ Affiliated = benv.requireWithJadeify require.resolve('../../views/affiliated'), ['template'] ResultsView = benv.requireWithJadeify require.resolve('../../../results_list/views/results'), ['template'] TypeaheadView = benv.requireWithJadeify require.resolve('../../../typeahead/view'), ['templates.index'] ResultsListView = rewire '../../../results_list/view' ResultsListView.__set__ 'ResultsView', ResultsView Affiliated.__set__ 'TypeaheadView', TypeaheadView Affiliated.__set__ 'ResultsListView', ResultsListView class TestAffiliated extends Affiliated title: 'This is only a test.' collectorProfileAttribute: 'affiliated_test_ids' galaxyPath: '_embedded.tests' galaxyEndpoint: 'tests' sinon.stub $, 'ajax' .yieldsTo 'success', { _embedded: { tests: [ { id: 'foorbar', name: 'Foobar' } ] } } @currentUser.related() .collectorProfile.set 'affiliated_test_ids', ['foobar'] @artwork.related() .partner.set 'pre_qualify', false @view = new TestAffiliated user: @currentUser, artwork: @artwork, state: @state afterEach -> $.ajax.restore() describe '#setup', -> it 'fetches the affiliated thing through Galaxy', -> fetch = $.ajax.args[0][0] fetch.headers .should.eql Accept: 'application/vnd.galaxy-public+json' fetch.url .should.containEql '/tests?token=' fetch.data .should.eql ids: ['foobar'] describe '#render', -> beforeEach -> @view.render() it 'renders the template', -> @view.$('.iq-headline').text() .should.equal 'This is only a test.(Optional)' @view.$('.results-list-item') .should.have.lengthOf 1 @view.$('.results-list-item').text() .should.equal 'Foobar'
9844
benv = require 'benv' sinon = require 'sinon' rewire = require 'rewire' Backbone = require 'backbone' { setup } = require './setup' Affiliated = null ResultsView = null TypeaheadView = null ResultsListView = null describe 'Affiliated', setup -> beforeEach -> $.fn.typeahead = -> this benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') window.jQuery = $ Affiliated = benv.requireWithJadeify require.resolve('../../views/affiliated'), ['template'] ResultsView = benv.requireWithJadeify require.resolve('../../../results_list/views/results'), ['template'] TypeaheadView = benv.requireWithJadeify require.resolve('../../../typeahead/view'), ['templates.index'] ResultsListView = rewire '../../../results_list/view' ResultsListView.__set__ 'ResultsView', ResultsView Affiliated.__set__ 'TypeaheadView', TypeaheadView Affiliated.__set__ 'ResultsListView', ResultsListView class TestAffiliated extends Affiliated title: 'This is only a test.' collectorProfileAttribute: 'affiliated_test_ids' galaxyPath: '_embedded.tests' galaxyEndpoint: 'tests' sinon.stub $, 'ajax' .yieldsTo 'success', { _embedded: { tests: [ { id: 'foorbar', name: '<NAME>' } ] } } @currentUser.related() .collectorProfile.set 'affiliated_test_ids', ['foobar'] @artwork.related() .partner.set 'pre_qualify', false @view = new TestAffiliated user: @currentUser, artwork: @artwork, state: @state afterEach -> $.ajax.restore() describe '#setup', -> it 'fetches the affiliated thing through Galaxy', -> fetch = $.ajax.args[0][0] fetch.headers .should.eql Accept: 'application/vnd.galaxy-public+json' fetch.url .should.containEql '/tests?token=' fetch.data .should.eql ids: ['foobar'] describe '#render', -> beforeEach -> @view.render() it 'renders the template', -> @view.$('.iq-headline').text() .should.equal 'This is only a test.(Optional)' @view.$('.results-list-item') .should.have.lengthOf 1 @view.$('.results-list-item').text() .should.equal 'Foobar'
true
benv = require 'benv' sinon = require 'sinon' rewire = require 'rewire' Backbone = require 'backbone' { setup } = require './setup' Affiliated = null ResultsView = null TypeaheadView = null ResultsListView = null describe 'Affiliated', setup -> beforeEach -> $.fn.typeahead = -> this benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') window.jQuery = $ Affiliated = benv.requireWithJadeify require.resolve('../../views/affiliated'), ['template'] ResultsView = benv.requireWithJadeify require.resolve('../../../results_list/views/results'), ['template'] TypeaheadView = benv.requireWithJadeify require.resolve('../../../typeahead/view'), ['templates.index'] ResultsListView = rewire '../../../results_list/view' ResultsListView.__set__ 'ResultsView', ResultsView Affiliated.__set__ 'TypeaheadView', TypeaheadView Affiliated.__set__ 'ResultsListView', ResultsListView class TestAffiliated extends Affiliated title: 'This is only a test.' collectorProfileAttribute: 'affiliated_test_ids' galaxyPath: '_embedded.tests' galaxyEndpoint: 'tests' sinon.stub $, 'ajax' .yieldsTo 'success', { _embedded: { tests: [ { id: 'foorbar', name: 'PI:NAME:<NAME>END_PI' } ] } } @currentUser.related() .collectorProfile.set 'affiliated_test_ids', ['foobar'] @artwork.related() .partner.set 'pre_qualify', false @view = new TestAffiliated user: @currentUser, artwork: @artwork, state: @state afterEach -> $.ajax.restore() describe '#setup', -> it 'fetches the affiliated thing through Galaxy', -> fetch = $.ajax.args[0][0] fetch.headers .should.eql Accept: 'application/vnd.galaxy-public+json' fetch.url .should.containEql '/tests?token=' fetch.data .should.eql ids: ['foobar'] describe '#render', -> beforeEach -> @view.render() it 'renders the template', -> @view.$('.iq-headline').text() .should.equal 'This is only a test.(Optional)' @view.$('.results-list-item') .should.have.lengthOf 1 @view.$('.results-list-item').text() .should.equal 'Foobar'
[ { "context": " base_url: \"http://localhost:3052\"\n user_name: \"admin\"\n password: \"admin\"\n}\n\nstatus = new PowerPanelSt", "end": 220, "score": 0.994982123374939, "start": 215, "tag": "USERNAME", "value": "admin" }, { "context": "localhost:3052\"\n user_name: \"admin\"\n ...
src/test.coffee
braintapper/cyberpower-powerpanel-status
2
PowerPanelStatus = require "./index.js" # If you have PowerPanel Business 4.x installed, test would be the default # connection URL and credentials. options = { base_url: "http://localhost:3052" user_name: "admin" password: "admin" } status = new PowerPanelStatus options scb = (response)-> console.log "Success!" console.log response ecb = (err)-> console.error "Error!" console.log err status.fetch scb, ecb
51149
PowerPanelStatus = require "./index.js" # If you have PowerPanel Business 4.x installed, test would be the default # connection URL and credentials. options = { base_url: "http://localhost:3052" user_name: "admin" password: "<PASSWORD>" } status = new PowerPanelStatus options scb = (response)-> console.log "Success!" console.log response ecb = (err)-> console.error "Error!" console.log err status.fetch scb, ecb
true
PowerPanelStatus = require "./index.js" # If you have PowerPanel Business 4.x installed, test would be the default # connection URL and credentials. options = { base_url: "http://localhost:3052" user_name: "admin" password: "PI:PASSWORD:<PASSWORD>END_PI" } status = new PowerPanelStatus options scb = (response)-> console.log "Success!" console.log response ecb = (err)-> console.error "Error!" console.log err status.fetch scb, ecb
[ { "context": "always asynch 2.1.x behaviour](https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.1#wiki-br", "end": 1110, "score": 0.9996930956840515, "start": 1103, "tag": "USERNAME", "value": "jrburke" }, { "context": "g-to-RequireJS-2.1#wiki-breaking-async)\r\n\r\n@...
source/code/NodeRequirer.coffee
gaybro8777/uRequire
103
fs = require 'fs' upath = require 'upath' util = require 'util' pathRelative = require './paths/pathRelative' Dependency = require './fileResources/Dependency' urequire = require './urequire' BundleBase = require './process/BundleBase' ### The `nodejs`'s require facility. An instance of `NodeRequirer` is created for each UMD module, when running on node. Its purpose is to resolve and load modules, synchronoysly or asynchronoysly, depending on how it was called: * sync (blocking): when call was made the nodejs way `require('dependency')` in which case the module is simply loaded & returned. * async (immediatelly returning): when called the AMD/requirejs way `require(['dep1', 'dep2'], function(dep1, dep2) {})` in which case the callback function is called, when all modules/dependencies have been loaded asynchronously. @note: it used to mimic the inconsistent RequireJS 2.0.x behaviour on the `require([..],->`, where if all deps are loaded before, then the call is SYNCHRONOUS :-(. It is now reverted to the [always asynch 2.1.x behaviour](https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.1#wiki-breaking-async) @author Agelos Pikoulas ### class NodeRequirer extends BundleBase ### Create a NodeRequirer instance, passing paths resolution information. @param {String} moduleNameBR `module` name of current UMD module (that calls 'require'), in bundleRelative format, eg 'models/Person', as hardcoded in generated uRequire UMD. @param {Object} modyle The node `module` object of the current UMD module (that calls 'require'). Used to issue the actual node `require` on the module, to preserve the correct `node_modules` lookup paths (as opposed to using the NodeRequirer's paths. @param {Function} The original module's `require`, used for debuging `require.resolve` @param {String} dirname `__dirname` passed at runtime from the UMD module, poiniting to its self (i.e filename of the .js file). @param {String} webRootMap where '/' is mapped when running on nodejs, as hardcoded in uRequire UMD (relative to path). ### constructor: (@moduleNameBR, @modyle, @moduleRequire, @dirname, @webRootMap, debugLevel) -> @l = new _B.Logger "uRequire/NodeRequirer `#{@moduleNameBR}`}", debugLevel # template.debugLevel @path = upath.normalize ( @dirname + '/' + (pathRelative "#{upath.dirname @moduleNameBR}", ".", assumeRoot: true) + '/' ) @l.deb("""\n `new NodeRequirer()` instanciating @moduleNameBR = '#{@moduleNameBR}' @modyle.id = '#{@modyle.id}' @dirname = '#{@dirname}' @webRootMap = '#{@webRootMap}') @path = '#{@path}' """) if @l.deb 30 if @getRequireJSConfig().baseUrl baseUrl = @getRequireJSConfig().baseUrl @l.deb("`baseUrl` (from requireJsConfig ) = #{baseUrl}") if @l.deb 15 @path = upath.normalize ( if baseUrl[0] is '/' #web root as reference @webRoot else #path as reference @path ) + '/' + baseUrl + '/' @l.deb("Final `@path` (from requireJsConfig.baseUrl & @path) = #{@path}") if @l.deb 30 ### Defaults to node's `require`, invoked on the module to preserve `node_modules` path lookup. It can be swaped with another/mock version (eg by spec tests). ### Object.defineProperties @::, nodeRequire: get: -> @_nodeRequire or _.bind @modyle.require, @modyle set: (@_nodeRequire) -> debugInfo: get:-> di = { path: @path webRoot: @webRoot } rjsLoaded = di["requirejsLoaded[@path]"] = {} for pathsRjs, rjs of NodeRequirer::requirejsLoaded rjsConfig = rjsLoaded[pathsRjs] = {} rjsConfig["requirejs._.config.baseUrl"] = rjs.s?.contexts?._?.config.baseUrl rjsConfig["requirejs._.config.paths"] = rjs.s?.contexts?._?.config.paths rjsConfigs = di["requireJSConfigs[@path]"] = {} for pathsRjsConfig, config of NodeRequirer::requireJSConfigs rjsConfigs[pathsRjsConfig] = config @l.prettify di ### Load the [Requirejs](http://requirejs.org/) system module (as npm installed), & cache for @path as key. Then cache it in static NodeRequirer::requirejsLoaded[@path], so only one instance is shared among all `NodeRequirer`s for a given @path. Hence, its created only once, first time it's needed (for each distinct @path). It is configuring rjs with resolved paths, for each of the paths entry in `requirejs.config.json`. Resolved paths are relative to `@path` (instead of `@dirname`). @return {requirejs} The module `RequireJS` for node, configured for this @path. ### requirejs: get: -> NodeRequirer::requirejsLoaded ?= {} # static / store in class if not NodeRequirer::requirejsLoaded[@path] requirejs = @nodeRequire 'requirejs' requireJsConf = nodeRequire: @nodeRequire baseUrl: @path # resolve each path, as we do in modules - take advantage of webRoot etc. if @getRequireJSConfig().paths requireJsConf.paths = {} for pathName, pathEntries of @getRequireJSConfig().paths pathEntries = _B.arrayize pathEntries requireJsConf.paths[pathName] or= [] for pathEntry in pathEntries for resolvedPath in @resolvePaths(new Dependency(pathEntry), @path) #rjs paths are relative to path, not some file requireJsConf.paths[pathName].push resolvedPath if not (resolvedPath in requireJsConf.paths[pathName]) requirejs.config requireJsConf NodeRequirer::requirejsLoaded[@path] = requirejs return NodeRequirer::requirejsLoaded[@path] ### Load 'requirejs.config.json' for @path & cache it with @path as key. @todo: do we really need this complexity ? @return {RequireJSConfig object} the requireJSConfig for @path (or {} if 'requirejs.config.json' not found/not valid json) ### getRequireJSConfig: -> NodeRequirer::requireJSConfigs ?= {} # static / store in class if NodeRequirer::requireJSConfigs[@path] is undefined try rjsc = require('fs').readFileSync @path + 'requirejs.config.json', 'utf-8' catch #do nothing, we just dont have a requirejs.config.json if rjsc try NodeRequirer::requireJSConfigs[@path] = JSON.parse rjsc catch err throw new UError "urequire: error parsing requirejs.config.json from #{@path + 'requirejs.config.json'}", nested: err NodeRequirer::requireJSConfigs[@path] ?= {} # if still undefined, after so much effort return NodeRequirer::requireJSConfigs[@path] ### Loads *one* module, synchronously. Uses either node's `require` or the synchronous version of `RequireJs`'s. The latter is used for modules that : * either have a plugin (eg `"text!module.txt"`) * or modules that failed to load with node's require: these are assumed to be native AMD, hence and attempt is made to load with RequireJS. @note If loading failures occur, it makes more than one attempts to find/load a module (alt paths & node/rjs require), noting loading errors. If all loading attempts fail, **it QUITS with process.exit(1)**. @param {Dependency} dep The Dependency to be load. @return {module} loaded module or quits if it fails ### unloaded = {} loadModule: (dep)=> #load module either via nodeRequire OR requireJS if it needs a plugin or if it fails! attempts = [] loadedModule = unloaded # cater for module returning 'undefined/null' which is a valid value @l.deb 95, "called `loadModule('#{dep}')`" resolvedPaths = @resolvePaths(dep, @dirname) @l.deb "resolvedPaths = \n", resolvedPaths if @l.deb 95 requirers = if hasPlugin = dep.plugin?.name?() not in [undefined, 'node'] # plugin 'node' is dummy: just signals ommit from defineArrayDeps ['requirejs'] else ['nodeRequire', 'requirejs'] for requirer in requirers for modulePath, resolvedPathNo in resolvedPaths if hasPlugin then modulePath = "#{dep.pluginName}!#{modulePath}" if @l.deb 50 @l.deb 50, "resolvedPathNo ##{resolvedPathNo}: '#{modulePath}'" if @l.deb(70) and requirer is 'nodeRequire' try @l.deb "@moduleRequire.resolve() = `#{@moduleRequire.resolve(modulePath)}`" catch attempts.push {resolvedPathNo, modulePath, requirerUsed: requirer, dependency: dep.name()} # modulePath = upath.addExt modulePath, '.js' # RequireJS wants this for some reason ? @l.deb "ISSUING: #{requirer}('#{modulePath}')" if @l.deb 30 try loadedModule = @[requirer](modulePath) catch err @l.warn "FAILED: `@#{requirer}('#{modulePath}')` err=\n", err if @l.deb 30 @requirejs.undef(modulePath) if requirer is 'requirejs' # solves https://github.com/jrburke/requirejs/issues/1224 _.extend _.last(attempts), urequireError: "Error loading module through requirer `#{requirer}`." error: {string:err.toString(), err: err} if hasPlugin _.extend _.last(attempts), pluginName: dep.pluginName, pluginPaths: @requireJSConfig?.paths[dep.pluginName], pluginResolvedPaths: @requirejs?.s?.contexts?._?.config?.paths[dep.pluginName] break if loadedModule isnt unloaded break if loadedModule isnt unloaded if loadedModule is unloaded @l.er """\n *uRequire #{urequire.VERSION}*: failed to load dependency: '#{dep}' in module '#{@moduleNameBR}'. Tried paths: #{ _.uniq("'" + att.modulePath + "'" for att in attempts).join '\n '} Quiting with throwing 1st error at the end - Detailed attempts follow: #{(" \u001b[33m Attempt #" + (attIdx + 1) + '\n' + @l.prettify(att) for att, attIdx in attempts).join('\n\n')} Debug info:\n """, @debugInfo throw attempts[0]?.error?.err or '1st err was undefined!' else @l.ok "`@#{requirer}` loaded dep `#{dep}` from `#{modulePath}` (resolvedPathNo ##{resolvedPathNo}) " if @l.deb 20 loadedModule ### The actual `require` method, called as synchronous or asynchronous. It is the method passed to the *factoryBody* of UMD modules (i.e what you call on your uRequire module when running on node) and the one used to load all deps before entering the module's factoryBody. @param { String, Array<String> } strDeps As `String`, its a single dependency to load *synchronously*, eg `"models/person"` or `'text!abc.txt'` As `Array<String>`, its an array of dependencies to load *asynchronously* the AMD/RequireJS way, eg `[ "models/person" or 'text!abc.txt' ]` @param {Function} callback The callback function to call when all dependencies are loaded, called asynchronously by default (or synchronously if all dependencies were cached, when it matched RequireJs's 2.0.x behaviour [not needed any more in 2.1.x](https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.1#wiki-breaking-async) ) @return {module} module loaded if called *synchronously*, or `undefined` if it was called *asynchronously* ### require: (strDeps, callback)=> # strDeps is { 'String' | '[]<String>' } if _.isString strDeps @l.deb "`nr.require('#{strDeps}')` called - @loadModule synchronously single dep." if @l.deb 80 @loadModule new Dependency strDeps, path: @moduleNameBR else if _.isArray(strDeps) and _.isFunction(callback) # we have an arrayDeps []<String> & cb @l.deb "`nr.require(#{util.inspect strDeps})` called: @loadModule called asynchronously for each dep in array." if @l.deb 50 process.nextTick => #load asynchronously # load each dependency and callback() callback.apply null, (@loadModule(new Dependency strDep, path: @moduleNameBR) for strDep in strDeps) module.exports = NodeRequirer
170127
fs = require 'fs' upath = require 'upath' util = require 'util' pathRelative = require './paths/pathRelative' Dependency = require './fileResources/Dependency' urequire = require './urequire' BundleBase = require './process/BundleBase' ### The `nodejs`'s require facility. An instance of `NodeRequirer` is created for each UMD module, when running on node. Its purpose is to resolve and load modules, synchronoysly or asynchronoysly, depending on how it was called: * sync (blocking): when call was made the nodejs way `require('dependency')` in which case the module is simply loaded & returned. * async (immediatelly returning): when called the AMD/requirejs way `require(['dep1', 'dep2'], function(dep1, dep2) {})` in which case the callback function is called, when all modules/dependencies have been loaded asynchronously. @note: it used to mimic the inconsistent RequireJS 2.0.x behaviour on the `require([..],->`, where if all deps are loaded before, then the call is SYNCHRONOUS :-(. It is now reverted to the [always asynch 2.1.x behaviour](https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.1#wiki-breaking-async) @author <NAME> ### class NodeRequirer extends BundleBase ### Create a NodeRequirer instance, passing paths resolution information. @param {String} moduleNameBR `module` name of current UMD module (that calls 'require'), in bundleRelative format, eg 'models/Person', as hardcoded in generated uRequire UMD. @param {Object} modyle The node `module` object of the current UMD module (that calls 'require'). Used to issue the actual node `require` on the module, to preserve the correct `node_modules` lookup paths (as opposed to using the NodeRequirer's paths. @param {Function} The original module's `require`, used for debuging `require.resolve` @param {String} dirname `__dirname` passed at runtime from the UMD module, poiniting to its self (i.e filename of the .js file). @param {String} webRootMap where '/' is mapped when running on nodejs, as hardcoded in uRequire UMD (relative to path). ### constructor: (@moduleNameBR, @modyle, @moduleRequire, @dirname, @webRootMap, debugLevel) -> @l = new _B.Logger "uRequire/NodeRequirer `#{@moduleNameBR}`}", debugLevel # template.debugLevel @path = upath.normalize ( @dirname + '/' + (pathRelative "#{upath.dirname @moduleNameBR}", ".", assumeRoot: true) + '/' ) @l.deb("""\n `new NodeRequirer()` instanciating @moduleNameBR = '#{@moduleNameBR}' @modyle.id = '#{@modyle.id}' @dirname = '#{@dirname}' @webRootMap = '#{@webRootMap}') @path = '#{@path}' """) if @l.deb 30 if @getRequireJSConfig().baseUrl baseUrl = @getRequireJSConfig().baseUrl @l.deb("`baseUrl` (from requireJsConfig ) = #{baseUrl}") if @l.deb 15 @path = upath.normalize ( if baseUrl[0] is '/' #web root as reference @webRoot else #path as reference @path ) + '/' + baseUrl + '/' @l.deb("Final `@path` (from requireJsConfig.baseUrl & @path) = #{@path}") if @l.deb 30 ### Defaults to node's `require`, invoked on the module to preserve `node_modules` path lookup. It can be swaped with another/mock version (eg by spec tests). ### Object.defineProperties @::, nodeRequire: get: -> @_nodeRequire or _.bind @modyle.require, @modyle set: (@_nodeRequire) -> debugInfo: get:-> di = { path: @path webRoot: @webRoot } rjsLoaded = di["requirejsLoaded[@path]"] = {} for pathsRjs, rjs of NodeRequirer::requirejsLoaded rjsConfig = rjsLoaded[pathsRjs] = {} rjsConfig["requirejs._.config.baseUrl"] = rjs.s?.contexts?._?.config.baseUrl rjsConfig["requirejs._.config.paths"] = rjs.s?.contexts?._?.config.paths rjsConfigs = di["requireJSConfigs[@path]"] = {} for pathsRjsConfig, config of NodeRequirer::requireJSConfigs rjsConfigs[pathsRjsConfig] = config @l.prettify di ### Load the [Requirejs](http://requirejs.org/) system module (as npm installed), & cache for @path as key. Then cache it in static NodeRequirer::requirejsLoaded[@path], so only one instance is shared among all `NodeRequirer`s for a given @path. Hence, its created only once, first time it's needed (for each distinct @path). It is configuring rjs with resolved paths, for each of the paths entry in `requirejs.config.json`. Resolved paths are relative to `@path` (instead of `@dirname`). @return {requirejs} The module `RequireJS` for node, configured for this @path. ### requirejs: get: -> NodeRequirer::requirejsLoaded ?= {} # static / store in class if not NodeRequirer::requirejsLoaded[@path] requirejs = @nodeRequire 'requirejs' requireJsConf = nodeRequire: @nodeRequire baseUrl: @path # resolve each path, as we do in modules - take advantage of webRoot etc. if @getRequireJSConfig().paths requireJsConf.paths = {} for pathName, pathEntries of @getRequireJSConfig().paths pathEntries = _B.arrayize pathEntries requireJsConf.paths[pathName] or= [] for pathEntry in pathEntries for resolvedPath in @resolvePaths(new Dependency(pathEntry), @path) #rjs paths are relative to path, not some file requireJsConf.paths[pathName].push resolvedPath if not (resolvedPath in requireJsConf.paths[pathName]) requirejs.config requireJsConf NodeRequirer::requirejsLoaded[@path] = requirejs return NodeRequirer::requirejsLoaded[@path] ### Load 'requirejs.config.json' for @path & cache it with @path as key. @todo: do we really need this complexity ? @return {RequireJSConfig object} the requireJSConfig for @path (or {} if 'requirejs.config.json' not found/not valid json) ### getRequireJSConfig: -> NodeRequirer::requireJSConfigs ?= {} # static / store in class if NodeRequirer::requireJSConfigs[@path] is undefined try rjsc = require('fs').readFileSync @path + 'requirejs.config.json', 'utf-8' catch #do nothing, we just dont have a requirejs.config.json if rjsc try NodeRequirer::requireJSConfigs[@path] = JSON.parse rjsc catch err throw new UError "urequire: error parsing requirejs.config.json from #{@path + 'requirejs.config.json'}", nested: err NodeRequirer::requireJSConfigs[@path] ?= {} # if still undefined, after so much effort return NodeRequirer::requireJSConfigs[@path] ### Loads *one* module, synchronously. Uses either node's `require` or the synchronous version of `RequireJs`'s. The latter is used for modules that : * either have a plugin (eg `"text!module.txt"`) * or modules that failed to load with node's require: these are assumed to be native AMD, hence and attempt is made to load with RequireJS. @note If loading failures occur, it makes more than one attempts to find/load a module (alt paths & node/rjs require), noting loading errors. If all loading attempts fail, **it QUITS with process.exit(1)**. @param {Dependency} dep The Dependency to be load. @return {module} loaded module or quits if it fails ### unloaded = {} loadModule: (dep)=> #load module either via nodeRequire OR requireJS if it needs a plugin or if it fails! attempts = [] loadedModule = unloaded # cater for module returning 'undefined/null' which is a valid value @l.deb 95, "called `loadModule('#{dep}')`" resolvedPaths = @resolvePaths(dep, @dirname) @l.deb "resolvedPaths = \n", resolvedPaths if @l.deb 95 requirers = if hasPlugin = dep.plugin?.name?() not in [undefined, 'node'] # plugin 'node' is dummy: just signals ommit from defineArrayDeps ['requirejs'] else ['nodeRequire', 'requirejs'] for requirer in requirers for modulePath, resolvedPathNo in resolvedPaths if hasPlugin then modulePath = "#{dep.pluginName}!#{modulePath}" if @l.deb 50 @l.deb 50, "resolvedPathNo ##{resolvedPathNo}: '#{modulePath}'" if @l.deb(70) and requirer is 'nodeRequire' try @l.deb "@moduleRequire.resolve() = `#{@moduleRequire.resolve(modulePath)}`" catch attempts.push {resolvedPathNo, modulePath, requirerUsed: requirer, dependency: dep.name()} # modulePath = upath.addExt modulePath, '.js' # RequireJS wants this for some reason ? @l.deb "ISSUING: #{requirer}('#{modulePath}')" if @l.deb 30 try loadedModule = @[requirer](modulePath) catch err @l.warn "FAILED: `@#{requirer}('#{modulePath}')` err=\n", err if @l.deb 30 @requirejs.undef(modulePath) if requirer is 'requirejs' # solves https://github.com/jrburke/requirejs/issues/1224 _.extend _.last(attempts), urequireError: "Error loading module through requirer `#{requirer}`." error: {string:err.toString(), err: err} if hasPlugin _.extend _.last(attempts), pluginName: dep.pluginName, pluginPaths: @requireJSConfig?.paths[dep.pluginName], pluginResolvedPaths: @requirejs?.s?.contexts?._?.config?.paths[dep.pluginName] break if loadedModule isnt unloaded break if loadedModule isnt unloaded if loadedModule is unloaded @l.er """\n *uRequire #{urequire.VERSION}*: failed to load dependency: '#{dep}' in module '#{@moduleNameBR}'. Tried paths: #{ _.uniq("'" + att.modulePath + "'" for att in attempts).join '\n '} Quiting with throwing 1st error at the end - Detailed attempts follow: #{(" \u001b[33m Attempt #" + (attIdx + 1) + '\n' + @l.prettify(att) for att, attIdx in attempts).join('\n\n')} Debug info:\n """, @debugInfo throw attempts[0]?.error?.err or '1st err was undefined!' else @l.ok "`@#{requirer}` loaded dep `#{dep}` from `#{modulePath}` (resolvedPathNo ##{resolvedPathNo}) " if @l.deb 20 loadedModule ### The actual `require` method, called as synchronous or asynchronous. It is the method passed to the *factoryBody* of UMD modules (i.e what you call on your uRequire module when running on node) and the one used to load all deps before entering the module's factoryBody. @param { String, Array<String> } strDeps As `String`, its a single dependency to load *synchronously*, eg `"models/person"` or `'text!abc.txt'` As `Array<String>`, its an array of dependencies to load *asynchronously* the AMD/RequireJS way, eg `[ "models/person" or 'text!abc.txt' ]` @param {Function} callback The callback function to call when all dependencies are loaded, called asynchronously by default (or synchronously if all dependencies were cached, when it matched RequireJs's 2.0.x behaviour [not needed any more in 2.1.x](https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.1#wiki-breaking-async) ) @return {module} module loaded if called *synchronously*, or `undefined` if it was called *asynchronously* ### require: (strDeps, callback)=> # strDeps is { 'String' | '[]<String>' } if _.isString strDeps @l.deb "`nr.require('#{strDeps}')` called - @loadModule synchronously single dep." if @l.deb 80 @loadModule new Dependency strDeps, path: @moduleNameBR else if _.isArray(strDeps) and _.isFunction(callback) # we have an arrayDeps []<String> & cb @l.deb "`nr.require(#{util.inspect strDeps})` called: @loadModule called asynchronously for each dep in array." if @l.deb 50 process.nextTick => #load asynchronously # load each dependency and callback() callback.apply null, (@loadModule(new Dependency strDep, path: @moduleNameBR) for strDep in strDeps) module.exports = NodeRequirer
true
fs = require 'fs' upath = require 'upath' util = require 'util' pathRelative = require './paths/pathRelative' Dependency = require './fileResources/Dependency' urequire = require './urequire' BundleBase = require './process/BundleBase' ### The `nodejs`'s require facility. An instance of `NodeRequirer` is created for each UMD module, when running on node. Its purpose is to resolve and load modules, synchronoysly or asynchronoysly, depending on how it was called: * sync (blocking): when call was made the nodejs way `require('dependency')` in which case the module is simply loaded & returned. * async (immediatelly returning): when called the AMD/requirejs way `require(['dep1', 'dep2'], function(dep1, dep2) {})` in which case the callback function is called, when all modules/dependencies have been loaded asynchronously. @note: it used to mimic the inconsistent RequireJS 2.0.x behaviour on the `require([..],->`, where if all deps are loaded before, then the call is SYNCHRONOUS :-(. It is now reverted to the [always asynch 2.1.x behaviour](https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.1#wiki-breaking-async) @author PI:NAME:<NAME>END_PI ### class NodeRequirer extends BundleBase ### Create a NodeRequirer instance, passing paths resolution information. @param {String} moduleNameBR `module` name of current UMD module (that calls 'require'), in bundleRelative format, eg 'models/Person', as hardcoded in generated uRequire UMD. @param {Object} modyle The node `module` object of the current UMD module (that calls 'require'). Used to issue the actual node `require` on the module, to preserve the correct `node_modules` lookup paths (as opposed to using the NodeRequirer's paths. @param {Function} The original module's `require`, used for debuging `require.resolve` @param {String} dirname `__dirname` passed at runtime from the UMD module, poiniting to its self (i.e filename of the .js file). @param {String} webRootMap where '/' is mapped when running on nodejs, as hardcoded in uRequire UMD (relative to path). ### constructor: (@moduleNameBR, @modyle, @moduleRequire, @dirname, @webRootMap, debugLevel) -> @l = new _B.Logger "uRequire/NodeRequirer `#{@moduleNameBR}`}", debugLevel # template.debugLevel @path = upath.normalize ( @dirname + '/' + (pathRelative "#{upath.dirname @moduleNameBR}", ".", assumeRoot: true) + '/' ) @l.deb("""\n `new NodeRequirer()` instanciating @moduleNameBR = '#{@moduleNameBR}' @modyle.id = '#{@modyle.id}' @dirname = '#{@dirname}' @webRootMap = '#{@webRootMap}') @path = '#{@path}' """) if @l.deb 30 if @getRequireJSConfig().baseUrl baseUrl = @getRequireJSConfig().baseUrl @l.deb("`baseUrl` (from requireJsConfig ) = #{baseUrl}") if @l.deb 15 @path = upath.normalize ( if baseUrl[0] is '/' #web root as reference @webRoot else #path as reference @path ) + '/' + baseUrl + '/' @l.deb("Final `@path` (from requireJsConfig.baseUrl & @path) = #{@path}") if @l.deb 30 ### Defaults to node's `require`, invoked on the module to preserve `node_modules` path lookup. It can be swaped with another/mock version (eg by spec tests). ### Object.defineProperties @::, nodeRequire: get: -> @_nodeRequire or _.bind @modyle.require, @modyle set: (@_nodeRequire) -> debugInfo: get:-> di = { path: @path webRoot: @webRoot } rjsLoaded = di["requirejsLoaded[@path]"] = {} for pathsRjs, rjs of NodeRequirer::requirejsLoaded rjsConfig = rjsLoaded[pathsRjs] = {} rjsConfig["requirejs._.config.baseUrl"] = rjs.s?.contexts?._?.config.baseUrl rjsConfig["requirejs._.config.paths"] = rjs.s?.contexts?._?.config.paths rjsConfigs = di["requireJSConfigs[@path]"] = {} for pathsRjsConfig, config of NodeRequirer::requireJSConfigs rjsConfigs[pathsRjsConfig] = config @l.prettify di ### Load the [Requirejs](http://requirejs.org/) system module (as npm installed), & cache for @path as key. Then cache it in static NodeRequirer::requirejsLoaded[@path], so only one instance is shared among all `NodeRequirer`s for a given @path. Hence, its created only once, first time it's needed (for each distinct @path). It is configuring rjs with resolved paths, for each of the paths entry in `requirejs.config.json`. Resolved paths are relative to `@path` (instead of `@dirname`). @return {requirejs} The module `RequireJS` for node, configured for this @path. ### requirejs: get: -> NodeRequirer::requirejsLoaded ?= {} # static / store in class if not NodeRequirer::requirejsLoaded[@path] requirejs = @nodeRequire 'requirejs' requireJsConf = nodeRequire: @nodeRequire baseUrl: @path # resolve each path, as we do in modules - take advantage of webRoot etc. if @getRequireJSConfig().paths requireJsConf.paths = {} for pathName, pathEntries of @getRequireJSConfig().paths pathEntries = _B.arrayize pathEntries requireJsConf.paths[pathName] or= [] for pathEntry in pathEntries for resolvedPath in @resolvePaths(new Dependency(pathEntry), @path) #rjs paths are relative to path, not some file requireJsConf.paths[pathName].push resolvedPath if not (resolvedPath in requireJsConf.paths[pathName]) requirejs.config requireJsConf NodeRequirer::requirejsLoaded[@path] = requirejs return NodeRequirer::requirejsLoaded[@path] ### Load 'requirejs.config.json' for @path & cache it with @path as key. @todo: do we really need this complexity ? @return {RequireJSConfig object} the requireJSConfig for @path (or {} if 'requirejs.config.json' not found/not valid json) ### getRequireJSConfig: -> NodeRequirer::requireJSConfigs ?= {} # static / store in class if NodeRequirer::requireJSConfigs[@path] is undefined try rjsc = require('fs').readFileSync @path + 'requirejs.config.json', 'utf-8' catch #do nothing, we just dont have a requirejs.config.json if rjsc try NodeRequirer::requireJSConfigs[@path] = JSON.parse rjsc catch err throw new UError "urequire: error parsing requirejs.config.json from #{@path + 'requirejs.config.json'}", nested: err NodeRequirer::requireJSConfigs[@path] ?= {} # if still undefined, after so much effort return NodeRequirer::requireJSConfigs[@path] ### Loads *one* module, synchronously. Uses either node's `require` or the synchronous version of `RequireJs`'s. The latter is used for modules that : * either have a plugin (eg `"text!module.txt"`) * or modules that failed to load with node's require: these are assumed to be native AMD, hence and attempt is made to load with RequireJS. @note If loading failures occur, it makes more than one attempts to find/load a module (alt paths & node/rjs require), noting loading errors. If all loading attempts fail, **it QUITS with process.exit(1)**. @param {Dependency} dep The Dependency to be load. @return {module} loaded module or quits if it fails ### unloaded = {} loadModule: (dep)=> #load module either via nodeRequire OR requireJS if it needs a plugin or if it fails! attempts = [] loadedModule = unloaded # cater for module returning 'undefined/null' which is a valid value @l.deb 95, "called `loadModule('#{dep}')`" resolvedPaths = @resolvePaths(dep, @dirname) @l.deb "resolvedPaths = \n", resolvedPaths if @l.deb 95 requirers = if hasPlugin = dep.plugin?.name?() not in [undefined, 'node'] # plugin 'node' is dummy: just signals ommit from defineArrayDeps ['requirejs'] else ['nodeRequire', 'requirejs'] for requirer in requirers for modulePath, resolvedPathNo in resolvedPaths if hasPlugin then modulePath = "#{dep.pluginName}!#{modulePath}" if @l.deb 50 @l.deb 50, "resolvedPathNo ##{resolvedPathNo}: '#{modulePath}'" if @l.deb(70) and requirer is 'nodeRequire' try @l.deb "@moduleRequire.resolve() = `#{@moduleRequire.resolve(modulePath)}`" catch attempts.push {resolvedPathNo, modulePath, requirerUsed: requirer, dependency: dep.name()} # modulePath = upath.addExt modulePath, '.js' # RequireJS wants this for some reason ? @l.deb "ISSUING: #{requirer}('#{modulePath}')" if @l.deb 30 try loadedModule = @[requirer](modulePath) catch err @l.warn "FAILED: `@#{requirer}('#{modulePath}')` err=\n", err if @l.deb 30 @requirejs.undef(modulePath) if requirer is 'requirejs' # solves https://github.com/jrburke/requirejs/issues/1224 _.extend _.last(attempts), urequireError: "Error loading module through requirer `#{requirer}`." error: {string:err.toString(), err: err} if hasPlugin _.extend _.last(attempts), pluginName: dep.pluginName, pluginPaths: @requireJSConfig?.paths[dep.pluginName], pluginResolvedPaths: @requirejs?.s?.contexts?._?.config?.paths[dep.pluginName] break if loadedModule isnt unloaded break if loadedModule isnt unloaded if loadedModule is unloaded @l.er """\n *uRequire #{urequire.VERSION}*: failed to load dependency: '#{dep}' in module '#{@moduleNameBR}'. Tried paths: #{ _.uniq("'" + att.modulePath + "'" for att in attempts).join '\n '} Quiting with throwing 1st error at the end - Detailed attempts follow: #{(" \u001b[33m Attempt #" + (attIdx + 1) + '\n' + @l.prettify(att) for att, attIdx in attempts).join('\n\n')} Debug info:\n """, @debugInfo throw attempts[0]?.error?.err or '1st err was undefined!' else @l.ok "`@#{requirer}` loaded dep `#{dep}` from `#{modulePath}` (resolvedPathNo ##{resolvedPathNo}) " if @l.deb 20 loadedModule ### The actual `require` method, called as synchronous or asynchronous. It is the method passed to the *factoryBody* of UMD modules (i.e what you call on your uRequire module when running on node) and the one used to load all deps before entering the module's factoryBody. @param { String, Array<String> } strDeps As `String`, its a single dependency to load *synchronously*, eg `"models/person"` or `'text!abc.txt'` As `Array<String>`, its an array of dependencies to load *asynchronously* the AMD/RequireJS way, eg `[ "models/person" or 'text!abc.txt' ]` @param {Function} callback The callback function to call when all dependencies are loaded, called asynchronously by default (or synchronously if all dependencies were cached, when it matched RequireJs's 2.0.x behaviour [not needed any more in 2.1.x](https://github.com/jrburke/requirejs/wiki/Upgrading-to-RequireJS-2.1#wiki-breaking-async) ) @return {module} module loaded if called *synchronously*, or `undefined` if it was called *asynchronously* ### require: (strDeps, callback)=> # strDeps is { 'String' | '[]<String>' } if _.isString strDeps @l.deb "`nr.require('#{strDeps}')` called - @loadModule synchronously single dep." if @l.deb 80 @loadModule new Dependency strDeps, path: @moduleNameBR else if _.isArray(strDeps) and _.isFunction(callback) # we have an arrayDeps []<String> & cb @l.deb "`nr.require(#{util.inspect strDeps})` called: @loadModule called asynchronously for each dep in array." if @l.deb 50 process.nextTick => #load asynchronously # load each dependency and callback() callback.apply null, (@loadModule(new Dependency strDep, path: @moduleNameBR) for strDep in strDeps) module.exports = NodeRequirer
[ { "context": "###\n\nAdapted from Fred Callaway's experiment.coffee file\n\n###\n# coffeelint: disab", "end": 31, "score": 0.9998524188995361, "start": 18, "tag": "NAME", "value": "Fred Callaway" } ]
experiment/src/experiment.coffee
ankitknitj/Masters_Thesis_MDPAssignment
0
### Adapted from Fred Callaway's experiment.coffee file ### # coffeelint: disable=max_line_length, indentation # Enforce a minimum window size checkWindowSize = (width, height, display) -> console.log 'cws' win_width = $(window).width() maxHeight = $(window).height() if $(window).width() < width or $(window).height() < height display.hide() $('#window_error').show() else $('#window_error').hide() display.show() $(window).resize -> checkWindowSize 800, 600, $('#jspsych-target') $(window).resize() loadJson = (file) -> result = $.ajax dataType: 'json' url: file async: false return result.responseJSON $(window).on 'load', -> trials = loadJson "static/json/trials.json" initializeExperiment trials initializeExperiment = (trials) -> console.log 'INITIALIZE EXPERIMENT' console.log trials # ============================== # # ========= EXPERIMENT ========= # # ============================== # welcome = type: 'text' text: """ <h1>Mouselab-MDP Demo</h1> This is an experiment to test understand human metacognitive learning. <p> Press <b>space</b> to continue. """ i = 0 main = type: 'mouselab-mdp' leftMessage: -> "Round: #{++i}/#{trials.length}" timeline: trials experiment_timeline = [ # welcome main ] # ================================================ # # ========= START AND END THE EXPERIMENT ========= # # ================================================ # jsPsych.init display_element: $('#jspsych-target') timeline: experiment_timeline # show_progress_bar: true on_finish: -> jsPsych.data.displayData() on_data_update: (data) -> console.log 'data', data
128228
### Adapted from <NAME>'s experiment.coffee file ### # coffeelint: disable=max_line_length, indentation # Enforce a minimum window size checkWindowSize = (width, height, display) -> console.log 'cws' win_width = $(window).width() maxHeight = $(window).height() if $(window).width() < width or $(window).height() < height display.hide() $('#window_error').show() else $('#window_error').hide() display.show() $(window).resize -> checkWindowSize 800, 600, $('#jspsych-target') $(window).resize() loadJson = (file) -> result = $.ajax dataType: 'json' url: file async: false return result.responseJSON $(window).on 'load', -> trials = loadJson "static/json/trials.json" initializeExperiment trials initializeExperiment = (trials) -> console.log 'INITIALIZE EXPERIMENT' console.log trials # ============================== # # ========= EXPERIMENT ========= # # ============================== # welcome = type: 'text' text: """ <h1>Mouselab-MDP Demo</h1> This is an experiment to test understand human metacognitive learning. <p> Press <b>space</b> to continue. """ i = 0 main = type: 'mouselab-mdp' leftMessage: -> "Round: #{++i}/#{trials.length}" timeline: trials experiment_timeline = [ # welcome main ] # ================================================ # # ========= START AND END THE EXPERIMENT ========= # # ================================================ # jsPsych.init display_element: $('#jspsych-target') timeline: experiment_timeline # show_progress_bar: true on_finish: -> jsPsych.data.displayData() on_data_update: (data) -> console.log 'data', data
true
### Adapted from PI:NAME:<NAME>END_PI's experiment.coffee file ### # coffeelint: disable=max_line_length, indentation # Enforce a minimum window size checkWindowSize = (width, height, display) -> console.log 'cws' win_width = $(window).width() maxHeight = $(window).height() if $(window).width() < width or $(window).height() < height display.hide() $('#window_error').show() else $('#window_error').hide() display.show() $(window).resize -> checkWindowSize 800, 600, $('#jspsych-target') $(window).resize() loadJson = (file) -> result = $.ajax dataType: 'json' url: file async: false return result.responseJSON $(window).on 'load', -> trials = loadJson "static/json/trials.json" initializeExperiment trials initializeExperiment = (trials) -> console.log 'INITIALIZE EXPERIMENT' console.log trials # ============================== # # ========= EXPERIMENT ========= # # ============================== # welcome = type: 'text' text: """ <h1>Mouselab-MDP Demo</h1> This is an experiment to test understand human metacognitive learning. <p> Press <b>space</b> to continue. """ i = 0 main = type: 'mouselab-mdp' leftMessage: -> "Round: #{++i}/#{trials.length}" timeline: trials experiment_timeline = [ # welcome main ] # ================================================ # # ========= START AND END THE EXPERIMENT ========= # # ================================================ # jsPsych.init display_element: $('#jspsych-target') timeline: experiment_timeline # show_progress_bar: true on_finish: -> jsPsych.data.displayData() on_data_update: (data) -> console.log 'data', data
[ { "context": "'checkout.vtex.com'\n COOKIE_ORDER_FORM_ID_KEY = '__ofid'\n cookie = readCookie(COOKIE_NAME)\n return ", "end": 17126, "score": 0.9671769142150879, "start": 17119, "tag": "KEY", "value": "'__ofid" } ]
src/checkout.coffee
vtex/vtex.js
99
# UTILITY FUNCTIONS trim = (str) -> str.replace(/^\s+|\s+$/g, ''); mapize = (str, pairSeparator, keyValueSeparator, fnKey, fnValue) -> map = {} for pair in str.split(pairSeparator) [key, value...] = pair.split(keyValueSeparator) map[fnKey(key)] = fnValue(value.join('=')) return map urlParams = -> mapize(window.location.search.substring(1), '&', '=', decodeURIComponent, decodeURIComponent) urlParam = (name) -> urlParams()[name] readCookies = -> mapize(document.cookie, ';', '=', trim, unescape) readCookie = (name) -> readCookies()[name] readSubcookie = (name, cookie) -> mapize(cookie, '&', '=', ((s)->s), unescape)[name] # IE window.location.origin or= window.location.protocol + "//" + window.location.hostname + (if window.location.port then ':' + window.location.port else '') class Checkout HOST_URL = window.location.origin events = ORDER_FORM_UPDATED: 'orderFormUpdated.vtex' ATTACHMENT_UPDATED: 'attachmentUpdated.vtex' REQUEST_BEGIN: 'checkoutRequestBegin.vtex' REQUEST_END: 'checkoutRequestEnd.vtex' constructor: (options = {}) -> HOST_URL = options.hostURL if options.hostURL if options.ajax @ajax = options.ajax else if window.AjaxQueue @ajax = window.AjaxQueue($.ajax) else @ajax = $.ajax @promise = options.promise or $.when @CHECKOUT_ID = 'checkout' @orderForm = undefined @orderFormId = undefined @_pendingRequestCounter = 0 @_urlToRequestMap = {} @_allOrderFormSections = [ 'items' 'totalizers' 'clientProfileData' 'shippingData' 'paymentData' 'sellers' 'messages' 'marketingData' 'clientPreferencesData' 'storePreferencesData' 'giftRegistryData' 'ratesAndBenefitsData' 'openTextField' 'commercialConditionData', 'customData' ] ### PRIVATE METHODS ### _cacheOrderForm: (data) => @orderFormId = data.orderFormId @orderForm = data _increasePendingRequests: (options) => @_pendingRequestCounter++ $(window).trigger(events.REQUEST_BEGIN, [options]) _decreasePendingRequests: => @_pendingRequestCounter-- $(window).trigger(events.REQUEST_END, arguments) _broadcastOrderFormUnlessPendingRequests: (orderForm) => return unless @_pendingRequestCounter is 0 $(window).trigger(events.ORDER_FORM_UPDATED, [orderForm]) _orderFormHasExpectedSections: (orderForm, sections) -> if not orderForm or not orderForm instanceof Object return false for section in sections return false if not orderForm[section] return true # $.ajax wrapper with common defaults. # Used to encapsulate requests which have side effects and should broadcast results _updateOrderForm: (options) => throw new Error("options.url is required when sending request") unless options?.url # Defaults options.type or= 'POST' options.contentType or= 'application/json; charset=utf-8' options.dataType or= 'json' @_increasePendingRequests(options) xhr = @ajax(options) # Abort current call to this URL @_urlToRequestMap[options.url]?.abort() # Save this request @_urlToRequestMap[options.url] = xhr # Delete request from map upon completion xhr.always(=> delete @_urlToRequestMap[options.url]) xhr.always(@_decreasePendingRequests) xhr.done(@_cacheOrderForm) xhr.done(@_broadcastOrderFormUnlessPendingRequests) return xhr ### PUBLIC METHODS ### # Sends an idempotent request to retrieve the current OrderForm. getOrderForm: (expectedFormSections = @_allOrderFormSections) => if @_orderFormHasExpectedSections(@orderForm, expectedFormSections) return @promise(@orderForm) else checkoutRequest = { expectedOrderFormSections: expectedFormSections } xhr = @ajax url: @_getOrderFormURLWithId() + '?refreshOutdatedData=true' type: 'POST' contentType: 'application/json; charset=utf-8' dataType: 'json' data: JSON.stringify(checkoutRequest) xhr.done(@_cacheOrderForm) xhr.done(@_broadcastOrderFormUnlessPendingRequests) # Sends an OrderForm attachment to the current OrderForm, possibly updating it. sendAttachment: (attachmentId, attachment, expectedOrderFormSections = @_allOrderFormSections) => if attachmentId is undefined or attachment is undefined d = $.Deferred() d.reject("Invalid arguments") return d.promise() attachment['expectedOrderFormSections'] = expectedOrderFormSections xhr = @_updateOrderForm url: @_getSaveAttachmentURL(attachmentId) data: JSON.stringify(attachment) xhr.done((orderForm) => $(window).trigger(events.ATTACHMENT_UPDATED, [attachmentId, orderForm]) ) # Sends a request to set the used locale. sendLocale: (locale='pt-BR') => @sendAttachment('clientPreferencesData', {locale: locale}, []) # Sends orderGroupId to checkout in order to finish a transaction finishTransaction: (orderGroupId, expectedOrderFormSections = @_allOrderFormSections) => @_updateOrderForm url: @_getFinishTransactionURL(orderGroupId) # Sends a request to select an available gift updateSelectableGifts: (list, selectedGifts, expectedOrderFormSections = @_allOrderFormSections) => updateSelectableGiftsRequest = id: list selectedGifts: selectedGifts expectedOrderFormSections: expectedOrderFormSections @_updateOrderForm url: @_getUpdateSelectableGifts(list) data: JSON.stringify(updateSelectableGiftsRequest) # Sends a request to add an offering, along with its info, to the OrderForm. addOfferingWithInfo: (offeringId, offeringInfo, itemIndex, expectedOrderFormSections = @_allOrderFormSections) => updateItemsRequest = id: offeringId info: offeringInfo expectedOrderFormSections: expectedOrderFormSections @_updateOrderForm url: @_getAddOfferingsURL(itemIndex) data: JSON.stringify(updateItemsRequest) # Sends a request to add an offering to the OrderForm. addOffering: (offeringId, itemIndex, expectedOrderFormSections) => @addOfferingWithInfo(offeringId, null, itemIndex, expectedOrderFormSections) # Sends a request to remove an offering from the OrderForm. removeOffering: (offeringId, itemIndex, expectedOrderFormSections = @_allOrderFormSections) => updateItemsRequest = Id: offeringId expectedOrderFormSections: expectedOrderFormSections @_updateOrderForm url: @_getRemoveOfferingsURL(itemIndex, offeringId) data: JSON.stringify(updateItemsRequest) # Sends a request to add an item in the OrderForm. addToCart: (items, expectedOrderFormSections = @_allOrderFormSections, salesChannel) => addToCartRequest = orderItems: items expectedOrderFormSections: expectedOrderFormSections salesChannelQueryString = '' if salesChannel salesChannelQueryString = '?sc=' + salesChannel @_updateOrderForm url: @_getAddToCartURL() + salesChannelQueryString data: JSON.stringify addToCartRequest # Sends a request to update the items in the OrderForm. Items that are omitted are not modified. updateItems: (items, expectedOrderFormSections = @_allOrderFormSections, splitItem = true) => updateItemsRequest = orderItems: items expectedOrderFormSections: expectedOrderFormSections noSplitItem: !splitItem @_updateOrderForm url: @_getUpdateItemURL() data: JSON.stringify(updateItemsRequest) # Sends a request to remove items from the OrderForm. removeItems: (items, expectedOrderFormSections = @_allOrderFormSections) => if items and items.length is 0 return @getOrderForm(expectedOrderFormSections) itemsToRemove = [] for item, i in items itemsToRemove.push({ index: item.index, quantity: 0 }) @updateItems(itemsToRemove, expectedOrderFormSections) # Sends a request to remove all items from the OrderForm. removeAllItems: (expectedOrderFormSections = @_allOrderFormSections) => @getOrderForm(['items']).then (orderForm) => items = orderForm.items if items and items.length is 0 return orderForm itemsToRemove = [] for item, i in items itemsToRemove.push({ index: i, quantity: 0 }) @updateItems(itemsToRemove, expectedOrderFormSections) # Clone an item to one or more new items like it cloneItem: (itemIndex, newItemsOptions, expectedFormSections = @_allOrderFormSections) => @_updateOrderForm url: @_getCloneItemURL(itemIndex) data: JSON.stringify(newItemsOptions) # Sends a request to change the order of all items inside the OrderForm. changeItemsOrdination: (criteria, ascending, expectedOrderFormSections = @_allOrderFormSections) => changeItemsOrdinationRequest = criteria: criteria ascending: ascending expectedOrderFormSections: expectedOrderFormSections @_updateOrderForm url: @_getChangeOrdinationURL() data: JSON.stringify(changeItemsOrdinationRequest) # Sends a request to change the price of an item, updating manualPrice on the orderForm # Only possible if allowManualPrice is true setManualPrice: (itemIndex, manualPrice) => setManualPriceRequest = price: manualPrice @_updateOrderForm url: @_manualPriceURL(itemIndex) type: 'PUT' contentType: 'application/json; charset=utf-8' dataType: 'json' data: JSON.stringify setManualPriceRequest # Sends a request to remove the manualPrice of an item, updating manualPrice on the orderForm removeManualPrice: (itemIndex) => @_updateOrderForm url: @_manualPriceURL(itemIndex) type: 'DELETE' contentType: 'application/json; charset=utf-8' dataType: 'json' # Sends a request to add an attachment to a specific item addItemAttachment: (itemIndex, attachmentName, content, expectedFormSections = @_allOrderFormSections, splitItem = true) => dataRequest = content: content expectedOrderFormSections: expectedFormSections noSplitItem: !splitItem @_updateOrderForm url: @_getItemAttachmentURL(itemIndex, attachmentName) data: JSON.stringify(dataRequest) # Sends a request to remove an attachment of a specific item removeItemAttachment: (itemIndex, attachmentName, content, expectedFormSections = @_allOrderFormSections) => dataRequest = content: content expectedOrderFormSections: expectedFormSections @_updateOrderForm url: @_getItemAttachmentURL(itemIndex, attachmentName) type: 'DELETE' data: JSON.stringify(dataRequest) # Send a request to add an attachment to a bunle item addBundleItemAttachment: (itemIndex, bundleItemId, attachmentName, content, expectedFormSections = @_allOrderFormSections) => dataRequest = content: content expectedOrderFormSections: expectedFormSections @_updateOrderForm url: @_getBundleItemAttachmentURL(itemIndex, bundleItemId, attachmentName) data: JSON.stringify(dataRequest) # Sends a request to remove an attachmetn from a bundle item removeBundleItemAttachment: (itemIndex, bundleItemId, attachmentName, content, expectedFormSections = @_allOrderFormSections) => dataRequest = content: content expectedOrderFormSections: expectedFormSections @_updateOrderForm url: @_getBundleItemAttachmentURL(itemIndex, bundleItemId, attachmentName) type: 'DELETE' data: JSON.stringify(dataRequest) # Sends a request to add a discount coupon to the OrderForm. addDiscountCoupon: (couponCode, expectedOrderFormSections = @_allOrderFormSections) => couponCodeRequest = text: couponCode expectedOrderFormSections: expectedOrderFormSections @_updateOrderForm url: @_getAddCouponURL() data: JSON.stringify couponCodeRequest # Sends a custom data setCustomData: (params) => customData = { value: params.value } @_updateOrderForm type: 'PUT' url: @_getCustomDataUrl({ app: params.app, field: params.field, }) data: JSON.stringify customData # Sends a request to remove the discount coupon from the OrderForm. removeDiscountCoupon: (expectedOrderFormSections) => @addDiscountCoupon('', expectedOrderFormSections) # Sends a request to remove the gift registry for the current OrderForm. removeGiftRegistry: (expectedFormSections = @_allOrderFormSections) => checkoutRequest = { expectedOrderFormSections: expectedFormSections } @_updateOrderForm url: @_getRemoveGiftRegistryURL() data: JSON.stringify(checkoutRequest) # Sends a request to calculates shipping for the current OrderForm, given a COMPLETE address object. calculateShipping: (address) => @sendAttachment('shippingData', {address: address}) # Simulates shipping using a list of items, a postal code or a shippingData object, orderFormID and a country. simulateShipping: () => dataRequest = null [country, salesChannel] = [arguments[2], arguments[3]] if Array.isArray( arguments[0] ) console.warn "Calling simulateShipping with a list of items and postal code is deprecated.\n" + \ "Call it with shippingData and orderFormId instead." [items,postalCode] = [arguments[0], arguments[1]] dataRequest = items: items postalCode: postalCode country: country else [shippingData,orderFormId] = [arguments[0], arguments[1]] dataRequest = shippingData: shippingData orderFormId: orderFormId country: country salesChannelQueryString = '' if salesChannel salesChannelQueryString = '?sc=' + salesChannel @ajax url: @_getSimulationURL() + salesChannelQueryString type: 'POST' contentType: 'application/json; charset=utf-8' dataType: 'json' data: JSON.stringify(dataRequest) # Given an address with postal code and a country, retrieves a complete address, when available. getAddressInformation: (address) => @ajax url: @_getPostalCodeURL(address.postalCode, address.country) type: 'GET' timeout : 20000 # Sends a request to retrieve a user's profile. getProfileByEmail: (email, salesChannel = 1) => @ajax url: @_getProfileURL() type: 'GET' data: {email: email, sc: salesChannel} # Sends a request to start the transaction. This is the final step in the checkout process. startTransaction: (value, referenceValue, interestValue, savePersonalData = false, optinNewsLetter, expectedOrderFormSections = @_allOrderFormSections, recaptchaKey, recaptchaToken) => transactionRequest = { referenceId: @_getOrderFormId() savePersonalData: savePersonalData optinNewsLetter: optinNewsLetter value: value referenceValue: referenceValue interestValue: interestValue expectedOrderFormSections : expectedOrderFormSections recaptchaKey: recaptchaKey recaptchaToken: recaptchaToken } @_updateOrderForm url: @_startTransactionURL(), data: JSON.stringify(transactionRequest) # Sends a request to retrieve the orders for a specific orderGroupId. getOrders: (orderGroupId) => @ajax url: @_getOrdersURL(orderGroupId) type: 'GET' contentType: 'application/json; charset=utf-8' dataType: 'json' # Sends a request to clear the OrderForm messages. clearMessages: (expectedOrderFormSections = @_allOrderFormSections) => clearMessagesRequest = { expectedOrderFormSections: expectedOrderFormSections } @ajax url: @_getOrderFormURL() + '/messages/clear' type: 'POST' contentType: 'application/json; charset=utf-8' dataType: 'json' data: JSON.stringify clearMessagesRequest # Sends a request to remove a payment account from the OrderForm. removeAccountId: (accountId, expectedOrderFormSections = @_allOrderFormSections) => removeAccountIdRequest = { expectedOrderFormSections: expectedOrderFormSections } @_updateOrderForm url: @_getOrderFormURL() + '/paymentAccount/' + accountId + '/remove' data: JSON.stringify removeAccountIdRequest # URL to redirect the user to when he chooses to logout. getChangeToAnonymousUserURL: => HOST_URL + '/checkout/changeToAnonymousUser/' + @_getOrderFormId() getLogoutURL: @::getChangeToAnonymousUserURL # Replace current SKU for new SKU replaceSKU: (items, expectedOrderFormSections = @_allOrderFormSections, splitItem = true) => @_updateOrderForm({ url: @_getAddToCartURL() type: 'PATCH' data: JSON.stringify({ "orderItems": items, "expectedOrderFormSections": expectedOrderFormSections, "noSplitItem": !splitItem, }) }) # URL BUILDERS _getOrderFormId: => @_getOrderFormIdFromURL() or @orderFormId or @_getOrderFormIdFromCookie() or '' _getOrderFormIdFromCookie: => COOKIE_NAME = 'checkout.vtex.com' COOKIE_ORDER_FORM_ID_KEY = '__ofid' cookie = readCookie(COOKIE_NAME) return undefined if cookie is undefined or cookie is '' return readSubcookie(cookie, COOKIE_ORDER_FORM_ID_KEY) _getOrderFormIdFromURL: => urlParam('orderFormId') _getBaseOrderFormURL: -> HOST_URL + '/api/checkout/pub/orderForm' _getOrderFormURL: => id = @_getOrderFormId() if id is '' throw new Error "This method requires an OrderForm. Use getOrderForm beforehand." "#{@_getBaseOrderFormURL()}/#{id}" _getOrderFormURLWithId: => id = @_getOrderFormId() if id then "#{@_getBaseOrderFormURL()}/#{id}" else @_getBaseOrderFormURL() _getSaveAttachmentURL: (attachmentId) => @_getOrderFormURL() + '/attachments/' + attachmentId _getAddOfferingsURL: (itemIndex) => @_getOrderFormURL() + '/items/' + itemIndex + '/offerings' _getRemoveOfferingsURL: (itemIndex, offeringId) => @_getOrderFormURL() + '/items/' + itemIndex + '/offerings/' + offeringId + '/remove' _getBundleItemAttachmentURL: (itemIndex, bundleItemId, attachmentName) => @_getOrderFormURL() + '/items/' + itemIndex + '/bundles/' + bundleItemId + '/attachments/' + attachmentName _getItemAttachmentURL: (itemIndex, attachmentName) => @_getOrderFormURL() + '/items/' + itemIndex + '/attachments/' + attachmentName _getChangeOrdinationURL: => @_getOrderFormURL() + '/itemsOrdination' _getCustomDataUrl: (params) => @_getOrderFormURL() + '/customData/' + params.app + '/' + params.field _getAddCouponURL: => @_getOrderFormURL() + '/coupons' _startTransactionURL: => @_getOrderFormURL() + '/transaction' _getUpdateItemURL: => @_getOrderFormURL() + '/items/update/' _getCloneItemURL: (itemIndex) => @_getOrderFormURL() + '/items/' + itemIndex + '/clone' _getUpdateSelectableGifts: (list) => @_getOrderFormURL() + '/selectable-gifts/' + list _getRemoveGiftRegistryURL: => @_getBaseOrderFormURL() + "/giftRegistry/#{@_getOrderFormId()}/remove" _getAddToCartURL: => @_getOrderFormURL() + '/items' _manualPriceURL: (itemIndex) => @_getOrderFormURL() + '/items/' + itemIndex + '/price' _getOrdersURL: (orderGroupId) => HOST_URL + '/api/checkout/pub/orders/order-group/' + orderGroupId _getSimulationURL: => HOST_URL + '/api/checkout/pub/orderForms/simulation' _getPostalCodeURL: (postalCode = '', countryCode = 'BRA') => HOST_URL + '/api/checkout/pub/postal-code/' + countryCode + '/' + postalCode _getProfileURL: => HOST_URL + '/api/checkout/pub/profiles/' _getGatewayCallbackURL: => HOST_URL + '/checkout/gatewayCallback/{0}/{1}/{2}' _getFinishTransactionURL: (orderGroupId) => HOST_URL + '/api/checkout/pub/gatewayCallback/' + orderGroupId window.vtexjs or= {} window.vtexjs.Checkout = Checkout window.vtexjs.checkout = new window.vtexjs.Checkout()
35328
# UTILITY FUNCTIONS trim = (str) -> str.replace(/^\s+|\s+$/g, ''); mapize = (str, pairSeparator, keyValueSeparator, fnKey, fnValue) -> map = {} for pair in str.split(pairSeparator) [key, value...] = pair.split(keyValueSeparator) map[fnKey(key)] = fnValue(value.join('=')) return map urlParams = -> mapize(window.location.search.substring(1), '&', '=', decodeURIComponent, decodeURIComponent) urlParam = (name) -> urlParams()[name] readCookies = -> mapize(document.cookie, ';', '=', trim, unescape) readCookie = (name) -> readCookies()[name] readSubcookie = (name, cookie) -> mapize(cookie, '&', '=', ((s)->s), unescape)[name] # IE window.location.origin or= window.location.protocol + "//" + window.location.hostname + (if window.location.port then ':' + window.location.port else '') class Checkout HOST_URL = window.location.origin events = ORDER_FORM_UPDATED: 'orderFormUpdated.vtex' ATTACHMENT_UPDATED: 'attachmentUpdated.vtex' REQUEST_BEGIN: 'checkoutRequestBegin.vtex' REQUEST_END: 'checkoutRequestEnd.vtex' constructor: (options = {}) -> HOST_URL = options.hostURL if options.hostURL if options.ajax @ajax = options.ajax else if window.AjaxQueue @ajax = window.AjaxQueue($.ajax) else @ajax = $.ajax @promise = options.promise or $.when @CHECKOUT_ID = 'checkout' @orderForm = undefined @orderFormId = undefined @_pendingRequestCounter = 0 @_urlToRequestMap = {} @_allOrderFormSections = [ 'items' 'totalizers' 'clientProfileData' 'shippingData' 'paymentData' 'sellers' 'messages' 'marketingData' 'clientPreferencesData' 'storePreferencesData' 'giftRegistryData' 'ratesAndBenefitsData' 'openTextField' 'commercialConditionData', 'customData' ] ### PRIVATE METHODS ### _cacheOrderForm: (data) => @orderFormId = data.orderFormId @orderForm = data _increasePendingRequests: (options) => @_pendingRequestCounter++ $(window).trigger(events.REQUEST_BEGIN, [options]) _decreasePendingRequests: => @_pendingRequestCounter-- $(window).trigger(events.REQUEST_END, arguments) _broadcastOrderFormUnlessPendingRequests: (orderForm) => return unless @_pendingRequestCounter is 0 $(window).trigger(events.ORDER_FORM_UPDATED, [orderForm]) _orderFormHasExpectedSections: (orderForm, sections) -> if not orderForm or not orderForm instanceof Object return false for section in sections return false if not orderForm[section] return true # $.ajax wrapper with common defaults. # Used to encapsulate requests which have side effects and should broadcast results _updateOrderForm: (options) => throw new Error("options.url is required when sending request") unless options?.url # Defaults options.type or= 'POST' options.contentType or= 'application/json; charset=utf-8' options.dataType or= 'json' @_increasePendingRequests(options) xhr = @ajax(options) # Abort current call to this URL @_urlToRequestMap[options.url]?.abort() # Save this request @_urlToRequestMap[options.url] = xhr # Delete request from map upon completion xhr.always(=> delete @_urlToRequestMap[options.url]) xhr.always(@_decreasePendingRequests) xhr.done(@_cacheOrderForm) xhr.done(@_broadcastOrderFormUnlessPendingRequests) return xhr ### PUBLIC METHODS ### # Sends an idempotent request to retrieve the current OrderForm. getOrderForm: (expectedFormSections = @_allOrderFormSections) => if @_orderFormHasExpectedSections(@orderForm, expectedFormSections) return @promise(@orderForm) else checkoutRequest = { expectedOrderFormSections: expectedFormSections } xhr = @ajax url: @_getOrderFormURLWithId() + '?refreshOutdatedData=true' type: 'POST' contentType: 'application/json; charset=utf-8' dataType: 'json' data: JSON.stringify(checkoutRequest) xhr.done(@_cacheOrderForm) xhr.done(@_broadcastOrderFormUnlessPendingRequests) # Sends an OrderForm attachment to the current OrderForm, possibly updating it. sendAttachment: (attachmentId, attachment, expectedOrderFormSections = @_allOrderFormSections) => if attachmentId is undefined or attachment is undefined d = $.Deferred() d.reject("Invalid arguments") return d.promise() attachment['expectedOrderFormSections'] = expectedOrderFormSections xhr = @_updateOrderForm url: @_getSaveAttachmentURL(attachmentId) data: JSON.stringify(attachment) xhr.done((orderForm) => $(window).trigger(events.ATTACHMENT_UPDATED, [attachmentId, orderForm]) ) # Sends a request to set the used locale. sendLocale: (locale='pt-BR') => @sendAttachment('clientPreferencesData', {locale: locale}, []) # Sends orderGroupId to checkout in order to finish a transaction finishTransaction: (orderGroupId, expectedOrderFormSections = @_allOrderFormSections) => @_updateOrderForm url: @_getFinishTransactionURL(orderGroupId) # Sends a request to select an available gift updateSelectableGifts: (list, selectedGifts, expectedOrderFormSections = @_allOrderFormSections) => updateSelectableGiftsRequest = id: list selectedGifts: selectedGifts expectedOrderFormSections: expectedOrderFormSections @_updateOrderForm url: @_getUpdateSelectableGifts(list) data: JSON.stringify(updateSelectableGiftsRequest) # Sends a request to add an offering, along with its info, to the OrderForm. addOfferingWithInfo: (offeringId, offeringInfo, itemIndex, expectedOrderFormSections = @_allOrderFormSections) => updateItemsRequest = id: offeringId info: offeringInfo expectedOrderFormSections: expectedOrderFormSections @_updateOrderForm url: @_getAddOfferingsURL(itemIndex) data: JSON.stringify(updateItemsRequest) # Sends a request to add an offering to the OrderForm. addOffering: (offeringId, itemIndex, expectedOrderFormSections) => @addOfferingWithInfo(offeringId, null, itemIndex, expectedOrderFormSections) # Sends a request to remove an offering from the OrderForm. removeOffering: (offeringId, itemIndex, expectedOrderFormSections = @_allOrderFormSections) => updateItemsRequest = Id: offeringId expectedOrderFormSections: expectedOrderFormSections @_updateOrderForm url: @_getRemoveOfferingsURL(itemIndex, offeringId) data: JSON.stringify(updateItemsRequest) # Sends a request to add an item in the OrderForm. addToCart: (items, expectedOrderFormSections = @_allOrderFormSections, salesChannel) => addToCartRequest = orderItems: items expectedOrderFormSections: expectedOrderFormSections salesChannelQueryString = '' if salesChannel salesChannelQueryString = '?sc=' + salesChannel @_updateOrderForm url: @_getAddToCartURL() + salesChannelQueryString data: JSON.stringify addToCartRequest # Sends a request to update the items in the OrderForm. Items that are omitted are not modified. updateItems: (items, expectedOrderFormSections = @_allOrderFormSections, splitItem = true) => updateItemsRequest = orderItems: items expectedOrderFormSections: expectedOrderFormSections noSplitItem: !splitItem @_updateOrderForm url: @_getUpdateItemURL() data: JSON.stringify(updateItemsRequest) # Sends a request to remove items from the OrderForm. removeItems: (items, expectedOrderFormSections = @_allOrderFormSections) => if items and items.length is 0 return @getOrderForm(expectedOrderFormSections) itemsToRemove = [] for item, i in items itemsToRemove.push({ index: item.index, quantity: 0 }) @updateItems(itemsToRemove, expectedOrderFormSections) # Sends a request to remove all items from the OrderForm. removeAllItems: (expectedOrderFormSections = @_allOrderFormSections) => @getOrderForm(['items']).then (orderForm) => items = orderForm.items if items and items.length is 0 return orderForm itemsToRemove = [] for item, i in items itemsToRemove.push({ index: i, quantity: 0 }) @updateItems(itemsToRemove, expectedOrderFormSections) # Clone an item to one or more new items like it cloneItem: (itemIndex, newItemsOptions, expectedFormSections = @_allOrderFormSections) => @_updateOrderForm url: @_getCloneItemURL(itemIndex) data: JSON.stringify(newItemsOptions) # Sends a request to change the order of all items inside the OrderForm. changeItemsOrdination: (criteria, ascending, expectedOrderFormSections = @_allOrderFormSections) => changeItemsOrdinationRequest = criteria: criteria ascending: ascending expectedOrderFormSections: expectedOrderFormSections @_updateOrderForm url: @_getChangeOrdinationURL() data: JSON.stringify(changeItemsOrdinationRequest) # Sends a request to change the price of an item, updating manualPrice on the orderForm # Only possible if allowManualPrice is true setManualPrice: (itemIndex, manualPrice) => setManualPriceRequest = price: manualPrice @_updateOrderForm url: @_manualPriceURL(itemIndex) type: 'PUT' contentType: 'application/json; charset=utf-8' dataType: 'json' data: JSON.stringify setManualPriceRequest # Sends a request to remove the manualPrice of an item, updating manualPrice on the orderForm removeManualPrice: (itemIndex) => @_updateOrderForm url: @_manualPriceURL(itemIndex) type: 'DELETE' contentType: 'application/json; charset=utf-8' dataType: 'json' # Sends a request to add an attachment to a specific item addItemAttachment: (itemIndex, attachmentName, content, expectedFormSections = @_allOrderFormSections, splitItem = true) => dataRequest = content: content expectedOrderFormSections: expectedFormSections noSplitItem: !splitItem @_updateOrderForm url: @_getItemAttachmentURL(itemIndex, attachmentName) data: JSON.stringify(dataRequest) # Sends a request to remove an attachment of a specific item removeItemAttachment: (itemIndex, attachmentName, content, expectedFormSections = @_allOrderFormSections) => dataRequest = content: content expectedOrderFormSections: expectedFormSections @_updateOrderForm url: @_getItemAttachmentURL(itemIndex, attachmentName) type: 'DELETE' data: JSON.stringify(dataRequest) # Send a request to add an attachment to a bunle item addBundleItemAttachment: (itemIndex, bundleItemId, attachmentName, content, expectedFormSections = @_allOrderFormSections) => dataRequest = content: content expectedOrderFormSections: expectedFormSections @_updateOrderForm url: @_getBundleItemAttachmentURL(itemIndex, bundleItemId, attachmentName) data: JSON.stringify(dataRequest) # Sends a request to remove an attachmetn from a bundle item removeBundleItemAttachment: (itemIndex, bundleItemId, attachmentName, content, expectedFormSections = @_allOrderFormSections) => dataRequest = content: content expectedOrderFormSections: expectedFormSections @_updateOrderForm url: @_getBundleItemAttachmentURL(itemIndex, bundleItemId, attachmentName) type: 'DELETE' data: JSON.stringify(dataRequest) # Sends a request to add a discount coupon to the OrderForm. addDiscountCoupon: (couponCode, expectedOrderFormSections = @_allOrderFormSections) => couponCodeRequest = text: couponCode expectedOrderFormSections: expectedOrderFormSections @_updateOrderForm url: @_getAddCouponURL() data: JSON.stringify couponCodeRequest # Sends a custom data setCustomData: (params) => customData = { value: params.value } @_updateOrderForm type: 'PUT' url: @_getCustomDataUrl({ app: params.app, field: params.field, }) data: JSON.stringify customData # Sends a request to remove the discount coupon from the OrderForm. removeDiscountCoupon: (expectedOrderFormSections) => @addDiscountCoupon('', expectedOrderFormSections) # Sends a request to remove the gift registry for the current OrderForm. removeGiftRegistry: (expectedFormSections = @_allOrderFormSections) => checkoutRequest = { expectedOrderFormSections: expectedFormSections } @_updateOrderForm url: @_getRemoveGiftRegistryURL() data: JSON.stringify(checkoutRequest) # Sends a request to calculates shipping for the current OrderForm, given a COMPLETE address object. calculateShipping: (address) => @sendAttachment('shippingData', {address: address}) # Simulates shipping using a list of items, a postal code or a shippingData object, orderFormID and a country. simulateShipping: () => dataRequest = null [country, salesChannel] = [arguments[2], arguments[3]] if Array.isArray( arguments[0] ) console.warn "Calling simulateShipping with a list of items and postal code is deprecated.\n" + \ "Call it with shippingData and orderFormId instead." [items,postalCode] = [arguments[0], arguments[1]] dataRequest = items: items postalCode: postalCode country: country else [shippingData,orderFormId] = [arguments[0], arguments[1]] dataRequest = shippingData: shippingData orderFormId: orderFormId country: country salesChannelQueryString = '' if salesChannel salesChannelQueryString = '?sc=' + salesChannel @ajax url: @_getSimulationURL() + salesChannelQueryString type: 'POST' contentType: 'application/json; charset=utf-8' dataType: 'json' data: JSON.stringify(dataRequest) # Given an address with postal code and a country, retrieves a complete address, when available. getAddressInformation: (address) => @ajax url: @_getPostalCodeURL(address.postalCode, address.country) type: 'GET' timeout : 20000 # Sends a request to retrieve a user's profile. getProfileByEmail: (email, salesChannel = 1) => @ajax url: @_getProfileURL() type: 'GET' data: {email: email, sc: salesChannel} # Sends a request to start the transaction. This is the final step in the checkout process. startTransaction: (value, referenceValue, interestValue, savePersonalData = false, optinNewsLetter, expectedOrderFormSections = @_allOrderFormSections, recaptchaKey, recaptchaToken) => transactionRequest = { referenceId: @_getOrderFormId() savePersonalData: savePersonalData optinNewsLetter: optinNewsLetter value: value referenceValue: referenceValue interestValue: interestValue expectedOrderFormSections : expectedOrderFormSections recaptchaKey: recaptchaKey recaptchaToken: recaptchaToken } @_updateOrderForm url: @_startTransactionURL(), data: JSON.stringify(transactionRequest) # Sends a request to retrieve the orders for a specific orderGroupId. getOrders: (orderGroupId) => @ajax url: @_getOrdersURL(orderGroupId) type: 'GET' contentType: 'application/json; charset=utf-8' dataType: 'json' # Sends a request to clear the OrderForm messages. clearMessages: (expectedOrderFormSections = @_allOrderFormSections) => clearMessagesRequest = { expectedOrderFormSections: expectedOrderFormSections } @ajax url: @_getOrderFormURL() + '/messages/clear' type: 'POST' contentType: 'application/json; charset=utf-8' dataType: 'json' data: JSON.stringify clearMessagesRequest # Sends a request to remove a payment account from the OrderForm. removeAccountId: (accountId, expectedOrderFormSections = @_allOrderFormSections) => removeAccountIdRequest = { expectedOrderFormSections: expectedOrderFormSections } @_updateOrderForm url: @_getOrderFormURL() + '/paymentAccount/' + accountId + '/remove' data: JSON.stringify removeAccountIdRequest # URL to redirect the user to when he chooses to logout. getChangeToAnonymousUserURL: => HOST_URL + '/checkout/changeToAnonymousUser/' + @_getOrderFormId() getLogoutURL: @::getChangeToAnonymousUserURL # Replace current SKU for new SKU replaceSKU: (items, expectedOrderFormSections = @_allOrderFormSections, splitItem = true) => @_updateOrderForm({ url: @_getAddToCartURL() type: 'PATCH' data: JSON.stringify({ "orderItems": items, "expectedOrderFormSections": expectedOrderFormSections, "noSplitItem": !splitItem, }) }) # URL BUILDERS _getOrderFormId: => @_getOrderFormIdFromURL() or @orderFormId or @_getOrderFormIdFromCookie() or '' _getOrderFormIdFromCookie: => COOKIE_NAME = 'checkout.vtex.com' COOKIE_ORDER_FORM_ID_KEY = <KEY>' cookie = readCookie(COOKIE_NAME) return undefined if cookie is undefined or cookie is '' return readSubcookie(cookie, COOKIE_ORDER_FORM_ID_KEY) _getOrderFormIdFromURL: => urlParam('orderFormId') _getBaseOrderFormURL: -> HOST_URL + '/api/checkout/pub/orderForm' _getOrderFormURL: => id = @_getOrderFormId() if id is '' throw new Error "This method requires an OrderForm. Use getOrderForm beforehand." "#{@_getBaseOrderFormURL()}/#{id}" _getOrderFormURLWithId: => id = @_getOrderFormId() if id then "#{@_getBaseOrderFormURL()}/#{id}" else @_getBaseOrderFormURL() _getSaveAttachmentURL: (attachmentId) => @_getOrderFormURL() + '/attachments/' + attachmentId _getAddOfferingsURL: (itemIndex) => @_getOrderFormURL() + '/items/' + itemIndex + '/offerings' _getRemoveOfferingsURL: (itemIndex, offeringId) => @_getOrderFormURL() + '/items/' + itemIndex + '/offerings/' + offeringId + '/remove' _getBundleItemAttachmentURL: (itemIndex, bundleItemId, attachmentName) => @_getOrderFormURL() + '/items/' + itemIndex + '/bundles/' + bundleItemId + '/attachments/' + attachmentName _getItemAttachmentURL: (itemIndex, attachmentName) => @_getOrderFormURL() + '/items/' + itemIndex + '/attachments/' + attachmentName _getChangeOrdinationURL: => @_getOrderFormURL() + '/itemsOrdination' _getCustomDataUrl: (params) => @_getOrderFormURL() + '/customData/' + params.app + '/' + params.field _getAddCouponURL: => @_getOrderFormURL() + '/coupons' _startTransactionURL: => @_getOrderFormURL() + '/transaction' _getUpdateItemURL: => @_getOrderFormURL() + '/items/update/' _getCloneItemURL: (itemIndex) => @_getOrderFormURL() + '/items/' + itemIndex + '/clone' _getUpdateSelectableGifts: (list) => @_getOrderFormURL() + '/selectable-gifts/' + list _getRemoveGiftRegistryURL: => @_getBaseOrderFormURL() + "/giftRegistry/#{@_getOrderFormId()}/remove" _getAddToCartURL: => @_getOrderFormURL() + '/items' _manualPriceURL: (itemIndex) => @_getOrderFormURL() + '/items/' + itemIndex + '/price' _getOrdersURL: (orderGroupId) => HOST_URL + '/api/checkout/pub/orders/order-group/' + orderGroupId _getSimulationURL: => HOST_URL + '/api/checkout/pub/orderForms/simulation' _getPostalCodeURL: (postalCode = '', countryCode = 'BRA') => HOST_URL + '/api/checkout/pub/postal-code/' + countryCode + '/' + postalCode _getProfileURL: => HOST_URL + '/api/checkout/pub/profiles/' _getGatewayCallbackURL: => HOST_URL + '/checkout/gatewayCallback/{0}/{1}/{2}' _getFinishTransactionURL: (orderGroupId) => HOST_URL + '/api/checkout/pub/gatewayCallback/' + orderGroupId window.vtexjs or= {} window.vtexjs.Checkout = Checkout window.vtexjs.checkout = new window.vtexjs.Checkout()
true
# UTILITY FUNCTIONS trim = (str) -> str.replace(/^\s+|\s+$/g, ''); mapize = (str, pairSeparator, keyValueSeparator, fnKey, fnValue) -> map = {} for pair in str.split(pairSeparator) [key, value...] = pair.split(keyValueSeparator) map[fnKey(key)] = fnValue(value.join('=')) return map urlParams = -> mapize(window.location.search.substring(1), '&', '=', decodeURIComponent, decodeURIComponent) urlParam = (name) -> urlParams()[name] readCookies = -> mapize(document.cookie, ';', '=', trim, unescape) readCookie = (name) -> readCookies()[name] readSubcookie = (name, cookie) -> mapize(cookie, '&', '=', ((s)->s), unescape)[name] # IE window.location.origin or= window.location.protocol + "//" + window.location.hostname + (if window.location.port then ':' + window.location.port else '') class Checkout HOST_URL = window.location.origin events = ORDER_FORM_UPDATED: 'orderFormUpdated.vtex' ATTACHMENT_UPDATED: 'attachmentUpdated.vtex' REQUEST_BEGIN: 'checkoutRequestBegin.vtex' REQUEST_END: 'checkoutRequestEnd.vtex' constructor: (options = {}) -> HOST_URL = options.hostURL if options.hostURL if options.ajax @ajax = options.ajax else if window.AjaxQueue @ajax = window.AjaxQueue($.ajax) else @ajax = $.ajax @promise = options.promise or $.when @CHECKOUT_ID = 'checkout' @orderForm = undefined @orderFormId = undefined @_pendingRequestCounter = 0 @_urlToRequestMap = {} @_allOrderFormSections = [ 'items' 'totalizers' 'clientProfileData' 'shippingData' 'paymentData' 'sellers' 'messages' 'marketingData' 'clientPreferencesData' 'storePreferencesData' 'giftRegistryData' 'ratesAndBenefitsData' 'openTextField' 'commercialConditionData', 'customData' ] ### PRIVATE METHODS ### _cacheOrderForm: (data) => @orderFormId = data.orderFormId @orderForm = data _increasePendingRequests: (options) => @_pendingRequestCounter++ $(window).trigger(events.REQUEST_BEGIN, [options]) _decreasePendingRequests: => @_pendingRequestCounter-- $(window).trigger(events.REQUEST_END, arguments) _broadcastOrderFormUnlessPendingRequests: (orderForm) => return unless @_pendingRequestCounter is 0 $(window).trigger(events.ORDER_FORM_UPDATED, [orderForm]) _orderFormHasExpectedSections: (orderForm, sections) -> if not orderForm or not orderForm instanceof Object return false for section in sections return false if not orderForm[section] return true # $.ajax wrapper with common defaults. # Used to encapsulate requests which have side effects and should broadcast results _updateOrderForm: (options) => throw new Error("options.url is required when sending request") unless options?.url # Defaults options.type or= 'POST' options.contentType or= 'application/json; charset=utf-8' options.dataType or= 'json' @_increasePendingRequests(options) xhr = @ajax(options) # Abort current call to this URL @_urlToRequestMap[options.url]?.abort() # Save this request @_urlToRequestMap[options.url] = xhr # Delete request from map upon completion xhr.always(=> delete @_urlToRequestMap[options.url]) xhr.always(@_decreasePendingRequests) xhr.done(@_cacheOrderForm) xhr.done(@_broadcastOrderFormUnlessPendingRequests) return xhr ### PUBLIC METHODS ### # Sends an idempotent request to retrieve the current OrderForm. getOrderForm: (expectedFormSections = @_allOrderFormSections) => if @_orderFormHasExpectedSections(@orderForm, expectedFormSections) return @promise(@orderForm) else checkoutRequest = { expectedOrderFormSections: expectedFormSections } xhr = @ajax url: @_getOrderFormURLWithId() + '?refreshOutdatedData=true' type: 'POST' contentType: 'application/json; charset=utf-8' dataType: 'json' data: JSON.stringify(checkoutRequest) xhr.done(@_cacheOrderForm) xhr.done(@_broadcastOrderFormUnlessPendingRequests) # Sends an OrderForm attachment to the current OrderForm, possibly updating it. sendAttachment: (attachmentId, attachment, expectedOrderFormSections = @_allOrderFormSections) => if attachmentId is undefined or attachment is undefined d = $.Deferred() d.reject("Invalid arguments") return d.promise() attachment['expectedOrderFormSections'] = expectedOrderFormSections xhr = @_updateOrderForm url: @_getSaveAttachmentURL(attachmentId) data: JSON.stringify(attachment) xhr.done((orderForm) => $(window).trigger(events.ATTACHMENT_UPDATED, [attachmentId, orderForm]) ) # Sends a request to set the used locale. sendLocale: (locale='pt-BR') => @sendAttachment('clientPreferencesData', {locale: locale}, []) # Sends orderGroupId to checkout in order to finish a transaction finishTransaction: (orderGroupId, expectedOrderFormSections = @_allOrderFormSections) => @_updateOrderForm url: @_getFinishTransactionURL(orderGroupId) # Sends a request to select an available gift updateSelectableGifts: (list, selectedGifts, expectedOrderFormSections = @_allOrderFormSections) => updateSelectableGiftsRequest = id: list selectedGifts: selectedGifts expectedOrderFormSections: expectedOrderFormSections @_updateOrderForm url: @_getUpdateSelectableGifts(list) data: JSON.stringify(updateSelectableGiftsRequest) # Sends a request to add an offering, along with its info, to the OrderForm. addOfferingWithInfo: (offeringId, offeringInfo, itemIndex, expectedOrderFormSections = @_allOrderFormSections) => updateItemsRequest = id: offeringId info: offeringInfo expectedOrderFormSections: expectedOrderFormSections @_updateOrderForm url: @_getAddOfferingsURL(itemIndex) data: JSON.stringify(updateItemsRequest) # Sends a request to add an offering to the OrderForm. addOffering: (offeringId, itemIndex, expectedOrderFormSections) => @addOfferingWithInfo(offeringId, null, itemIndex, expectedOrderFormSections) # Sends a request to remove an offering from the OrderForm. removeOffering: (offeringId, itemIndex, expectedOrderFormSections = @_allOrderFormSections) => updateItemsRequest = Id: offeringId expectedOrderFormSections: expectedOrderFormSections @_updateOrderForm url: @_getRemoveOfferingsURL(itemIndex, offeringId) data: JSON.stringify(updateItemsRequest) # Sends a request to add an item in the OrderForm. addToCart: (items, expectedOrderFormSections = @_allOrderFormSections, salesChannel) => addToCartRequest = orderItems: items expectedOrderFormSections: expectedOrderFormSections salesChannelQueryString = '' if salesChannel salesChannelQueryString = '?sc=' + salesChannel @_updateOrderForm url: @_getAddToCartURL() + salesChannelQueryString data: JSON.stringify addToCartRequest # Sends a request to update the items in the OrderForm. Items that are omitted are not modified. updateItems: (items, expectedOrderFormSections = @_allOrderFormSections, splitItem = true) => updateItemsRequest = orderItems: items expectedOrderFormSections: expectedOrderFormSections noSplitItem: !splitItem @_updateOrderForm url: @_getUpdateItemURL() data: JSON.stringify(updateItemsRequest) # Sends a request to remove items from the OrderForm. removeItems: (items, expectedOrderFormSections = @_allOrderFormSections) => if items and items.length is 0 return @getOrderForm(expectedOrderFormSections) itemsToRemove = [] for item, i in items itemsToRemove.push({ index: item.index, quantity: 0 }) @updateItems(itemsToRemove, expectedOrderFormSections) # Sends a request to remove all items from the OrderForm. removeAllItems: (expectedOrderFormSections = @_allOrderFormSections) => @getOrderForm(['items']).then (orderForm) => items = orderForm.items if items and items.length is 0 return orderForm itemsToRemove = [] for item, i in items itemsToRemove.push({ index: i, quantity: 0 }) @updateItems(itemsToRemove, expectedOrderFormSections) # Clone an item to one or more new items like it cloneItem: (itemIndex, newItemsOptions, expectedFormSections = @_allOrderFormSections) => @_updateOrderForm url: @_getCloneItemURL(itemIndex) data: JSON.stringify(newItemsOptions) # Sends a request to change the order of all items inside the OrderForm. changeItemsOrdination: (criteria, ascending, expectedOrderFormSections = @_allOrderFormSections) => changeItemsOrdinationRequest = criteria: criteria ascending: ascending expectedOrderFormSections: expectedOrderFormSections @_updateOrderForm url: @_getChangeOrdinationURL() data: JSON.stringify(changeItemsOrdinationRequest) # Sends a request to change the price of an item, updating manualPrice on the orderForm # Only possible if allowManualPrice is true setManualPrice: (itemIndex, manualPrice) => setManualPriceRequest = price: manualPrice @_updateOrderForm url: @_manualPriceURL(itemIndex) type: 'PUT' contentType: 'application/json; charset=utf-8' dataType: 'json' data: JSON.stringify setManualPriceRequest # Sends a request to remove the manualPrice of an item, updating manualPrice on the orderForm removeManualPrice: (itemIndex) => @_updateOrderForm url: @_manualPriceURL(itemIndex) type: 'DELETE' contentType: 'application/json; charset=utf-8' dataType: 'json' # Sends a request to add an attachment to a specific item addItemAttachment: (itemIndex, attachmentName, content, expectedFormSections = @_allOrderFormSections, splitItem = true) => dataRequest = content: content expectedOrderFormSections: expectedFormSections noSplitItem: !splitItem @_updateOrderForm url: @_getItemAttachmentURL(itemIndex, attachmentName) data: JSON.stringify(dataRequest) # Sends a request to remove an attachment of a specific item removeItemAttachment: (itemIndex, attachmentName, content, expectedFormSections = @_allOrderFormSections) => dataRequest = content: content expectedOrderFormSections: expectedFormSections @_updateOrderForm url: @_getItemAttachmentURL(itemIndex, attachmentName) type: 'DELETE' data: JSON.stringify(dataRequest) # Send a request to add an attachment to a bunle item addBundleItemAttachment: (itemIndex, bundleItemId, attachmentName, content, expectedFormSections = @_allOrderFormSections) => dataRequest = content: content expectedOrderFormSections: expectedFormSections @_updateOrderForm url: @_getBundleItemAttachmentURL(itemIndex, bundleItemId, attachmentName) data: JSON.stringify(dataRequest) # Sends a request to remove an attachmetn from a bundle item removeBundleItemAttachment: (itemIndex, bundleItemId, attachmentName, content, expectedFormSections = @_allOrderFormSections) => dataRequest = content: content expectedOrderFormSections: expectedFormSections @_updateOrderForm url: @_getBundleItemAttachmentURL(itemIndex, bundleItemId, attachmentName) type: 'DELETE' data: JSON.stringify(dataRequest) # Sends a request to add a discount coupon to the OrderForm. addDiscountCoupon: (couponCode, expectedOrderFormSections = @_allOrderFormSections) => couponCodeRequest = text: couponCode expectedOrderFormSections: expectedOrderFormSections @_updateOrderForm url: @_getAddCouponURL() data: JSON.stringify couponCodeRequest # Sends a custom data setCustomData: (params) => customData = { value: params.value } @_updateOrderForm type: 'PUT' url: @_getCustomDataUrl({ app: params.app, field: params.field, }) data: JSON.stringify customData # Sends a request to remove the discount coupon from the OrderForm. removeDiscountCoupon: (expectedOrderFormSections) => @addDiscountCoupon('', expectedOrderFormSections) # Sends a request to remove the gift registry for the current OrderForm. removeGiftRegistry: (expectedFormSections = @_allOrderFormSections) => checkoutRequest = { expectedOrderFormSections: expectedFormSections } @_updateOrderForm url: @_getRemoveGiftRegistryURL() data: JSON.stringify(checkoutRequest) # Sends a request to calculates shipping for the current OrderForm, given a COMPLETE address object. calculateShipping: (address) => @sendAttachment('shippingData', {address: address}) # Simulates shipping using a list of items, a postal code or a shippingData object, orderFormID and a country. simulateShipping: () => dataRequest = null [country, salesChannel] = [arguments[2], arguments[3]] if Array.isArray( arguments[0] ) console.warn "Calling simulateShipping with a list of items and postal code is deprecated.\n" + \ "Call it with shippingData and orderFormId instead." [items,postalCode] = [arguments[0], arguments[1]] dataRequest = items: items postalCode: postalCode country: country else [shippingData,orderFormId] = [arguments[0], arguments[1]] dataRequest = shippingData: shippingData orderFormId: orderFormId country: country salesChannelQueryString = '' if salesChannel salesChannelQueryString = '?sc=' + salesChannel @ajax url: @_getSimulationURL() + salesChannelQueryString type: 'POST' contentType: 'application/json; charset=utf-8' dataType: 'json' data: JSON.stringify(dataRequest) # Given an address with postal code and a country, retrieves a complete address, when available. getAddressInformation: (address) => @ajax url: @_getPostalCodeURL(address.postalCode, address.country) type: 'GET' timeout : 20000 # Sends a request to retrieve a user's profile. getProfileByEmail: (email, salesChannel = 1) => @ajax url: @_getProfileURL() type: 'GET' data: {email: email, sc: salesChannel} # Sends a request to start the transaction. This is the final step in the checkout process. startTransaction: (value, referenceValue, interestValue, savePersonalData = false, optinNewsLetter, expectedOrderFormSections = @_allOrderFormSections, recaptchaKey, recaptchaToken) => transactionRequest = { referenceId: @_getOrderFormId() savePersonalData: savePersonalData optinNewsLetter: optinNewsLetter value: value referenceValue: referenceValue interestValue: interestValue expectedOrderFormSections : expectedOrderFormSections recaptchaKey: recaptchaKey recaptchaToken: recaptchaToken } @_updateOrderForm url: @_startTransactionURL(), data: JSON.stringify(transactionRequest) # Sends a request to retrieve the orders for a specific orderGroupId. getOrders: (orderGroupId) => @ajax url: @_getOrdersURL(orderGroupId) type: 'GET' contentType: 'application/json; charset=utf-8' dataType: 'json' # Sends a request to clear the OrderForm messages. clearMessages: (expectedOrderFormSections = @_allOrderFormSections) => clearMessagesRequest = { expectedOrderFormSections: expectedOrderFormSections } @ajax url: @_getOrderFormURL() + '/messages/clear' type: 'POST' contentType: 'application/json; charset=utf-8' dataType: 'json' data: JSON.stringify clearMessagesRequest # Sends a request to remove a payment account from the OrderForm. removeAccountId: (accountId, expectedOrderFormSections = @_allOrderFormSections) => removeAccountIdRequest = { expectedOrderFormSections: expectedOrderFormSections } @_updateOrderForm url: @_getOrderFormURL() + '/paymentAccount/' + accountId + '/remove' data: JSON.stringify removeAccountIdRequest # URL to redirect the user to when he chooses to logout. getChangeToAnonymousUserURL: => HOST_URL + '/checkout/changeToAnonymousUser/' + @_getOrderFormId() getLogoutURL: @::getChangeToAnonymousUserURL # Replace current SKU for new SKU replaceSKU: (items, expectedOrderFormSections = @_allOrderFormSections, splitItem = true) => @_updateOrderForm({ url: @_getAddToCartURL() type: 'PATCH' data: JSON.stringify({ "orderItems": items, "expectedOrderFormSections": expectedOrderFormSections, "noSplitItem": !splitItem, }) }) # URL BUILDERS _getOrderFormId: => @_getOrderFormIdFromURL() or @orderFormId or @_getOrderFormIdFromCookie() or '' _getOrderFormIdFromCookie: => COOKIE_NAME = 'checkout.vtex.com' COOKIE_ORDER_FORM_ID_KEY = PI:KEY:<KEY>END_PI' cookie = readCookie(COOKIE_NAME) return undefined if cookie is undefined or cookie is '' return readSubcookie(cookie, COOKIE_ORDER_FORM_ID_KEY) _getOrderFormIdFromURL: => urlParam('orderFormId') _getBaseOrderFormURL: -> HOST_URL + '/api/checkout/pub/orderForm' _getOrderFormURL: => id = @_getOrderFormId() if id is '' throw new Error "This method requires an OrderForm. Use getOrderForm beforehand." "#{@_getBaseOrderFormURL()}/#{id}" _getOrderFormURLWithId: => id = @_getOrderFormId() if id then "#{@_getBaseOrderFormURL()}/#{id}" else @_getBaseOrderFormURL() _getSaveAttachmentURL: (attachmentId) => @_getOrderFormURL() + '/attachments/' + attachmentId _getAddOfferingsURL: (itemIndex) => @_getOrderFormURL() + '/items/' + itemIndex + '/offerings' _getRemoveOfferingsURL: (itemIndex, offeringId) => @_getOrderFormURL() + '/items/' + itemIndex + '/offerings/' + offeringId + '/remove' _getBundleItemAttachmentURL: (itemIndex, bundleItemId, attachmentName) => @_getOrderFormURL() + '/items/' + itemIndex + '/bundles/' + bundleItemId + '/attachments/' + attachmentName _getItemAttachmentURL: (itemIndex, attachmentName) => @_getOrderFormURL() + '/items/' + itemIndex + '/attachments/' + attachmentName _getChangeOrdinationURL: => @_getOrderFormURL() + '/itemsOrdination' _getCustomDataUrl: (params) => @_getOrderFormURL() + '/customData/' + params.app + '/' + params.field _getAddCouponURL: => @_getOrderFormURL() + '/coupons' _startTransactionURL: => @_getOrderFormURL() + '/transaction' _getUpdateItemURL: => @_getOrderFormURL() + '/items/update/' _getCloneItemURL: (itemIndex) => @_getOrderFormURL() + '/items/' + itemIndex + '/clone' _getUpdateSelectableGifts: (list) => @_getOrderFormURL() + '/selectable-gifts/' + list _getRemoveGiftRegistryURL: => @_getBaseOrderFormURL() + "/giftRegistry/#{@_getOrderFormId()}/remove" _getAddToCartURL: => @_getOrderFormURL() + '/items' _manualPriceURL: (itemIndex) => @_getOrderFormURL() + '/items/' + itemIndex + '/price' _getOrdersURL: (orderGroupId) => HOST_URL + '/api/checkout/pub/orders/order-group/' + orderGroupId _getSimulationURL: => HOST_URL + '/api/checkout/pub/orderForms/simulation' _getPostalCodeURL: (postalCode = '', countryCode = 'BRA') => HOST_URL + '/api/checkout/pub/postal-code/' + countryCode + '/' + postalCode _getProfileURL: => HOST_URL + '/api/checkout/pub/profiles/' _getGatewayCallbackURL: => HOST_URL + '/checkout/gatewayCallback/{0}/{1}/{2}' _getFinishTransactionURL: (orderGroupId) => HOST_URL + '/api/checkout/pub/gatewayCallback/' + orderGroupId window.vtexjs or= {} window.vtexjs.Checkout = Checkout window.vtexjs.checkout = new window.vtexjs.Checkout()
[ { "context": "tle\": \"Home\"\n\"search\":\n \"inputPlaceholder\": \"Szukaj\"\n \"title\": \"Szukaj\"\n \"titleQuery\": \"Szukaj:", "end": 1227, "score": 0.6620312929153442, "start": 1223, "tag": "NAME", "value": "ukaj" }, { "context": "\":\n \"inputPlaceholder\": \"Szuka...
src/i18n/pl.cson
Intraktio/hybrid
2
PULL_TO_REFRESH: "Pociągnij aby odświeżyć." RETRY: "Spróbuj ponownie." CANCEL: "Cancel" SUBMIT: "Submit" BACK: "Powrót" ERROR: "O nie! Stało się coś strasznego! Spróbuj ponownie.." ATTEMPT_TO_CONNECT: "{{attempt}} próba połączenia z {{attemptMax}}." OK: "Ok" YES: "Tak" NO: "Nie" EMPTY_LIST: "Nic tu nie ma!" MENU: "Menu" HOME: "Home" TAGS: "Tagi" PAGES: "Pages" AUTHORS: "Authors" POSTS: "Posts" SEARCH: "Szukaj" SOCIAL_NETWORKS: "Społeczności" CATEGORIES: "Kategorie" SETTINGS: "Ustawienia" CUSTOM_POSTS: "Custom posts" CUSTOM_TAXO: "Custom Taxonomy" CUSTOM_TAXO_TITLE: "{{term}}: {{name}}" PUSH_NOTIFS: "Push notifications" PUSH_NOTIF_TITLE: "Coś nowego!" PUSH_NOTIF_TEXT: "Hej! W {{appTitle}} właśnie pojawiło się coś nowego: '{{postTitle}}' stuknij aby otworzyć." BOOKMARKS: "Zakładki" BOOKMARKS_EMPTY: "Nic tu jeszcze nie ma. Śmiało, dodaj coś." BOOKMARK_ADDED: "Słodko. Dodano do zakładek!" BOOKMARK_REMOVED: "Zakładka usunięta!" ZOOM: "Zoom" CACHE_CLEAR: "Clear cache" CACHE_CLEARED: "Cache cleared" "tags": "title": "Tagi" "tag": "title": "Tag: {{name}}" "categories": "title": "Kategorie" "category": "title": "Kategoria: {{name}}" "home": "title": "Home" "search": "inputPlaceholder": "Szukaj" "title": "Szukaj" "titleQuery": "Szukaj: {{query}}" "sharing": "shared": "Udostępniono!" AUTHORS: "Authors" AUTHOR: "Author" AUTHOR_TITLE: "Author: {{name}}" "pages": "title": "Pages" "posts": "title": "Posts" "featured": "Wyróżnione" "post": "comments": "Komentarze" "openInBrowser": "Otwórz w przeglądarce" "about": "title": "Info" "languages": "en": "English" "fr": "French" "zh": "Chinese" "es": "Spanish" "pl": "Polski" "de": "Niemiecki" "pt": "Portugalski" "it": "Włoski" "nl": "Holenderski"
144258
PULL_TO_REFRESH: "Pociągnij aby odświeżyć." RETRY: "Spróbuj ponownie." CANCEL: "Cancel" SUBMIT: "Submit" BACK: "Powrót" ERROR: "O nie! Stało się coś strasznego! Spróbuj ponownie.." ATTEMPT_TO_CONNECT: "{{attempt}} próba połączenia z {{attemptMax}}." OK: "Ok" YES: "Tak" NO: "Nie" EMPTY_LIST: "Nic tu nie ma!" MENU: "Menu" HOME: "Home" TAGS: "Tagi" PAGES: "Pages" AUTHORS: "Authors" POSTS: "Posts" SEARCH: "Szukaj" SOCIAL_NETWORKS: "Społeczności" CATEGORIES: "Kategorie" SETTINGS: "Ustawienia" CUSTOM_POSTS: "Custom posts" CUSTOM_TAXO: "Custom Taxonomy" CUSTOM_TAXO_TITLE: "{{term}}: {{name}}" PUSH_NOTIFS: "Push notifications" PUSH_NOTIF_TITLE: "Coś nowego!" PUSH_NOTIF_TEXT: "Hej! W {{appTitle}} właśnie pojawiło się coś nowego: '{{postTitle}}' stuknij aby otworzyć." BOOKMARKS: "Zakładki" BOOKMARKS_EMPTY: "Nic tu jeszcze nie ma. Śmiało, dodaj coś." BOOKMARK_ADDED: "Słodko. Dodano do zakładek!" BOOKMARK_REMOVED: "Zakładka usunięta!" ZOOM: "Zoom" CACHE_CLEAR: "Clear cache" CACHE_CLEARED: "Cache cleared" "tags": "title": "Tagi" "tag": "title": "Tag: {{name}}" "categories": "title": "Kategorie" "category": "title": "Kategoria: {{name}}" "home": "title": "Home" "search": "inputPlaceholder": "Sz<NAME>" "title": "<NAME>" "titleQuery": "Szukaj: {{query}}" "sharing": "shared": "Udostępniono!" AUTHORS: "Authors" AUTHOR: "Author" AUTHOR_TITLE: "Author: {{name}}" "pages": "title": "Pages" "posts": "title": "Posts" "featured": "Wyróżnione" "post": "comments": "Komentarze" "openInBrowser": "Otwórz w przeglądarce" "about": "title": "Info" "languages": "en": "English" "fr": "French" "zh": "Chinese" "es": "Spanish" "pl": "Polski" "de": "Niemiecki" "pt": "Portugalski" "it": "Włoski" "nl": "Holenderski"
true
PULL_TO_REFRESH: "Pociągnij aby odświeżyć." RETRY: "Spróbuj ponownie." CANCEL: "Cancel" SUBMIT: "Submit" BACK: "Powrót" ERROR: "O nie! Stało się coś strasznego! Spróbuj ponownie.." ATTEMPT_TO_CONNECT: "{{attempt}} próba połączenia z {{attemptMax}}." OK: "Ok" YES: "Tak" NO: "Nie" EMPTY_LIST: "Nic tu nie ma!" MENU: "Menu" HOME: "Home" TAGS: "Tagi" PAGES: "Pages" AUTHORS: "Authors" POSTS: "Posts" SEARCH: "Szukaj" SOCIAL_NETWORKS: "Społeczności" CATEGORIES: "Kategorie" SETTINGS: "Ustawienia" CUSTOM_POSTS: "Custom posts" CUSTOM_TAXO: "Custom Taxonomy" CUSTOM_TAXO_TITLE: "{{term}}: {{name}}" PUSH_NOTIFS: "Push notifications" PUSH_NOTIF_TITLE: "Coś nowego!" PUSH_NOTIF_TEXT: "Hej! W {{appTitle}} właśnie pojawiło się coś nowego: '{{postTitle}}' stuknij aby otworzyć." BOOKMARKS: "Zakładki" BOOKMARKS_EMPTY: "Nic tu jeszcze nie ma. Śmiało, dodaj coś." BOOKMARK_ADDED: "Słodko. Dodano do zakładek!" BOOKMARK_REMOVED: "Zakładka usunięta!" ZOOM: "Zoom" CACHE_CLEAR: "Clear cache" CACHE_CLEARED: "Cache cleared" "tags": "title": "Tagi" "tag": "title": "Tag: {{name}}" "categories": "title": "Kategorie" "category": "title": "Kategoria: {{name}}" "home": "title": "Home" "search": "inputPlaceholder": "SzPI:NAME:<NAME>END_PI" "title": "PI:NAME:<NAME>END_PI" "titleQuery": "Szukaj: {{query}}" "sharing": "shared": "Udostępniono!" AUTHORS: "Authors" AUTHOR: "Author" AUTHOR_TITLE: "Author: {{name}}" "pages": "title": "Pages" "posts": "title": "Posts" "featured": "Wyróżnione" "post": "comments": "Komentarze" "openInBrowser": "Otwórz w przeglądarce" "about": "title": "Info" "languages": "en": "English" "fr": "French" "zh": "Chinese" "es": "Spanish" "pl": "Polski" "de": "Niemiecki" "pt": "Portugalski" "it": "Włoski" "nl": "Holenderski"
[ { "context": "t-er-animating\n# requestAnimationFrame polyfill by Erik Möller\n# fixes from Paul Irish and Tino Zijdel\n\nlastTime", "end": 209, "score": 0.9999015927314758, "start": 198, "tag": "NAME", "value": "Erik Möller" }, { "context": "nimationFrame polyfill by Erik Möller\n# ...
app/src/helpers.coffee
concord-consortium/genigames
0
# http://paulirish.com/2011/requestanimationframe-for-smart-animating/ # http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating # requestAnimationFrame polyfill by Erik Möller # fixes from Paul Irish and Tino Zijdel lastTime = 0; vendors = ['ms', 'moz', 'webkit', 'o']; while !window.requestAnimationFrame && vendor = vendors.pop() window.requestAnimationFrame = window[vendor+'RequestAnimationFrame'] window.cancelAnimationFrame = window[vendor+'CancelAnimationFrame'] || window[vendor+'CancelRequestAnimationFrame'] if !window.requestAnimationFrame window.requestAnimationFrame = (callback, element) -> currTime = new Date().getTime() timeToCall = Math.max(0, 16 - (currTime - lastTime)) id = window.setTimeout -> callback(currTime + timeToCall) , timeToCall lastTime = currTime + timeToCall return id if !window.cancelAnimationFrame window.cancelAnimationFrame = (id) -> clearTimeout id # Add show/hide triggers to elements (($) -> $.each(['show','hide'], (i, val) -> _org = $.fn[val] $.fn[val] = -> this.trigger(val) _org.apply(this, arguments) ) )(jQuery)
81076
# http://paulirish.com/2011/requestanimationframe-for-smart-animating/ # http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating # requestAnimationFrame polyfill by <NAME> # fixes from <NAME> and <NAME> lastTime = 0; vendors = ['ms', 'moz', 'webkit', 'o']; while !window.requestAnimationFrame && vendor = vendors.pop() window.requestAnimationFrame = window[vendor+'RequestAnimationFrame'] window.cancelAnimationFrame = window[vendor+'CancelAnimationFrame'] || window[vendor+'CancelRequestAnimationFrame'] if !window.requestAnimationFrame window.requestAnimationFrame = (callback, element) -> currTime = new Date().getTime() timeToCall = Math.max(0, 16 - (currTime - lastTime)) id = window.setTimeout -> callback(currTime + timeToCall) , timeToCall lastTime = currTime + timeToCall return id if !window.cancelAnimationFrame window.cancelAnimationFrame = (id) -> clearTimeout id # Add show/hide triggers to elements (($) -> $.each(['show','hide'], (i, val) -> _org = $.fn[val] $.fn[val] = -> this.trigger(val) _org.apply(this, arguments) ) )(jQuery)
true
# http://paulirish.com/2011/requestanimationframe-for-smart-animating/ # http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating # requestAnimationFrame polyfill by PI:NAME:<NAME>END_PI # fixes from PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI lastTime = 0; vendors = ['ms', 'moz', 'webkit', 'o']; while !window.requestAnimationFrame && vendor = vendors.pop() window.requestAnimationFrame = window[vendor+'RequestAnimationFrame'] window.cancelAnimationFrame = window[vendor+'CancelAnimationFrame'] || window[vendor+'CancelRequestAnimationFrame'] if !window.requestAnimationFrame window.requestAnimationFrame = (callback, element) -> currTime = new Date().getTime() timeToCall = Math.max(0, 16 - (currTime - lastTime)) id = window.setTimeout -> callback(currTime + timeToCall) , timeToCall lastTime = currTime + timeToCall return id if !window.cancelAnimationFrame window.cancelAnimationFrame = (id) -> clearTimeout id # Add show/hide triggers to elements (($) -> $.each(['show','hide'], (i, val) -> _org = $.fn[val] $.fn[val] = -> this.trigger(val) _org.apply(this, arguments) ) )(jQuery)
[ { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ", "end": 38, "score": 0.9998858571052551, "start": 25, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright...
public/taiga-front/app/coffee/modules/base/urls.coffee
mabotech/maboss
0
### # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com> # Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/base/http.coffee ### format = (fmt, obj) -> obj = _.clone(obj) return fmt.replace /%s/g, (match) -> String(obj.shift()) taiga = @.taiga class UrlsService extends taiga.Service @.$inject = ["$tgConfig"] constructor: (@config) -> @.urls = {} @.mainUrl = config.get("api") update: (urls) -> @.urls = _.merge(@.urls, urls) resolve: -> args = _.toArray(arguments) if args.length == 0 throw Error("wrong arguments to setUrls") name = args.slice(0, 1)[0] url = format(@.urls[name], args.slice(1)) return format("%s/%s", [ _.str.rtrim(@.mainUrl, "/"), _.str.ltrim(url, "/") ]) module = angular.module("taigaBase") module.service('$tgUrls', UrlsService)
29602
### # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/base/http.coffee ### format = (fmt, obj) -> obj = _.clone(obj) return fmt.replace /%s/g, (match) -> String(obj.shift()) taiga = @.taiga class UrlsService extends taiga.Service @.$inject = ["$tgConfig"] constructor: (@config) -> @.urls = {} @.mainUrl = config.get("api") update: (urls) -> @.urls = _.merge(@.urls, urls) resolve: -> args = _.toArray(arguments) if args.length == 0 throw Error("wrong arguments to setUrls") name = args.slice(0, 1)[0] url = format(@.urls[name], args.slice(1)) return format("%s/%s", [ _.str.rtrim(@.mainUrl, "/"), _.str.ltrim(url, "/") ]) module = angular.module("taigaBase") module.service('$tgUrls', UrlsService)
true
### # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/base/http.coffee ### format = (fmt, obj) -> obj = _.clone(obj) return fmt.replace /%s/g, (match) -> String(obj.shift()) taiga = @.taiga class UrlsService extends taiga.Service @.$inject = ["$tgConfig"] constructor: (@config) -> @.urls = {} @.mainUrl = config.get("api") update: (urls) -> @.urls = _.merge(@.urls, urls) resolve: -> args = _.toArray(arguments) if args.length == 0 throw Error("wrong arguments to setUrls") name = args.slice(0, 1)[0] url = format(@.urls[name], args.slice(1)) return format("%s/%s", [ _.str.rtrim(@.mainUrl, "/"), _.str.ltrim(url, "/") ]) module = angular.module("taigaBase") module.service('$tgUrls', UrlsService)
[ { "context": "\n modelKey: 'clientId'\n jsonKey: 'client_id'\n\n 'serverId': Attributes.ServerId\n model", "end": 313, "score": 0.9122720956802368, "start": 311, "tag": "KEY", "value": "id" } ]
app/src/flux/models/json-blob.coffee
immershy/nodemail
0
_ = require 'underscore' Model = require './model' Attributes = require '../attributes' class JSONBlob extends Model @attributes: 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String queryable: true modelKey: 'clientId' jsonKey: 'client_id' 'serverId': Attributes.ServerId modelKey: 'serverId' jsonKey: 'server_id' 'json': Attributes.Object modelKey: 'json' jsonKey: 'json' Object.defineProperty @prototype, 'key', get: -> @serverId set: (val) -> @serverId = val Object.defineProperty @prototype, 'clientId', get: -> @serverId set: (val) -> @serverId = val module.exports = JSONBlob
105188
_ = require 'underscore' Model = require './model' Attributes = require '../attributes' class JSONBlob extends Model @attributes: 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String queryable: true modelKey: 'clientId' jsonKey: 'client_<KEY>' 'serverId': Attributes.ServerId modelKey: 'serverId' jsonKey: 'server_id' 'json': Attributes.Object modelKey: 'json' jsonKey: 'json' Object.defineProperty @prototype, 'key', get: -> @serverId set: (val) -> @serverId = val Object.defineProperty @prototype, 'clientId', get: -> @serverId set: (val) -> @serverId = val module.exports = JSONBlob
true
_ = require 'underscore' Model = require './model' Attributes = require '../attributes' class JSONBlob extends Model @attributes: 'id': Attributes.String queryable: true modelKey: 'id' 'clientId': Attributes.String queryable: true modelKey: 'clientId' jsonKey: 'client_PI:KEY:<KEY>END_PI' 'serverId': Attributes.ServerId modelKey: 'serverId' jsonKey: 'server_id' 'json': Attributes.Object modelKey: 'json' jsonKey: 'json' Object.defineProperty @prototype, 'key', get: -> @serverId set: (val) -> @serverId = val Object.defineProperty @prototype, 'clientId', get: -> @serverId set: (val) -> @serverId = val module.exports = JSONBlob
[ { "context": "s\",\"Prov\",\"Eccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"", "end": 505, "score": 0.7930361032485962, "start": 502, "tag": "NAME", "value": "Dan" }, { "context": "ov\",\"Eccl\",\"Song\",\"Isa\"...
lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/so/spec.coffee
saiba-mais/bible-lessons
149
bcv_parser = require("../../js/so_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 (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Bilowgii 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Bil 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1") p.include_apocrypha(false) expect(p.parse("BILOWGII 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("BIL 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1") ` true describe "Localized book Exod (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Baxniintii 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Bax 1:1").osis()).toEqual("Exod.1.1") p.include_apocrypha(false) expect(p.parse("BAXNIINTII 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("BAX 1:1").osis()).toEqual("Exod.1.1") ` true describe "Localized book Bel (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1") ` true describe "Localized book Lev (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Laawiyiintii 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Laaw 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1") p.include_apocrypha(false) expect(p.parse("LAAWIYIINTII 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LAAW 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1") ` true describe "Localized book Num (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Tirintii 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Tir 1:1").osis()).toEqual("Num.1.1") p.include_apocrypha(false) expect(p.parse("TIRINTII 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1") expect(p.parse("TIR 1:1").osis()).toEqual("Num.1.1") ` true describe "Localized book Sir (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1") ` true describe "Localized book Wis (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1") ` true describe "Localized book Lam (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Baroorashadii Yeremyaah 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Baroorashadii 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Baroor 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1") p.include_apocrypha(false) expect(p.parse("BAROORASHADII YEREMYAAH 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("BAROORASHADII 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("BAROOR 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1") ` true describe "Localized book EpJer (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1") ` true describe "Localized book Rev (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Muujintii 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Muuj 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1") p.include_apocrypha(false) expect(p.parse("MUUJINTII 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("MUUJ 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1") ` true describe "Localized book PrMan (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1") ` true describe "Localized book Deut (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sharciga Kunoqoshadiisa 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Sharci 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1") p.include_apocrypha(false) expect(p.parse("SHARCIGA KUNOQOSHADIISA 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("SHARCI 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1") ` true describe "Localized book Josh (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yashuuca 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Yash 1:1").osis()).toEqual("Josh.1.1") p.include_apocrypha(false) expect(p.parse("YASHUUCA 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("YASH 1:1").osis()).toEqual("Josh.1.1") ` true describe "Localized book Judg (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Xaakinnada 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Xaak 1:1").osis()).toEqual("Judg.1.1") p.include_apocrypha(false) expect(p.parse("XAAKINNADA 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("XAAK 1:1").osis()).toEqual("Judg.1.1") ` true describe "Localized book Ruth (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruud 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("RUUD 1:1").osis()).toEqual("Ruth.1.1") ` true describe "Localized book 1Esd (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1") ` true describe "Localized book 2Esd (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1") ` true describe "Localized book Isa (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Ishacyaah 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Ish 1:1").osis()).toEqual("Isa.1.1") p.include_apocrypha(false) expect(p.parse("ISHACYAAH 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISH 1:1").osis()).toEqual("Isa.1.1") ` true describe "Localized book 2Sam (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Samuu'eel Labaad 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Samuu’eel Labaad 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Samuu'eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Samuu’eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Samuu'eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Samuu’eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Samuu'eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Samuu’eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Samuu'eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Samuu’eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1") p.include_apocrypha(false) expect(p.parse("SAMUU'EEL LABAAD 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SAMUU’EEL LABAAD 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAMUU'EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAMUU’EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAMUU'EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAMUU’EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAMUU'EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAMUU’EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAMUU'EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAMUU’EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1") ` true describe "Localized book 1Sam (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Samuu'eel Kowaad 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Samuu’eel Kowaad 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Samuu'eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Samuu’eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. Samuu'eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. Samuu’eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Samuu'eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Samuu’eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Samuu'eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Samuu’eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1") p.include_apocrypha(false) expect(p.parse("SAMUU'EEL KOWAAD 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("SAMUU’EEL KOWAAD 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAMUU'EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAMUU’EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAMUU'EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAMUU’EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAMUU'EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAMUU’EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAMUU'EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAMUU’EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1") ` true describe "Localized book 2Kgs (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Boqorradii Labaad 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. Boqorradii 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. Boqorradii 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II Boqorradii 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Boqorradii 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. Boq 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. Boq 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II Boq 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Boq 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1") p.include_apocrypha(false) expect(p.parse("BOQORRADII LABAAD 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. BOQORRADII 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. BOQORRADII 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II BOQORRADII 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 BOQORRADII 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. BOQ 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. BOQ 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II BOQ 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 BOQ 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1") ` true describe "Localized book 1Kgs (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Boqorradii Kowaad 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. Boqorradii 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. Boqorradii 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Boqorradii 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I Boqorradii 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. Boq 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. Boq 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Boq 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I Boq 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1") p.include_apocrypha(false) expect(p.parse("BOQORRADII KOWAAD 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. BOQORRADII 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. BOQORRADII 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 BOQORRADII 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I BOQORRADII 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. BOQ 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. BOQ 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 BOQ 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I BOQ 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1") ` true describe "Localized book 2Chr (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Taariikhdii Labaad 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. Taariikhdii 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. Taariikhdii 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II Taariikhdii 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Taariikhdii 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. Taar 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. Taar 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II Taar 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Taar 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("TAARIIKHDII LABAAD 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. TAARIIKHDII 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. TAARIIKHDII 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II TAARIIKHDII 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 TAARIIKHDII 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. TAAR 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. TAAR 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II TAAR 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 TAAR 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1") ` true describe "Localized book 1Chr (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Taariikhdii Kowaad 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. Taariikhdii 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. Taariikhdii 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Taariikhdii 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I Taariikhdii 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. Taar 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. Taar 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Taar 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I Taar 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("TAARIIKHDII KOWAAD 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. TAARIIKHDII 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. TAARIIKHDII 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 TAARIIKHDII 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I TAARIIKHDII 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. TAAR 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. TAAR 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 TAAR 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I TAAR 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1") ` true describe "Localized book Ezra (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Cesraa 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Cesr 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ces 1:1").osis()).toEqual("Ezra.1.1") p.include_apocrypha(false) expect(p.parse("CESRAA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("CESR 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("CES 1:1").osis()).toEqual("Ezra.1.1") ` true describe "Localized book Neh (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Nexemyaah 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Nex 1:1").osis()).toEqual("Neh.1.1") p.include_apocrypha(false) expect(p.parse("NEXEMYAAH 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEX 1:1").osis()).toEqual("Neh.1.1") ` true describe "Localized book GkEsth (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1") ` true describe "Localized book Esth (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Esteer 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1") p.include_apocrypha(false) expect(p.parse("ESTEER 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1") ` true describe "Localized book Job (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Ayuub 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Ayu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1") p.include_apocrypha(false) expect(p.parse("AYUUB 1:1").osis()).toEqual("Job.1.1") expect(p.parse("AYU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1") ` true describe "Localized book Ps (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sabuurradii 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Sabuur 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Sab 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1") p.include_apocrypha(false) expect(p.parse("SABUURRADII 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("SABUUR 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("SAB 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1") ` true describe "Localized book PrAzar (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1") ` true describe "Localized book Prov (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Maahmaahyadii 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Maah 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1") p.include_apocrypha(false) expect(p.parse("MAAHMAAHYADII 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("MAAH 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1") ` true describe "Localized book Eccl (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Wacdiyahii 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Wacdiyaha 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Wac 1:1").osis()).toEqual("Eccl.1.1") p.include_apocrypha(false) expect(p.parse("WACDIYAHII 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("WACDIYAHA 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("WAC 1:1").osis()).toEqual("Eccl.1.1") ` true describe "Localized book SgThree (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1") ` true describe "Localized book Song (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Gabaygii Sulaymaan 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Gabaygii 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Gab 1:1").osis()).toEqual("Song.1.1") p.include_apocrypha(false) expect(p.parse("GABAYGII SULAYMAAN 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GABAYGII 1:1").osis()).toEqual("Song.1.1") expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GAB 1:1").osis()).toEqual("Song.1.1") ` true describe "Localized book Jer (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yeremyaah 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Yer 1:1").osis()).toEqual("Jer.1.1") p.include_apocrypha(false) expect(p.parse("YEREMYAAH 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("YER 1:1").osis()).toEqual("Jer.1.1") ` true describe "Localized book Ezek (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yexesqeel 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Yex 1:1").osis()).toEqual("Ezek.1.1") p.include_apocrypha(false) expect(p.parse("YEXESQEEL 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("YEX 1:1").osis()).toEqual("Ezek.1.1") ` true describe "Localized book Dan (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Daanyeel 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Daan 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1") p.include_apocrypha(false) expect(p.parse("DAANYEEL 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAAN 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1") ` true describe "Localized book Hos (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Hoosheeca 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hoosh 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1") p.include_apocrypha(false) expect(p.parse("HOOSHEECA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOOSH 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1") ` true describe "Localized book Joel (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yoo'eel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Yoo’eel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Yool 1:1").osis()).toEqual("Joel.1.1") p.include_apocrypha(false) expect(p.parse("YOO'EEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("YOO’EEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("YOOL 1:1").osis()).toEqual("Joel.1.1") ` true describe "Localized book Amos (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Caamoos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Caam 1:1").osis()).toEqual("Amos.1.1") p.include_apocrypha(false) expect(p.parse("CAAMOOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("CAAM 1:1").osis()).toEqual("Amos.1.1") ` true describe "Localized book Obad (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Cobadyaah 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Cobad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Cob 1:1").osis()).toEqual("Obad.1.1") p.include_apocrypha(false) expect(p.parse("COBADYAAH 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("COBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("COB 1:1").osis()).toEqual("Obad.1.1") ` true describe "Localized book Jonah (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yoonis 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Jonah 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Yoon 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("YOONIS 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("YOON 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book Mic (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Miikaah 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Miik 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1") p.include_apocrypha(false) expect(p.parse("MIIKAAH 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIIK 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1") ` true describe "Localized book Nah (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Naxuum 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nax 1:1").osis()).toEqual("Nah.1.1") p.include_apocrypha(false) expect(p.parse("NAXUUM 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAX 1:1").osis()).toEqual("Nah.1.1") ` true describe "Localized book Hab (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Xabaquuq 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Xab 1:1").osis()).toEqual("Hab.1.1") p.include_apocrypha(false) expect(p.parse("XABAQUUQ 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("XAB 1:1").osis()).toEqual("Hab.1.1") ` true describe "Localized book Zeph (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sefanyaah 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sef 1:1").osis()).toEqual("Zeph.1.1") p.include_apocrypha(false) expect(p.parse("SEFANYAAH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SEF 1:1").osis()).toEqual("Zeph.1.1") ` true describe "Localized book Hag (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Xaggay 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Xagg 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Xag 1:1").osis()).toEqual("Hag.1.1") p.include_apocrypha(false) expect(p.parse("XAGGAY 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("XAGG 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("XAG 1:1").osis()).toEqual("Hag.1.1") ` true describe "Localized book Zech (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sekaryaah 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Sek 1:1").osis()).toEqual("Zech.1.1") p.include_apocrypha(false) expect(p.parse("SEKARYAAH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("SEK 1:1").osis()).toEqual("Zech.1.1") ` true describe "Localized book Mal (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Malaakii 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1") p.include_apocrypha(false) expect(p.parse("MALAAKII 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1") ` true describe "Localized book Matt (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Matayos 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") p.include_apocrypha(false) expect(p.parse("MATAYOS 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") ` true describe "Localized book Mark (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Markos 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") p.include_apocrypha(false) expect(p.parse("MARKOS 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") ` true describe "Localized book Luke (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Luukos 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luuk 1:1").osis()).toEqual("Luke.1.1") p.include_apocrypha(false) expect(p.parse("LUUKOS 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUUK 1:1").osis()).toEqual("Luke.1.1") ` true describe "Localized book 1John (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yooxanaa Kowaad 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Yooxanaa 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Yooxanaa 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Yooxanaa 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Yooxanaa 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Yoox 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Yoox 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Yoox 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Yoox 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1") p.include_apocrypha(false) expect(p.parse("YOOXANAA KOWAAD 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. YOOXANAA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. YOOXANAA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 YOOXANAA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I YOOXANAA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. YOOX 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. YOOX 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 YOOX 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I YOOX 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1") ` true describe "Localized book 2John (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yooxanaa Labaad 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Yooxanaa 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Yooxanaa 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Yooxanaa 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Yooxanaa 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Yoox 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Yoox 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Yoox 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Yoox 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1") p.include_apocrypha(false) expect(p.parse("YOOXANAA LABAAD 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. YOOXANAA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. YOOXANAA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II YOOXANAA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 YOOXANAA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. YOOX 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. YOOX 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II YOOX 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 YOOX 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1") ` true describe "Localized book 3John (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yooxanaa Saddexaad 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Yooxanaa 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Yooxanaa 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Yooxanaa 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Yooxanaa 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Yoox 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Yoox 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Yoox 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Yoox 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1") p.include_apocrypha(false) expect(p.parse("YOOXANAA SADDEXAAD 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. YOOXANAA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III YOOXANAA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. YOOXANAA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 YOOXANAA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. YOOX 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III YOOX 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. YOOX 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 YOOX 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1") ` true describe "Localized book John (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yooxanaa 1:1").osis()).toEqual("John.1.1") expect(p.parse("John 1:1").osis()).toEqual("John.1.1") expect(p.parse("Yoox 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("YOOXANAA 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1") expect(p.parse("YOOX 1:1").osis()).toEqual("John.1.1") ` true describe "Localized book Acts (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Falimaha Rasuullada 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Fal 1:1").osis()).toEqual("Acts.1.1") p.include_apocrypha(false) expect(p.parse("FALIMAHA RASUULLADA 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("FAL 1:1").osis()).toEqual("Acts.1.1") ` true describe "Localized book Rom (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Rooma 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Room 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1") p.include_apocrypha(false) expect(p.parse("ROOMA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROOM 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1") ` true describe "Localized book 2Cor (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Korintos Labaad 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Korintos 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Korintos 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Korintos 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Korintos 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1") p.include_apocrypha(false) expect(p.parse("KORINTOS LABAAD 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. KORINTOS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. KORINTOS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II KORINTOS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KORINTOS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1") ` true describe "Localized book 1Cor (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Korintos Kowaad 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Korintos 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Korintos 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Korintos 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Korintos 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1") p.include_apocrypha(false) expect(p.parse("KORINTOS KOWAAD 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. KORINTOS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. KORINTOS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KORINTOS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I KORINTOS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1") ` true describe "Localized book Gal (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Galatiya 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1") p.include_apocrypha(false) expect(p.parse("GALATIYA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1") ` true describe "Localized book Eph (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Efesos 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("EFESOS 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 (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Filiboy 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Fil 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("FILIBOY 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FIL 1:1").osis()).toEqual("Phil.1.1") ` true describe "Localized book Col (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Kolosay 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kol 1:1").osis()).toEqual("Col.1.1") p.include_apocrypha(false) expect(p.parse("KOLOSAY 1:1").osis()).toEqual("Col.1.1") expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOL 1:1").osis()).toEqual("Col.1.1") ` true describe "Localized book 2Thess (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Tesoloniika Labaad 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Tesaloniika 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Tesaloniika 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Tesaloniika 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Tesaloniika 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Tes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Tes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Tes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Tes 1:1").osis()).toEqual("2Thess.1.1") p.include_apocrypha(false) expect(p.parse("TESOLONIIKA LABAAD 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. TESALONIIKA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. TESALONIIKA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II TESALONIIKA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TESALONIIKA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. TES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. TES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II TES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TES 1:1").osis()).toEqual("2Thess.1.1") ` true describe "Localized book 1Thess (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Tesoloniika Kowaad 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Tesaloniika 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Tesaloniika 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Tesaloniika 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Tesaloniika 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Tes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Tes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Tes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Tes 1:1").osis()).toEqual("1Thess.1.1") p.include_apocrypha(false) expect(p.parse("TESOLONIIKA KOWAAD 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. TESALONIIKA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. TESALONIIKA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TESALONIIKA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I TESALONIIKA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. TES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. TES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I TES 1:1").osis()).toEqual("1Thess.1.1") ` true describe "Localized book 2Tim (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Timoteyos Labaad 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Timoteyos 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Timoteyos 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Timoteyos 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Timoteyos 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Tim 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("TIMOTEYOS LABAAD 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TIMOTEYOS 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TIMOTEYOS 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TIMOTEYOS 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIMOTEYOS 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1") ` true describe "Localized book 1Tim (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Timoteyos Kowaad 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Timoteyos 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Timoteyos 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Timoteyos 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Timoteyos 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Tim 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("TIMOTEYOS KOWAAD 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TIMOTEYOS 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TIMOTEYOS 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIMOTEYOS 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TIMOTEYOS 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1") ` true describe "Localized book Titus (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Tiitos 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tiit 1:1").osis()).toEqual("Titus.1.1") p.include_apocrypha(false) expect(p.parse("TIITOS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TIIT 1:1").osis()).toEqual("Titus.1.1") ` true describe "Localized book Phlm (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Filemon 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") p.include_apocrypha(false) expect(p.parse("FILEMON 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") ` true describe "Localized book Heb (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Cibraaniyada 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Cib 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1") p.include_apocrypha(false) expect(p.parse("CIBRAANIYADA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("CIB 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1") ` true describe "Localized book Jas (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yacquub 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Yacq 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Yac 1:1").osis()).toEqual("Jas.1.1") p.include_apocrypha(false) expect(p.parse("YACQUUB 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("YACQ 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("YAC 1:1").osis()).toEqual("Jas.1.1") ` true describe "Localized book 2Pet (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Butros Labaad 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. Butros 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. Butros 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II Butros 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Butros 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. But 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. But 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II But 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 But 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1") p.include_apocrypha(false) expect(p.parse("BUTROS LABAAD 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. BUTROS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. BUTROS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II BUTROS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 BUTROS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. BUT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. BUT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II BUT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 BUT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1") ` true describe "Localized book 1Pet (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Butros Kowaad 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. Butros 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. Butros 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Butros 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I Butros 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. But 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. But 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 But 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I But 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1") p.include_apocrypha(false) expect(p.parse("BUTROS KOWAAD 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. BUTROS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. BUTROS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 BUTROS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I BUTROS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. BUT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. BUT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 BUT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I BUT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1") ` true describe "Localized book Jude (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yuudas 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Yuud 1:1").osis()).toEqual("Jude.1.1") p.include_apocrypha(false) expect(p.parse("YUUDAS 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("YUUD 1:1").osis()).toEqual("Jude.1.1") ` true describe "Localized book Tob (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1") ` true describe "Localized book Jdt (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1") ` true describe "Localized book Bar (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1") ` true describe "Localized book Sus (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1") ` true describe "Localized book 2Macc (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1") ` true describe "Localized book 3Macc (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1") ` true describe "Localized book 4Macc (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1") ` true describe "Localized book 1Macc (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1") ` true describe "Localized book Jonah,Joel (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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,Joel (so)", -> ` expect(p.parse("Yoo 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("YOO 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book Phil,Phlm (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Fi 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("FI 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 ["so"] it "should handle ranges (so)", -> expect(p.parse("Titus 1:1 - 2").osis()).toEqual "Titus.1.1-Titus.1.2" expect(p.parse("Matt 1-2").osis()).toEqual "Matt.1-Matt.2" expect(p.parse("Phlm 2 - 3").osis()).toEqual "Phlm.1.2-Phlm.1.3" it "should handle chapters (so)", -> expect(p.parse("Titus 1:1, chapter 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 CHAPTER 6").osis()).toEqual "Matt.3.4,Matt.6" it "should handle verses (so)", -> expect(p.parse("Exod 1:1 verse 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm VERSE 6").osis()).toEqual "Phlm.1.6" it "should handle 'and' (so)", -> expect(p.parse("Exod 1:1 iyo 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 IYO 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" it "should handle titles (so)", -> expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" it "should handle 'ff' (so)", -> expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" it "should handle translations (so)", -> expect(p.parse("Lev 1 (SIMK)").osis_and_translations()).toEqual [["Lev.1", "SIMK"]] expect(p.parse("lev 1 simk").osis_and_translations()).toEqual [["Lev.1", "SIMK"]] it "should handle book ranges (so)", -> p.set_options {book_alone_strategy: "full", book_range_strategy: "include"} expect(p.parse("1 - 3 Yoox").osis()).toEqual "1John.1-3John.1" it "should handle boundaries (so)", -> 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"
156162
bcv_parser = require("../../js/so_bcv_parser.js").bcv_parser describe "Parsing", -> p = {} beforeEach -> p = new bcv_parser p.options.osis_compaction_strategy = "b" p.options.sequence_combination_strategy = "combine" it "should round-trip OSIS references", -> p.set_options osis_compaction_strategy: "bc" books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","<NAME>","<NAME>","<NAME>","<NAME>mos","<NAME>ad","<NAME>","<NAME>","<NAME>ah","Hab","Zeph","Hag","Zech","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range it "should round-trip OSIS Apocrypha references", -> p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b" p.include_apocrypha true books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range p.set_options ps151_strategy: "bc" expect(p.parse("Ps151.1").osis()).toEqual "Ps.151" expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1" expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2" p.include_apocrypha false for book in books bc = book + ".1" expect(p.parse(bc).osis()).toEqual "" it "should handle a preceding character", -> expect(p.parse(" Gen 1").osis()).toEqual "Gen.1" expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3" expect(p.parse("1Ps 1").osis()).toEqual "" expect(p.parse("11Sam 1").osis()).toEqual "" describe "Localized book Gen (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Bilowgii 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Bil 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1") p.include_apocrypha(false) expect(p.parse("BILOWGII 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("BIL 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1") ` true describe "Localized book Exod (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Baxniintii 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Bax 1:1").osis()).toEqual("Exod.1.1") p.include_apocrypha(false) expect(p.parse("BAXNIINTII 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("BAX 1:1").osis()).toEqual("Exod.1.1") ` true describe "Localized book Bel (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1") ` true describe "Localized book Lev (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Laawiyiintii 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Laaw 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1") p.include_apocrypha(false) expect(p.parse("LAAWIYIINTII 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LAAW 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1") ` true describe "Localized book Num (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Tirintii 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Tir 1:1").osis()).toEqual("Num.1.1") p.include_apocrypha(false) expect(p.parse("TIRINTII 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1") expect(p.parse("TIR 1:1").osis()).toEqual("Num.1.1") ` true describe "Localized book Sir (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1") ` true describe "Localized book Wis (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1") ` true describe "Localized book Lam (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Baroorashadii Yeremyaah 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Baroorashadii 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Baroor 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1") p.include_apocrypha(false) expect(p.parse("BAROORASHADII YEREMYAAH 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("BAROORASHADII 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("BAROOR 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1") ` true describe "Localized book EpJer (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1") ` true describe "Localized book Rev (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Muujintii 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Muuj 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1") p.include_apocrypha(false) expect(p.parse("MUUJINTII 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("MUUJ 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1") ` true describe "Localized book PrMan (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1") ` true describe "Localized book Deut (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("<NAME> 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Sharci 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1") p.include_apocrypha(false) expect(p.parse("SH<NAME>SH<NAME> 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("SHARCI 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1") ` true describe "Localized book <NAME> (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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> (so)", -> ` expect(p.parse("Yashuuca 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Yash 1:1").osis()).toEqual("Josh.1.1") p.include_apocrypha(false) expect(p.parse("YASHUUCA 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("YASH 1:1").osis()).toEqual("Josh.1.1") ` true describe "Localized book Judg (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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>udg (so)", -> ` expect(p.parse("Xaakinnada 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Xaak 1:1").osis()).toEqual("Judg.1.1") p.include_apocrypha(false) expect(p.parse("XAAKINNADA 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("XAAK 1:1").osis()).toEqual("Judg.1.1") ` true describe "Localized book Ruth (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruud 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("RUUD 1:1").osis()).toEqual("Ruth.1.1") ` true describe "Localized book 1Esd (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1") ` true describe "Localized book 2Esd (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1") ` true describe "Localized book Isa (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Ishacyaah 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Ish 1:1").osis()).toEqual("Isa.1.1") p.include_apocrypha(false) expect(p.parse("ISHACYAAH 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISH 1:1").osis()).toEqual("Isa.1.1") ` true describe "Localized book 2Sam (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Samuu'eel Labaad 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Samuu’eel Labaad 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Samuu'eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Samuu’eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Samuu'eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Samuu’eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Samuu'eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Samuu’eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Samuu'eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Samuu’eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1") p.include_apocrypha(false) expect(p.parse("SAMUU'EEL LABAAD 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SAMUU’EEL LABAAD 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAMUU'EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAMUU’EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAMUU'EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAMUU’EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAMUU'EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAMUU’EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAMUU'EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAMUU’EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1") ` true describe "Localized book 1Sam (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Samuu'eel Kowaad 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Samuu’eel Kowaad 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Samuu'eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Samuu’eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. Samuu'eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. Samuu’eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Samuu'eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Samuu’eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Samuu'eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Samuu’eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1") p.include_apocrypha(false) expect(p.parse("SAMUU'EEL KOWAAD 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("SAMUU’EEL KOWAAD 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAMUU'EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAMUU’EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAMUU'EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAMUU’EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAMUU'EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAMUU’EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAMUU'EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAMUU’EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1") ` true describe "Localized book 2Kgs (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Boqorradii Labaad 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. Boqorradii 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. Boqorradii 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II Boqorradii 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Boqorradii 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. Boq 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. Boq 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II Boq 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Boq 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1") p.include_apocrypha(false) expect(p.parse("BOQORRADII LABAAD 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. BOQORRADII 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. BOQORRADII 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II BOQORRADII 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 BOQORRADII 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. BOQ 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. BOQ 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II BOQ 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 BOQ 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1") ` true describe "Localized book 1Kgs (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Boqorradii Kowaad 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. Boqorradii 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. Boqorradii 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Boqorradii 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I Boqorradii 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. Boq 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. Boq 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Boq 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I Boq 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1") p.include_apocrypha(false) expect(p.parse("BOQORRADII KOWAAD 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. BOQORRADII 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. BOQORRADII 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 BOQORRADII 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I BOQORRADII 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. BOQ 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. BOQ 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 BOQ 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I BOQ 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1") ` true describe "Localized book 2Chr (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Taariikhdii Labaad 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. Taariikhdii 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. Taariikhdii 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II Taariikhdii 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Taariikhdii 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. Taar 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. Taar 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II Taar 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Taar 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("TAARIIKHDII LABAAD 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. TAARIIKHDII 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. TAARIIKHDII 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II TAARIIKHDII 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 TAARIIKHDII 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. TAAR 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. TAAR 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II TAAR 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 TAAR 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1") ` true describe "Localized book 1Chr (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Taariikhdii Kowaad 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. Taariikhdii 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. Taariikhdii 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Taariikhdii 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I Taariikhdii 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. Taar 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. Taar 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Taar 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I Taar 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("TAARIIKHDII KOWAAD 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. TAARIIKHDII 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. TAARIIKHDII 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 TAARIIKHDII 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I TAARIIKHDII 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. TAAR 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. TAAR 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 TAAR 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I TAAR 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1") ` true describe "Localized book Ezra (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Cesraa 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Cesr 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ces 1:1").osis()).toEqual("Ezra.1.1") p.include_apocrypha(false) expect(p.parse("CESRAA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("CESR 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("CES 1:1").osis()).toEqual("Ezra.1.1") ` true describe "Localized book Neh (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Nexemyaah 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Nex 1:1").osis()).toEqual("Neh.1.1") p.include_apocrypha(false) expect(p.parse("NEXEMYAAH 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEX 1:1").osis()).toEqual("Neh.1.1") ` true describe "Localized book GkEsth (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1") ` true describe "Localized book Esth (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Esteer 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1") p.include_apocrypha(false) expect(p.parse("ESTEER 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1") ` true describe "Localized book Job (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Ayuub 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Ayu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1") p.include_apocrypha(false) expect(p.parse("AYUUB 1:1").osis()).toEqual("Job.1.1") expect(p.parse("AYU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1") ` true describe "Localized book Ps (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sabuurradii 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Sabuur 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Sab 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1") p.include_apocrypha(false) expect(p.parse("SABUURRADII 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("SABUUR 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("SAB 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1") ` true describe "Localized book PrAzar (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1") ` true describe "Localized book Prov (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Maahmaahyadii 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Maah 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1") p.include_apocrypha(false) expect(p.parse("MAAHMAAHYADII 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("MAAH 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1") ` true describe "Localized book Eccl (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Wacdiyahii 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Wacdiyaha 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Wac 1:1").osis()).toEqual("Eccl.1.1") p.include_apocrypha(false) expect(p.parse("WACDIYAHII 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("WACDIYAHA 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("WAC 1:1").osis()).toEqual("Eccl.1.1") ` true describe "Localized book SgThree (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1") ` true describe "Localized book Song (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Gabaygii Sulaymaan 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Gabaygii 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Gab 1:1").osis()).toEqual("Song.1.1") p.include_apocrypha(false) expect(p.parse("GABAYGII SULAYMAAN 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GABAYGII 1:1").osis()).toEqual("Song.1.1") expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GAB 1:1").osis()).toEqual("Song.1.1") ` true describe "Localized book <NAME> (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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> (so)", -> ` expect(p.parse("Yeremyaah 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Yer 1:1").osis()).toEqual("Jer.1.1") p.include_apocrypha(false) expect(p.parse("YEREMYAAH 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("YER 1:1").osis()).toEqual("Jer.1.1") ` true describe "Localized book <NAME>zek (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yexesqeel 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Yex 1:1").osis()).toEqual("Ezek.1.1") p.include_apocrypha(false) expect(p.parse("YEXESQEEL 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("YEX 1:1").osis()).toEqual("Ezek.1.1") ` true describe "Localized book <NAME> (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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> (so)", -> ` expect(p.parse("Daanyeel 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Daan 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1") p.include_apocrypha(false) expect(p.parse("DAANYEEL 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAAN 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1") ` true describe "Localized book Hos (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Hoosheeca 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hoosh 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1") p.include_apocrypha(false) expect(p.parse("HOOSHEECA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOOSH 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1") ` true describe "Localized book Joel (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yoo'eel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Yoo’eel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Yool 1:1").osis()).toEqual("Joel.1.1") p.include_apocrypha(false) expect(p.parse("YOO'EEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("YOO’EEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("YOOL 1:1").osis()).toEqual("Joel.1.1") ` true describe "Localized book Amos (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Caamoos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Caam 1:1").osis()).toEqual("Amos.1.1") p.include_apocrypha(false) expect(p.parse("CAAMOOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("CAAM 1:1").osis()).toEqual("Amos.1.1") ` true describe "Localized book Obad (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Cobadyaah 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Cobad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Cob 1:1").osis()).toEqual("Obad.1.1") p.include_apocrypha(false) expect(p.parse("COBADYAAH 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("COBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("COB 1:1").osis()).toEqual("Obad.1.1") ` true describe "Localized book <NAME> (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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> (so)", -> ` expect(p.parse("Yoonis 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("<NAME> 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Yoon 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("YOONIS 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("YOON 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book <NAME> <NAME> (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: <NAME>ic (so)", -> ` expect(p.parse("Miikaah 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Miik 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1") p.include_apocrypha(false) expect(p.parse("MIIKAAH 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIIK 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1") ` true describe "Localized book Nah (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Naxuum 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nax 1:1").osis()).toEqual("Nah.1.1") p.include_apocrypha(false) expect(p.parse("NAXUUM 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAX 1:1").osis()).toEqual("Nah.1.1") ` true describe "Localized book Hab (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Xabaquuq 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Xab 1:1").osis()).toEqual("Hab.1.1") p.include_apocrypha(false) expect(p.parse("XABAQUUQ 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("XAB 1:1").osis()).toEqual("Hab.1.1") ` true describe "Localized book Zeph (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sefanyaah 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sef 1:1").osis()).toEqual("Zeph.1.1") p.include_apocrypha(false) expect(p.parse("SEFANYAAH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SEF 1:1").osis()).toEqual("Zeph.1.1") ` true describe "Localized book Hag (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Xaggay 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Xagg 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Xag 1:1").osis()).toEqual("Hag.1.1") p.include_apocrypha(false) expect(p.parse("XAGGAY 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("XAGG 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("XAG 1:1").osis()).toEqual("Hag.1.1") ` true describe "Localized book Zech (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sekaryaah 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Sek 1:1").osis()).toEqual("Zech.1.1") p.include_apocrypha(false) expect(p.parse("SEKARYAAH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("SEK 1:1").osis()).toEqual("Zech.1.1") ` true describe "Localized book Mal (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Malaakii 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1") p.include_apocrypha(false) expect(p.parse("MALAAKII 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1") ` true describe "Localized book <NAME> <NAME> (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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> (so)", -> ` expect(p.parse("Matayos 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") p.include_apocrypha(false) expect(p.parse("MATAYOS 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") ` true describe "Localized book Mark (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Markos 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") p.include_apocrypha(false) expect(p.parse("MARKOS 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") ` true describe "Localized book Luke (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Luukos 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luuk 1:1").osis()).toEqual("Luke.1.1") p.include_apocrypha(false) expect(p.parse("LUUKOS 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUUK 1:1").osis()).toEqual("Luke.1.1") ` true describe "Localized book 1John (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yooxanaa Kowaad 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Yooxanaa 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Yooxanaa 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Yooxanaa 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Yooxanaa 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Yoox 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Yoox 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Yoox 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Yoox 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1") p.include_apocrypha(false) expect(p.parse("YOOXANAA KOWAAD 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. YOOXANAA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. YOOXANAA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 YOOXANAA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I YOOXANAA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. YOOX 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. YOOX 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 YOOX 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I YOOX 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1") ` true describe "Localized book 2John (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yooxanaa Labaad 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Yooxanaa 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Yooxanaa 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Yooxanaa 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Yooxanaa 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Yoox 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Yoox 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Yoox 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Yoox 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1") p.include_apocrypha(false) expect(p.parse("YOOXANAA LABAAD 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. YOOXANAA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. YOOXANAA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II YOOXANAA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 YOOXANAA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. YOOX 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. YOOX 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II YOOX 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 YOOX 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1") ` true describe "Localized book 3John (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yooxanaa Saddexaad 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Yooxanaa 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Yooxanaa 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Yooxanaa 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Yooxanaa 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Yoox 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Yoox 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Yoox 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Yoox 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1") p.include_apocrypha(false) expect(p.parse("YOOXANAA SADDEXAAD 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. YOOXANAA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III YOOXANAA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. YOOXANAA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 YOOXANAA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. YOOX 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III YOOX 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. YOOX 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 YOOX 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1") ` true describe "Localized book John (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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> (so)", -> ` expect(p.parse("Yooxanaa 1:1").osis()).toEqual("John.1.1") expect(p.parse("John 1:1").osis()).toEqual("John.1.1") expect(p.parse("Yoox 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("YOOXANAA 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1") expect(p.parse("YOOX 1:1").osis()).toEqual("John.1.1") ` true describe "Localized book Acts (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("<NAME> 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Fal 1:1").osis()).toEqual("Acts.1.1") p.include_apocrypha(false) expect(p.parse("F<NAME> 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("FAL 1:1").osis()).toEqual("Acts.1.1") ` true describe "Localized book Rom (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Rooma 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Room 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1") p.include_apocrypha(false) expect(p.parse("ROOMA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROOM 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1") ` true describe "Localized book 2Cor (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Korintos Labaad 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Korintos 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Korintos 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Korintos 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Korintos 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1") p.include_apocrypha(false) expect(p.parse("KORINTOS LABAAD 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. KORINTOS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. KORINTOS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II KORINTOS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KORINTOS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1") ` true describe "Localized book 1Cor (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Korintos Kowaad 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Korintos 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Korintos 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Korintos 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Korintos 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1") p.include_apocrypha(false) expect(p.parse("KORINTOS KOWAAD 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. KORINTOS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. KORINTOS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KORINTOS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I KORINTOS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1") ` true describe "Localized book Gal (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Galatiya 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1") p.include_apocrypha(false) expect(p.parse("GALATIYA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1") ` true describe "Localized book Eph (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Efesos 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("EFESOS 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 (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Filiboy 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Fil 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("FILIBOY 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FIL 1:1").osis()).toEqual("Phil.1.1") ` true describe "Localized book Col (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Kolosay 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kol 1:1").osis()).toEqual("Col.1.1") p.include_apocrypha(false) expect(p.parse("KOLOSAY 1:1").osis()).toEqual("Col.1.1") expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOL 1:1").osis()).toEqual("Col.1.1") ` true describe "Localized book 2Thess (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Tes<NAME> 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Tesaloniika 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Tesaloniika 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Tesaloniika 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Tesaloniika 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Tes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Tes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Tes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Tes 1:1").osis()).toEqual("2Thess.1.1") p.include_apocrypha(false) expect(p.parse("TESOLONIIKA LABAAD 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. TESALONIIKA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. TESALONIIKA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II TESALONIIKA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TESALONIIKA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. TES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. TES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II TES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TES 1:1").osis()).toEqual("2Thess.1.1") ` true describe "Localized book 1Thess (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Tes<NAME> 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Tesaloniika 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Tesaloniika 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Tesaloniika 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Tesaloniika 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Tes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Tes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Tes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Tes 1:1").osis()).toEqual("1Thess.1.1") p.include_apocrypha(false) expect(p.parse("TESOLONIIKA KOWAAD 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. TESALONIIKA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. TESALONIIKA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TESALONIIKA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I TESALONIIKA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. TES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. TES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I TES 1:1").osis()).toEqual("1Thess.1.1") ` true describe "Localized book 2Tim (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Timoteyos Labaad 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Timoteyos 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Timoteyos 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Timoteyos 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Timoteyos 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Tim 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("TIMOTEYOS LABAAD 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TIMOTEYOS 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TIMOTEYOS 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TIMOTEYOS 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIMOTEYOS 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1") ` true describe "Localized book 1Tim (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Timoteyos Kowaad 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Timoteyos 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Timoteyos 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Timoteyos 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Timoteyos 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Tim 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("TIMOTEYOS KOWAAD 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TIMOTEYOS 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TIMOTEYOS 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIMOTEYOS 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TIMOTEYOS 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1") ` true describe "Localized book Titus (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Tiitos 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tiit 1:1").osis()).toEqual("Titus.1.1") p.include_apocrypha(false) expect(p.parse("TIITOS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TIIT 1:1").osis()).toEqual("Titus.1.1") ` true describe "Localized book Phlm (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Filemon 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") p.include_apocrypha(false) expect(p.parse("FILEMON 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") ` true describe "Localized book Heb (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Cibraaniyada 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Cib 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1") p.include_apocrypha(false) expect(p.parse("CIBRAANIYADA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("CIB 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1") ` true describe "Localized book Jas (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yacquub 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Yacq 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Yac 1:1").osis()).toEqual("Jas.1.1") p.include_apocrypha(false) expect(p.parse("YACQUUB 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("YACQ 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("YAC 1:1").osis()).toEqual("Jas.1.1") ` true describe "Localized book 2Pet (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Butros Labaad 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. Butros 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. Butros 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II Butros 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Butros 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. But 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. But 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II But 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 But 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1") p.include_apocrypha(false) expect(p.parse("BUTROS LABAAD 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. BUTROS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. BUTROS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II BUTROS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 BUTROS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. BUT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. BUT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II BUT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 BUT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1") ` true describe "Localized book 1Pet (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Butros Kowaad 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. Butros 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. Butros 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Butros 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I Butros 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. But 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. But 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 But 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I But 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1") p.include_apocrypha(false) expect(p.parse("BUTROS KOWAAD 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. BUTROS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. BUTROS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 BUTROS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I BUTROS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. BUT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. BUT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 BUT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I BUT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1") ` true describe "Localized book Jude (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yuudas 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Yuud 1:1").osis()).toEqual("Jude.1.1") p.include_apocrypha(false) expect(p.parse("YUUDAS 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("YUUD 1:1").osis()).toEqual("Jude.1.1") ` true describe "Localized book Tob (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1") ` true describe "Localized book Jdt (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1") ` true describe "Localized book Bar (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1") ` true describe "Localized book Sus (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1") ` true describe "Localized book 2Macc (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1") ` true describe "Localized book 3Macc (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1") ` true describe "Localized book 4Macc (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1") ` true describe "Localized book 1Macc (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1") ` true describe "Localized book <NAME>,Jo<NAME> (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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>,Jo<NAME> (so)", -> ` expect(p.parse("Yoo 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("YOO 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book <NAME>,Phlm (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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>,Phlm (so)", -> ` expect(p.parse("Fi 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("FI 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 ["so"] it "should handle ranges (so)", -> expect(p.parse("Titus 1:1 - 2").osis()).toEqual "Titus.1.1-Titus.1.2" expect(p.parse("Matt 1-2").osis()).toEqual "Matt.1-Matt.2" expect(p.parse("Phlm 2 - 3").osis()).toEqual "Phlm.1.2-Phlm.1.3" it "should handle chapters (so)", -> expect(p.parse("Titus 1:1, chapter 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 CHAPTER 6").osis()).toEqual "Matt.3.4,Matt.6" it "should handle verses (so)", -> expect(p.parse("Exod 1:1 verse 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm VERSE 6").osis()).toEqual "Phlm.1.6" it "should handle 'and' (so)", -> expect(p.parse("Exod 1:1 iyo 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 IYO 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" it "should handle titles (so)", -> expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" it "should handle 'ff' (so)", -> expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" it "should handle translations (so)", -> expect(p.parse("Lev 1 (SIMK)").osis_and_translations()).toEqual [["Lev.1", "SIMK"]] expect(p.parse("lev 1 simk").osis_and_translations()).toEqual [["Lev.1", "SIMK"]] it "should handle book ranges (so)", -> p.set_options {book_alone_strategy: "full", book_range_strategy: "include"} expect(p.parse("1 - 3 Yoox").osis()).toEqual "1John.1-3John.1" it "should handle boundaries (so)", -> 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/so_bcv_parser.js").bcv_parser describe "Parsing", -> p = {} beforeEach -> p = new bcv_parser p.options.osis_compaction_strategy = "b" p.options.sequence_combination_strategy = "combine" it "should round-trip OSIS references", -> p.set_options osis_compaction_strategy: "bc" books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PImos","PI:NAME:<NAME>END_PIad","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PIah","Hab","Zeph","Hag","Zech","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range it "should round-trip OSIS Apocrypha references", -> p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b" p.include_apocrypha true books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"] for book in books bc = book + ".1" bcv = bc + ".1" bcv_range = bcv + "-" + bc + ".2" expect(p.parse(bc).osis()).toEqual bc expect(p.parse(bcv).osis()).toEqual bcv expect(p.parse(bcv_range).osis()).toEqual bcv_range p.set_options ps151_strategy: "bc" expect(p.parse("Ps151.1").osis()).toEqual "Ps.151" expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1" expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2" p.include_apocrypha false for book in books bc = book + ".1" expect(p.parse(bc).osis()).toEqual "" it "should handle a preceding character", -> expect(p.parse(" Gen 1").osis()).toEqual "Gen.1" expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3" expect(p.parse("1Ps 1").osis()).toEqual "" expect(p.parse("11Sam 1").osis()).toEqual "" describe "Localized book Gen (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Bilowgii 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Bil 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1") p.include_apocrypha(false) expect(p.parse("BILOWGII 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("BIL 1:1").osis()).toEqual("Gen.1.1") expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1") ` true describe "Localized book Exod (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Baxniintii 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("Bax 1:1").osis()).toEqual("Exod.1.1") p.include_apocrypha(false) expect(p.parse("BAXNIINTII 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1") expect(p.parse("BAX 1:1").osis()).toEqual("Exod.1.1") ` true describe "Localized book Bel (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1") ` true describe "Localized book Lev (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Laawiyiintii 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Laaw 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1") p.include_apocrypha(false) expect(p.parse("LAAWIYIINTII 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LAAW 1:1").osis()).toEqual("Lev.1.1") expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1") ` true describe "Localized book Num (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Tirintii 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1") expect(p.parse("Tir 1:1").osis()).toEqual("Num.1.1") p.include_apocrypha(false) expect(p.parse("TIRINTII 1:1").osis()).toEqual("Num.1.1") expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1") expect(p.parse("TIR 1:1").osis()).toEqual("Num.1.1") ` true describe "Localized book Sir (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1") ` true describe "Localized book Wis (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1") ` true describe "Localized book Lam (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Baroorashadii Yeremyaah 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Baroorashadii 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Baroor 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1") p.include_apocrypha(false) expect(p.parse("BAROORASHADII YEREMYAAH 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("BAROORASHADII 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("BAROOR 1:1").osis()).toEqual("Lam.1.1") expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1") ` true describe "Localized book EpJer (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1") ` true describe "Localized book Rev (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Muujintii 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Muuj 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1") p.include_apocrypha(false) expect(p.parse("MUUJINTII 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("MUUJ 1:1").osis()).toEqual("Rev.1.1") expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1") ` true describe "Localized book PrMan (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1") ` true describe "Localized book Deut (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Sharci 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1") p.include_apocrypha(false) expect(p.parse("SHPI:NAME:<NAME>END_PISHPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("SHARCI 1:1").osis()).toEqual("Deut.1.1") expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yashuuca 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("Yash 1:1").osis()).toEqual("Josh.1.1") p.include_apocrypha(false) expect(p.parse("YASHUUCA 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1") expect(p.parse("YASH 1:1").osis()).toEqual("Josh.1.1") ` true describe "Localized book Judg (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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_PIudg (so)", -> ` expect(p.parse("Xaakinnada 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("Xaak 1:1").osis()).toEqual("Judg.1.1") p.include_apocrypha(false) expect(p.parse("XAAKINNADA 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1") expect(p.parse("XAAK 1:1").osis()).toEqual("Judg.1.1") ` true describe "Localized book Ruth (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1") expect(p.parse("Ruud 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("RUUD 1:1").osis()).toEqual("Ruth.1.1") ` true describe "Localized book 1Esd (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1") ` true describe "Localized book 2Esd (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1") ` true describe "Localized book Isa (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Ishacyaah 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("Ish 1:1").osis()).toEqual("Isa.1.1") p.include_apocrypha(false) expect(p.parse("ISHACYAAH 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1") expect(p.parse("ISH 1:1").osis()).toEqual("Isa.1.1") ` true describe "Localized book 2Sam (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Samuu'eel Labaad 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("Samuu’eel Labaad 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Samuu'eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Samuu’eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Samuu'eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Samuu’eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Samuu'eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Samuu’eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Samuu'eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Samuu’eel 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1") p.include_apocrypha(false) expect(p.parse("SAMUU'EEL LABAAD 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("SAMUU’EEL LABAAD 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAMUU'EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAMUU’EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAMUU'EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAMUU’EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAMUU'EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAMUU’EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAMUU'EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAMUU’EEL 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2. SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("II SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1") expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1") ` true describe "Localized book 1Sam (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Samuu'eel Kowaad 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("Samuu’eel Kowaad 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Samuu'eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Samuu’eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. Samuu'eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. Samuu’eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Samuu'eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Samuu’eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Samuu'eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Samuu’eel 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I Sam 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1") p.include_apocrypha(false) expect(p.parse("SAMUU'EEL KOWAAD 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("SAMUU’EEL KOWAAD 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAMUU'EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAMUU’EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAMUU'EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAMUU’EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAMUU'EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAMUU’EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAMUU'EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAMUU’EEL 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I. SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("I SAM 1:1").osis()).toEqual("1Sam.1.1") expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1") ` true describe "Localized book 2Kgs (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Boqorradii Labaad 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. Boqorradii 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. Boqorradii 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II Boqorradii 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Boqorradii 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. Boq 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. Boq 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II Boq 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 Boq 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1") p.include_apocrypha(false) expect(p.parse("BOQORRADII LABAAD 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. BOQORRADII 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. BOQORRADII 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II BOQORRADII 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 BOQORRADII 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II. BOQ 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2. BOQ 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("II BOQ 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2 BOQ 1:1").osis()).toEqual("2Kgs.1.1") expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1") ` true describe "Localized book 1Kgs (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Boqorradii Kowaad 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. Boqorradii 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. Boqorradii 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Boqorradii 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I Boqorradii 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. Boq 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. Boq 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 Boq 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I Boq 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1") p.include_apocrypha(false) expect(p.parse("BOQORRADII KOWAAD 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. BOQORRADII 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. BOQORRADII 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 BOQORRADII 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I BOQORRADII 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1. BOQ 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I. BOQ 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1 BOQ 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("I BOQ 1:1").osis()).toEqual("1Kgs.1.1") expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1") ` true describe "Localized book 2Chr (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Taariikhdii Labaad 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. Taariikhdii 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. Taariikhdii 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II Taariikhdii 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Taariikhdii 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. Taar 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. Taar 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II Taar 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 Taar 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("TAARIIKHDII LABAAD 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. TAARIIKHDII 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. TAARIIKHDII 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II TAARIIKHDII 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 TAARIIKHDII 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II. TAAR 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2. TAAR 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("II TAAR 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2 TAAR 1:1").osis()).toEqual("2Chr.1.1") expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1") ` true describe "Localized book 1Chr (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Taariikhdii Kowaad 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. Taariikhdii 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. Taariikhdii 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Taariikhdii 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I Taariikhdii 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. Taar 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. Taar 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 Taar 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I Taar 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("TAARIIKHDII KOWAAD 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. TAARIIKHDII 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. TAARIIKHDII 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 TAARIIKHDII 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I TAARIIKHDII 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1. TAAR 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I. TAAR 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1 TAAR 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("I TAAR 1:1").osis()).toEqual("1Chr.1.1") expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1") ` true describe "Localized book Ezra (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Cesraa 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Cesr 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("Ces 1:1").osis()).toEqual("Ezra.1.1") p.include_apocrypha(false) expect(p.parse("CESRAA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("CESR 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1") expect(p.parse("CES 1:1").osis()).toEqual("Ezra.1.1") ` true describe "Localized book Neh (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Nexemyaah 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("Nex 1:1").osis()).toEqual("Neh.1.1") p.include_apocrypha(false) expect(p.parse("NEXEMYAAH 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1") expect(p.parse("NEX 1:1").osis()).toEqual("Neh.1.1") ` true describe "Localized book GkEsth (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1") ` true describe "Localized book Esth (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Esteer 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1") p.include_apocrypha(false) expect(p.parse("ESTEER 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1") expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1") ` true describe "Localized book Job (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Ayuub 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Ayu 1:1").osis()).toEqual("Job.1.1") expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1") p.include_apocrypha(false) expect(p.parse("AYUUB 1:1").osis()).toEqual("Job.1.1") expect(p.parse("AYU 1:1").osis()).toEqual("Job.1.1") expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1") ` true describe "Localized book Ps (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sabuurradii 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Sabuur 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Sab 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1") p.include_apocrypha(false) expect(p.parse("SABUURRADII 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("SABUUR 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("SAB 1:1").osis()).toEqual("Ps.1.1") expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1") ` true describe "Localized book PrAzar (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1") ` true describe "Localized book Prov (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Maahmaahyadii 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Maah 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1") p.include_apocrypha(false) expect(p.parse("MAAHMAAHYADII 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("MAAH 1:1").osis()).toEqual("Prov.1.1") expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1") ` true describe "Localized book Eccl (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Wacdiyahii 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Wacdiyaha 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("Wac 1:1").osis()).toEqual("Eccl.1.1") p.include_apocrypha(false) expect(p.parse("WACDIYAHII 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("WACDIYAHA 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1") expect(p.parse("WAC 1:1").osis()).toEqual("Eccl.1.1") ` true describe "Localized book SgThree (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1") ` true describe "Localized book Song (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Gabaygii Sulaymaan 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Gabaygii 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1") expect(p.parse("Gab 1:1").osis()).toEqual("Song.1.1") p.include_apocrypha(false) expect(p.parse("GABAYGII SULAYMAAN 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GABAYGII 1:1").osis()).toEqual("Song.1.1") expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1") expect(p.parse("GAB 1:1").osis()).toEqual("Song.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yeremyaah 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("Yer 1:1").osis()).toEqual("Jer.1.1") p.include_apocrypha(false) expect(p.parse("YEREMYAAH 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1") expect(p.parse("YER 1:1").osis()).toEqual("Jer.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PIzek (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yexesqeel 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("Yex 1:1").osis()).toEqual("Ezek.1.1") p.include_apocrypha(false) expect(p.parse("YEXESQEEL 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1") expect(p.parse("YEX 1:1").osis()).toEqual("Ezek.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Daanyeel 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Daan 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1") p.include_apocrypha(false) expect(p.parse("DAANYEEL 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAAN 1:1").osis()).toEqual("Dan.1.1") expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1") ` true describe "Localized book Hos (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Hoosheeca 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hoosh 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1") p.include_apocrypha(false) expect(p.parse("HOOSHEECA 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOOSH 1:1").osis()).toEqual("Hos.1.1") expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1") ` true describe "Localized book Joel (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yoo'eel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Yoo’eel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("Yool 1:1").osis()).toEqual("Joel.1.1") p.include_apocrypha(false) expect(p.parse("YOO'EEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("YOO’EEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1") expect(p.parse("YOOL 1:1").osis()).toEqual("Joel.1.1") ` true describe "Localized book Amos (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Caamoos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("Caam 1:1").osis()).toEqual("Amos.1.1") p.include_apocrypha(false) expect(p.parse("CAAMOOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1") expect(p.parse("CAAM 1:1").osis()).toEqual("Amos.1.1") ` true describe "Localized book Obad (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Cobadyaah 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Cobad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("Cob 1:1").osis()).toEqual("Obad.1.1") p.include_apocrypha(false) expect(p.parse("COBADYAAH 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("COBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1") expect(p.parse("COB 1:1").osis()).toEqual("Obad.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yoonis 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("Yoon 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("YOONIS 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1") expect(p.parse("YOON 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete" p.include_apocrypha true it "should handle book: PI:NAME:<NAME>END_PIic (so)", -> ` expect(p.parse("Miikaah 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Miik 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1") p.include_apocrypha(false) expect(p.parse("MIIKAAH 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIIK 1:1").osis()).toEqual("Mic.1.1") expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1") ` true describe "Localized book Nah (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Naxuum 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("Nax 1:1").osis()).toEqual("Nah.1.1") p.include_apocrypha(false) expect(p.parse("NAXUUM 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1") expect(p.parse("NAX 1:1").osis()).toEqual("Nah.1.1") ` true describe "Localized book Hab (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Xabaquuq 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("Xab 1:1").osis()).toEqual("Hab.1.1") p.include_apocrypha(false) expect(p.parse("XABAQUUQ 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1") expect(p.parse("XAB 1:1").osis()).toEqual("Hab.1.1") ` true describe "Localized book Zeph (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sefanyaah 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("Sef 1:1").osis()).toEqual("Zeph.1.1") p.include_apocrypha(false) expect(p.parse("SEFANYAAH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1") expect(p.parse("SEF 1:1").osis()).toEqual("Zeph.1.1") ` true describe "Localized book Hag (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Xaggay 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Xagg 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("Xag 1:1").osis()).toEqual("Hag.1.1") p.include_apocrypha(false) expect(p.parse("XAGGAY 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("XAGG 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1") expect(p.parse("XAG 1:1").osis()).toEqual("Hag.1.1") ` true describe "Localized book Zech (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sekaryaah 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("Sek 1:1").osis()).toEqual("Zech.1.1") p.include_apocrypha(false) expect(p.parse("SEKARYAAH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1") expect(p.parse("SEK 1:1").osis()).toEqual("Zech.1.1") ` true describe "Localized book Mal (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Malaakii 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1") p.include_apocrypha(false) expect(p.parse("MALAAKII 1:1").osis()).toEqual("Mal.1.1") expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Matayos 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") p.include_apocrypha(false) expect(p.parse("MATAYOS 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") ` true describe "Localized book Mark (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Markos 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") p.include_apocrypha(false) expect(p.parse("MARKOS 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") ` true describe "Localized book Luke (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Luukos 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("Luuk 1:1").osis()).toEqual("Luke.1.1") p.include_apocrypha(false) expect(p.parse("LUUKOS 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1") expect(p.parse("LUUK 1:1").osis()).toEqual("Luke.1.1") ` true describe "Localized book 1John (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yooxanaa Kowaad 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Yooxanaa 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Yooxanaa 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Yooxanaa 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Yooxanaa 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. Yoox 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. Yoox 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 Yoox 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I Yoox 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1") p.include_apocrypha(false) expect(p.parse("YOOXANAA KOWAAD 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. YOOXANAA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. YOOXANAA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 YOOXANAA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I YOOXANAA 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1. YOOX 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I. YOOX 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1 YOOX 1:1").osis()).toEqual("1John.1.1") expect(p.parse("I YOOX 1:1").osis()).toEqual("1John.1.1") expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1") ` true describe "Localized book 2John (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yooxanaa Labaad 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Yooxanaa 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Yooxanaa 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Yooxanaa 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Yooxanaa 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. Yoox 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. Yoox 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II Yoox 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 Yoox 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1") p.include_apocrypha(false) expect(p.parse("YOOXANAA LABAAD 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. YOOXANAA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. YOOXANAA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II YOOXANAA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 YOOXANAA 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II. YOOX 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2. YOOX 1:1").osis()).toEqual("2John.1.1") expect(p.parse("II YOOX 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2 YOOX 1:1").osis()).toEqual("2John.1.1") expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1") ` true describe "Localized book 3John (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yooxanaa Saddexaad 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Yooxanaa 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Yooxanaa 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Yooxanaa 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Yooxanaa 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. Yoox 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III Yoox 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. Yoox 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 Yoox 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1") p.include_apocrypha(false) expect(p.parse("YOOXANAA SADDEXAAD 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. YOOXANAA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III YOOXANAA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. YOOXANAA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 YOOXANAA 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III. YOOX 1:1").osis()).toEqual("3John.1.1") expect(p.parse("III YOOX 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3. YOOX 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3 YOOX 1:1").osis()).toEqual("3John.1.1") expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1") ` true describe "Localized book John (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yooxanaa 1:1").osis()).toEqual("John.1.1") expect(p.parse("John 1:1").osis()).toEqual("John.1.1") expect(p.parse("Yoox 1:1").osis()).toEqual("John.1.1") p.include_apocrypha(false) expect(p.parse("YOOXANAA 1:1").osis()).toEqual("John.1.1") expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1") expect(p.parse("YOOX 1:1").osis()).toEqual("John.1.1") ` true describe "Localized book Acts (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("Fal 1:1").osis()).toEqual("Acts.1.1") p.include_apocrypha(false) expect(p.parse("FPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1") expect(p.parse("FAL 1:1").osis()).toEqual("Acts.1.1") ` true describe "Localized book Rom (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Rooma 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Room 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1") p.include_apocrypha(false) expect(p.parse("ROOMA 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROOM 1:1").osis()).toEqual("Rom.1.1") expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1") ` true describe "Localized book 2Cor (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Korintos Labaad 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Korintos 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Korintos 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Korintos 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Korintos 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 Kor 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1") p.include_apocrypha(false) expect(p.parse("KORINTOS LABAAD 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. KORINTOS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. KORINTOS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II KORINTOS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KORINTOS 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2. KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("II KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2 KOR 1:1").osis()).toEqual("2Cor.1.1") expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1") ` true describe "Localized book 1Cor (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Korintos Kowaad 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Korintos 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Korintos 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Korintos 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Korintos 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I Kor 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1") p.include_apocrypha(false) expect(p.parse("KORINTOS KOWAAD 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. KORINTOS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. KORINTOS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KORINTOS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I KORINTOS 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I. KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1 KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("I KOR 1:1").osis()).toEqual("1Cor.1.1") expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1") ` true describe "Localized book Gal (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Galatiya 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1") p.include_apocrypha(false) expect(p.parse("GALATIYA 1:1").osis()).toEqual("Gal.1.1") expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1") ` true describe "Localized book Eph (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Efesos 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("EFESOS 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 (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Filiboy 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("Fil 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("FILIBOY 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1") expect(p.parse("FIL 1:1").osis()).toEqual("Phil.1.1") ` true describe "Localized book Col (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Kolosay 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1") expect(p.parse("Kol 1:1").osis()).toEqual("Col.1.1") p.include_apocrypha(false) expect(p.parse("KOLOSAY 1:1").osis()).toEqual("Col.1.1") expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1") expect(p.parse("KOL 1:1").osis()).toEqual("Col.1.1") ` true describe "Localized book 2Thess (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("TesPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Tesaloniika 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Tesaloniika 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Tesaloniika 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Tesaloniika 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. Tes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. Tes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II Tes 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 Tes 1:1").osis()).toEqual("2Thess.1.1") p.include_apocrypha(false) expect(p.parse("TESOLONIIKA LABAAD 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. TESALONIIKA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. TESALONIIKA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II TESALONIIKA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TESALONIIKA 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II. TES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2. TES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("II TES 1:1").osis()).toEqual("2Thess.1.1") expect(p.parse("2 TES 1:1").osis()).toEqual("2Thess.1.1") ` true describe "Localized book 1Thess (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("TesPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Tesaloniika 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Tesaloniika 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Tesaloniika 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Tesaloniika 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. Tes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. Tes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 Tes 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I Tes 1:1").osis()).toEqual("1Thess.1.1") p.include_apocrypha(false) expect(p.parse("TESOLONIIKA KOWAAD 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. TESALONIIKA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. TESALONIIKA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TESALONIIKA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I TESALONIIKA 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1. TES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I. TES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("1 TES 1:1").osis()).toEqual("1Thess.1.1") expect(p.parse("I TES 1:1").osis()).toEqual("1Thess.1.1") ` true describe "Localized book 2Tim (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Timoteyos Labaad 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Timoteyos 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Timoteyos 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Timoteyos 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Timoteyos 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II Tim 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 Tim 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("TIMOTEYOS LABAAD 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TIMOTEYOS 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TIMOTEYOS 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TIMOTEYOS 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIMOTEYOS 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2. TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("II TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1") expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1") ` true describe "Localized book 1Tim (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Timoteyos Kowaad 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Timoteyos 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Timoteyos 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Timoteyos 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Timoteyos 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I Tim 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("TIMOTEYOS KOWAAD 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TIMOTEYOS 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TIMOTEYOS 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIMOTEYOS 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TIMOTEYOS 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I. TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("I TIM 1:1").osis()).toEqual("1Tim.1.1") expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1") ` true describe "Localized book Titus (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Tiitos 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("Tiit 1:1").osis()).toEqual("Titus.1.1") p.include_apocrypha(false) expect(p.parse("TIITOS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1") expect(p.parse("TIIT 1:1").osis()).toEqual("Titus.1.1") ` true describe "Localized book Phlm (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Filemon 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") p.include_apocrypha(false) expect(p.parse("FILEMON 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") ` true describe "Localized book Heb (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Cibraaniyada 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Cib 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1") p.include_apocrypha(false) expect(p.parse("CIBRAANIYADA 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("CIB 1:1").osis()).toEqual("Heb.1.1") expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1") ` true describe "Localized book Jas (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yacquub 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Yacq 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("Yac 1:1").osis()).toEqual("Jas.1.1") p.include_apocrypha(false) expect(p.parse("YACQUUB 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("YACQ 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1") expect(p.parse("YAC 1:1").osis()).toEqual("Jas.1.1") ` true describe "Localized book 2Pet (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Butros Labaad 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. Butros 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. Butros 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II Butros 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 Butros 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. But 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. But 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II But 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 But 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1") p.include_apocrypha(false) expect(p.parse("BUTROS LABAAD 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. BUTROS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. BUTROS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II BUTROS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 BUTROS 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II. BUT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2. BUT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("II BUT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2 BUT 1:1").osis()).toEqual("2Pet.1.1") expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1") ` true describe "Localized book 1Pet (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Butros Kowaad 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. Butros 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. Butros 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 Butros 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I Butros 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. But 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. But 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 But 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I But 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1") p.include_apocrypha(false) expect(p.parse("BUTROS KOWAAD 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. BUTROS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. BUTROS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 BUTROS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I BUTROS 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1. BUT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I. BUT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1 BUT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("I BUT 1:1").osis()).toEqual("1Pet.1.1") expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1") ` true describe "Localized book Jude (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Yuudas 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("Yuud 1:1").osis()).toEqual("Jude.1.1") p.include_apocrypha(false) expect(p.parse("YUUDAS 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1") expect(p.parse("YUUD 1:1").osis()).toEqual("Jude.1.1") ` true describe "Localized book Tob (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1") ` true describe "Localized book Jdt (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1") ` true describe "Localized book Bar (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1") ` true describe "Localized book Sus (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1") ` true describe "Localized book 2Macc (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1") ` true describe "Localized book 3Macc (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1") ` true describe "Localized book 4Macc (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1") ` true describe "Localized book 1Macc (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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 (so)", -> ` expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI,JoPI:NAME:<NAME>END_PI (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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,JoPI:NAME:<NAME>END_PI (so)", -> ` expect(p.parse("Yoo 1:1").osis()).toEqual("Jonah.1.1") p.include_apocrypha(false) expect(p.parse("YOO 1:1").osis()).toEqual("Jonah.1.1") ` true describe "Localized book PI:NAME:<NAME>END_PI,Phlm (so)", -> p = {} beforeEach -> p = new bcv_parser p.set_options book_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,Phlm (so)", -> ` expect(p.parse("Fi 1:1").osis()).toEqual("Phil.1.1") p.include_apocrypha(false) expect(p.parse("FI 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 ["so"] it "should handle ranges (so)", -> expect(p.parse("Titus 1:1 - 2").osis()).toEqual "Titus.1.1-Titus.1.2" expect(p.parse("Matt 1-2").osis()).toEqual "Matt.1-Matt.2" expect(p.parse("Phlm 2 - 3").osis()).toEqual "Phlm.1.2-Phlm.1.3" it "should handle chapters (so)", -> expect(p.parse("Titus 1:1, chapter 2").osis()).toEqual "Titus.1.1,Titus.2" expect(p.parse("Matt 3:4 CHAPTER 6").osis()).toEqual "Matt.3.4,Matt.6" it "should handle verses (so)", -> expect(p.parse("Exod 1:1 verse 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm VERSE 6").osis()).toEqual "Phlm.1.6" it "should handle 'and' (so)", -> expect(p.parse("Exod 1:1 iyo 3").osis()).toEqual "Exod.1.1,Exod.1.3" expect(p.parse("Phlm 2 IYO 6").osis()).toEqual "Phlm.1.2,Phlm.1.6" it "should handle titles (so)", -> expect(p.parse("Ps 3 title, 4:2, 5:title").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" expect(p.parse("PS 3 TITLE, 4:2, 5:TITLE").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1" it "should handle 'ff' (so)", -> expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11" it "should handle translations (so)", -> expect(p.parse("Lev 1 (SIMK)").osis_and_translations()).toEqual [["Lev.1", "SIMK"]] expect(p.parse("lev 1 simk").osis_and_translations()).toEqual [["Lev.1", "SIMK"]] it "should handle book ranges (so)", -> p.set_options {book_alone_strategy: "full", book_range_strategy: "include"} expect(p.parse("1 - 3 Yoox").osis()).toEqual "1John.1-3John.1" it "should handle boundaries (so)", -> 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": "rtual('password').set((password) ->\n @_password = password\n @salt = @makeSalt()\n @hashedPassword = @encryp", "end": 497, "score": 0.9781333208084106, "start": 489, "tag": "PASSWORD", "value": "password" } ]
server/api/user/user.model.coffee
harryoh/node-dd-shortener
0
'use strict' mongoose = require 'mongoose' Schema = mongoose.Schema crypto = require 'crypto' authTypes = [ 'github' 'twitter' 'facebook' 'google' ] UserSchema = new Schema( name: String email: type: String lowercase: true role: type: String default: 'user' hashedPassword: String provider: String salt: String facebook: {} twitter: {} google: {} github: {} ) ###* Virtuals ### UserSchema.virtual('password').set((password) -> @_password = password @salt = @makeSalt() @hashedPassword = @encryptPassword(password) ).get -> @_password # Public profile information UserSchema.virtual('profile').get -> name: @name role: @role # Non-sensitive info we'll be putting in the token UserSchema.virtual('token').get -> _id: @_id role: @role ###* Validations ### # Validate empty email UserSchema.path('email').validate ((email) -> return true if authTypes.indexOf(@provider) isnt -1 email.length ), 'Email cannot be blank' # Validate empty password UserSchema.path('hashedPassword').validate ((hashedPassword) -> return true if authTypes.indexOf(@provider) isnt -1 hashedPassword.length ), 'Password cannot be blank' # Validate email is not taken UserSchema.path('email').validate ((value, respond) -> self = this @constructor.findOne email: value , (err, user) -> throw err if err if user return respond(true) if self.id is user.id return respond(false) respond true ), 'The specified email address is already in use.' validatePresenceOf = (value) -> value and value.length ###* Pre-save hook ### UserSchema.pre 'save', (next) -> return next() unless @isNew if not validatePresenceOf(@hashedPassword) and authTypes.indexOf(@provider) is -1 next new Error('Invalid password') else next() ###* Methods ### UserSchema.methods = ###* Authenticate - check if the passwords are the same @param {String} plainText @return {Boolean} @api public ### authenticate: (plainText) -> @encryptPassword(plainText) is @hashedPassword ###* Make salt @return {String} @api public ### makeSalt: -> crypto.randomBytes(16).toString 'base64' ###* Encrypt password @param {String} password @return {String} @api public ### encryptPassword: (password) -> return '' if not password or not @salt salt = new Buffer(@salt, 'base64') crypto.pbkdf2Sync(password, salt, 10000, 64).toString 'base64' module.exports = mongoose.model('User', UserSchema)
223358
'use strict' mongoose = require 'mongoose' Schema = mongoose.Schema crypto = require 'crypto' authTypes = [ 'github' 'twitter' 'facebook' 'google' ] UserSchema = new Schema( name: String email: type: String lowercase: true role: type: String default: 'user' hashedPassword: String provider: String salt: String facebook: {} twitter: {} google: {} github: {} ) ###* Virtuals ### UserSchema.virtual('password').set((password) -> @_password = <PASSWORD> @salt = @makeSalt() @hashedPassword = @encryptPassword(password) ).get -> @_password # Public profile information UserSchema.virtual('profile').get -> name: @name role: @role # Non-sensitive info we'll be putting in the token UserSchema.virtual('token').get -> _id: @_id role: @role ###* Validations ### # Validate empty email UserSchema.path('email').validate ((email) -> return true if authTypes.indexOf(@provider) isnt -1 email.length ), 'Email cannot be blank' # Validate empty password UserSchema.path('hashedPassword').validate ((hashedPassword) -> return true if authTypes.indexOf(@provider) isnt -1 hashedPassword.length ), 'Password cannot be blank' # Validate email is not taken UserSchema.path('email').validate ((value, respond) -> self = this @constructor.findOne email: value , (err, user) -> throw err if err if user return respond(true) if self.id is user.id return respond(false) respond true ), 'The specified email address is already in use.' validatePresenceOf = (value) -> value and value.length ###* Pre-save hook ### UserSchema.pre 'save', (next) -> return next() unless @isNew if not validatePresenceOf(@hashedPassword) and authTypes.indexOf(@provider) is -1 next new Error('Invalid password') else next() ###* Methods ### UserSchema.methods = ###* Authenticate - check if the passwords are the same @param {String} plainText @return {Boolean} @api public ### authenticate: (plainText) -> @encryptPassword(plainText) is @hashedPassword ###* Make salt @return {String} @api public ### makeSalt: -> crypto.randomBytes(16).toString 'base64' ###* Encrypt password @param {String} password @return {String} @api public ### encryptPassword: (password) -> return '' if not password or not @salt salt = new Buffer(@salt, 'base64') crypto.pbkdf2Sync(password, salt, 10000, 64).toString 'base64' module.exports = mongoose.model('User', UserSchema)
true
'use strict' mongoose = require 'mongoose' Schema = mongoose.Schema crypto = require 'crypto' authTypes = [ 'github' 'twitter' 'facebook' 'google' ] UserSchema = new Schema( name: String email: type: String lowercase: true role: type: String default: 'user' hashedPassword: String provider: String salt: String facebook: {} twitter: {} google: {} github: {} ) ###* Virtuals ### UserSchema.virtual('password').set((password) -> @_password = PI:PASSWORD:<PASSWORD>END_PI @salt = @makeSalt() @hashedPassword = @encryptPassword(password) ).get -> @_password # Public profile information UserSchema.virtual('profile').get -> name: @name role: @role # Non-sensitive info we'll be putting in the token UserSchema.virtual('token').get -> _id: @_id role: @role ###* Validations ### # Validate empty email UserSchema.path('email').validate ((email) -> return true if authTypes.indexOf(@provider) isnt -1 email.length ), 'Email cannot be blank' # Validate empty password UserSchema.path('hashedPassword').validate ((hashedPassword) -> return true if authTypes.indexOf(@provider) isnt -1 hashedPassword.length ), 'Password cannot be blank' # Validate email is not taken UserSchema.path('email').validate ((value, respond) -> self = this @constructor.findOne email: value , (err, user) -> throw err if err if user return respond(true) if self.id is user.id return respond(false) respond true ), 'The specified email address is already in use.' validatePresenceOf = (value) -> value and value.length ###* Pre-save hook ### UserSchema.pre 'save', (next) -> return next() unless @isNew if not validatePresenceOf(@hashedPassword) and authTypes.indexOf(@provider) is -1 next new Error('Invalid password') else next() ###* Methods ### UserSchema.methods = ###* Authenticate - check if the passwords are the same @param {String} plainText @return {Boolean} @api public ### authenticate: (plainText) -> @encryptPassword(plainText) is @hashedPassword ###* Make salt @return {String} @api public ### makeSalt: -> crypto.randomBytes(16).toString 'base64' ###* Encrypt password @param {String} password @return {String} @api public ### encryptPassword: (password) -> return '' if not password or not @salt salt = new Buffer(@salt, 'base64') crypto.pbkdf2Sync(password, salt, 10000, 64).toString 'base64' module.exports = mongoose.model('User', UserSchema)
[ { "context": "then return false\n\t# List from https://github.com/substack/provinces\n\tcountriesUsingStates = ['US', 'GB', 'C", "end": 6400, "score": 0.9796277284622192, "start": 6392, "tag": "USERNAME", "value": "substack" }, { "context": "ces = (priceId) ->\n\tenvKey = if isEnvPro...
test4.coffee
Cottin/AutoRequire
0
{any, contains, curry, empty, isEmpty, isNil, keys, length, match, replace, test, toUpper, type} = R = require 'ramda' #auto_require: ramda {$, sf0, satisfies} = RE = require 'ramda-extras' #auto_require: ramda-extras [ːkeys] = ['keys'] #auto_sugar qq = (f) -> console.log match(/return (.*);/, f.toString())[1], f() qqq = (...args) -> console.log ...args _ = (...xs) -> xs require 'dayjs/locale/en-gb' dayjs = require 'dayjs' dayjs.locale('en-gb') # en-gb starts week on monday, en does not quarterOfYear = require 'dayjs/plugin/quarterOfYear' dayjs.extend quarterOfYear weekOfYear = require 'dayjs/plugin/weekOfYear' dayjs.extend weekOfYear {WeirdError} = require './errors' _YYYYMMDD = 'YYYY-MM-DD' ###### VERY EXPERIMENTAL, WATCH OUT #################### # Crashes popsiql and gives warning in react... not worth it :) # ramdaProxy = (o) -> # return new Proxy o, # get: (target, prop) -> # f = R[prop] # if f.length == 1 then () -> ramdaProxy f target # else if f.length == 2 then (x) -> ramdaProxy f x, target # else if f.length == 3 then throw new Error 'r() does not support functions with 3 arguments yet' # else throw new Error ':::' + prop # Object.prototype.r = () -> ramdaProxy @ ################# NEW IDEA ############################# # https://stackoverflow.com/a/20728736 # ramdaProxy = (_o) -> # if _o != Object _o then o = Object _o # else o = _o # return new Proxy o, # get: (target, prop) -> # f = R[prop] # if !f then f = RE[prop] # console.log prop # if !f then target[prop] # else if f.length == 1 then ramdaProxy f target # else if f.length == 2 then (x) -> ramdaProxy f x, target # else if f.length > 2 then throw new Error 'r() does not support functions with 3 arguments yet' # ext_obj = [ːkeys] # exts = ext_obj.concat [], [] # Object.defineProperty Object.prototype, 'r', # value: () -> # return ramdaProxy @ # for k in exts # if Object.prototype[k] then continue # Object.defineProperty Object.prototype, k, # value: () -> # f = R[k] # if !f then f = RE[k] # if f.length == 1 then () -> ramdaProxy f @ # else if f.length == 2 then (x) -> ramdaProxy f x, @ # else if f.length == 3 then throw new Error 'ramdaExt does not support functions with 3 arguments yet' # else throw new Error ':::' + prop # console.log {a: 1}.r().keys.length # test1 = {a: 1}.r().keys.length # console.log test1 # console.log test1.gt(1) # if !test1.gt(1) then console.log 'Problem' # if Boolean(false) then console.log 'Propblem x 2' # console.log Number(1) > 2 # Object.defineProperty Object.prototype, 'reverse', # value: () -> # return reverse @ # console.log [1, 2, 3] .reverse() ######################################################## # Many libraries behave different based on NODE_ENV in optimization, logging etc. # To keep environments as simialar as possible to prod we keep NODE_ENV set to production and use ENV instead. # Local: NODE_ENV=dev ENV=dev, Test: NODE_ENV=production ENV=test, Prod: NODE_ENV=production ENV=prod isEnvProd = () -> process.env.ENV == 'prod' isEnvProdOrTest = () -> process.env.ENV == 'prod' || process.env.ENV == 'test' isEnvDev = () -> process.env.ENV == 'dev' # Proxy for date related utils df = # Mo = 0, Su = 6 dayOfWeek: (date) -> dow = dayjs(date).day() if dow == 0 then 6 else dow - 1 format: curry (format, _date) -> if type(_date) == 'Number' && _date < 9000000000 then date = 1000 * _date # epoch seconds to milliseconds else date = _date if format == 'W' then dayjs(date).week() # shorthand for simple format W and Q else if format == 'Q' then dayjs(date).quarter() else if format == 'Dth' dateS = dayjs(date).format 'D' dateI = parseInt dateS ordinal = switch dateI when 1 then 'st' when 2 then 'nd' when 3 then 'rd' else 'th' return "#{dateS}#{ordinal}" else dayjs(date).format(format) diff: curry (early, late, unit) -> dayjs(late).diff(early, unit) get: curry (unit, date) -> dayjs(date).get(unit) isAfter: (date1, date2, unit = undefined) -> dayjs(date1).isAfter(date2, unit) isSame: (date1, date2, unit = undefined) -> dayjs(date1).isSame(date2, unit) yyyymmdd: (date) -> dayjs(date).format 'YYYY-MM-DD' # Tid mostly handles dates and we save quite a bit of complexity by defaulting to not care about time add: curry (num, unit, date) -> dayjs(date).add(num, unit).format(_YYYYMMDD) subtract: curry (num, unit, date) -> dayjs(date).subtract(num, unit).format(_YYYYMMDD) startOf: curry (unit, date) -> dayjs(date).startOf(unit).format(_YYYYMMDD) endOf: curry (unit, date) -> dayjs(date).endOf(unit).format(_YYYYMMDD) t: # use df.t if you need to handle time and not only date add: curry (num, unit, date) -> dayjs(date).add(num, unit).format() subtract: curry (num, unit, date) -> dayjs(date).subtract(num, unit).format() startOf: curry (unit, date) -> dayjs(date).startOf(unit).format() endOf: curry (unit, date) -> dayjs(date).endOf(unit).format() sleep = (ms) -> new Promise (resolve) -> setTimeout(resolve, ms) toShortString = (x) -> if 'Array' == type x len = length x if len == 0 then return "[] (empty)" else if len == 1 then return "[ {} ] (1 item)" else if len == 2 then return "[ {}, {} ] (2 items)" else if len > 2 then return "[ {}, {}, ... ] (#{len} items)" else if 'Object' == type x return "{ id: #{x.id}, ... }" else return res ensureSpec = (o, spec, errorMsg) -> res = satisfies o, spec if !isEmpty res then throw new Error "#{errorMsg} #{sf0 res}" vatFor = (countryCode) -> eu = AT: 20, BE: 21, BG: 20, CY: 19, CZ: 21, DE: 19, DK: 25, EE: 20, EL: 24, ES: 21, FI: 24, FR: 20, HR: 25, HU: 27, IE: 23, IT: 22, LT: 21, LU: 17, LV: 21, MT: 18, NL: 21, PL: 23, PT: 23, RO: 19, SE: 25, SI: 22, SK: 20, UK: 20 return eu[countryCode] || 0 isEU = (countryCode) -> vatFor(countryCode) > 0 isEurope = (countryCode) -> europeanOutsideEU = ['AL', 'AD', 'AM', 'BY', 'BA', 'FO', 'GE', 'GI', 'IS', 'IM', 'XK', 'LI', 'MK', 'MD', 'MC', 'MN', 'NO', 'RU', 'SM', 'RS', 'CH', 'TR', 'UA', 'GB', 'VA'] if vatFor(countryCode) > 0 then true else if contains countryCode, europeanOutsideEU then true else false parseVAT = (vat) -> if isNil vat then return [undefined, undefined] return [toUpper(vat.substr(0, 2)), vat.substr(2)] countryUsesStates = (countryCode) -> if !countryCode then return false # List from https://github.com/substack/provinces countriesUsingStates = ['US', 'GB', 'CA', 'MX', 'AU', 'CN', 'DE', 'BE', 'NL', 'DK', 'TR', 'ID', 'JO', 'IN', 'KH', 'ET', 'PE', 'CU', 'AR', 'CL', 'BO', 'ES', 'BD', 'PK', 'NG', 'JP', 'AT', 'BR', 'PH', 'VN', 'CR'] return contains countryCode, countriesUsingStates countryStateType = (countryCode) -> switch countryCode when 'US' then 'State' when 'BE' then 'Province' else 'State, provice, region' currencyFor = (countryCode) -> if countryCode == 'UK' then return 'GBP' if countryCode == 'SE' then return 'SEK' else if isEurope countryCode then return 'EUR' else return 'USD' currencySymbol = (currency) -> switch currency when 'GBP' then '£' when 'EUR' then '€' when 'USD' then '$' when 'SEK' then 'kr' else '$' # priceFor = (currency) -> # switch currency # when 'GBP' then 8000000 # when 'EUR' then 9000000 # when 'USD' then 9000000 # when 'SEK' then 90000000 # else 9000000 # monthlyToYearly = (monthlyPrice) -> monthlyPrice * 0.85 formatPrice = (n, removeZero = false) -> if removeZero && n % 100 == 0 then return '' + n/100 return '' + (n/100).toFixed(2) formatCurrency = (amount, currency, removeZero = false) -> switch currency when 'GBP' then "£#{formatPrice amount, removeZero}" when 'EUR' then "#{formatPrice amount, removeZero} €" when 'SEK' then "#{replace('.', ',', formatPrice(amount, removeZero))} kr" else "$#{formatPrice amount, removeZero}" # else throw new Error "NYI currency #{currency}" _currentDeal = 'from20201001' _deals = from20201001: test: month: USD: {priceId: 'price_1HMxiIDDW8849IySx1WgJm0m', amount: 900} EUR: {priceId: 'price_1HMxikDDW8849IySNCSZ4vGb', amount: 900} SEK: {priceId: 'price_1HACR4DDW8849IySoUIiUlUp', amount: 9000} year: USD: {priceId: 'price_1HL8waDDW8849IySoZj3eH4W', amount: 9180} EUR: {priceId: 'price_1HL8wuDDW8849IySITuWLYNu', amount: 9180} SEK: {priceId: 'price_1HL8vqDDW8849IySE16PEZQV', amount: 91800} prod: todo: 1 getPrices = (priceId) -> envKey = if isEnvProd() then 'prod' else 'test' # ENV=dev gives 'test' here if !priceId then return _deals[_currentDeal][envKey] pricesToSearch = null for deal, envs of _deals for interval, currencies of envs[envKey] for currency, priceDef of currencies if priceId == priceDef.priceId then return envs[envKey] throw new WeirdError "priceId #{priceId} does not match any existing prices" getPriceFor = ({isYear, currency}) -> prices = getPrices() return prices[isYear && 'year' || 'month'][currency] getPriceFor2 = ({isYear, currency}) -> prices = getPrices() return prices[isYear && 'year' || 'month'][currency] getPrice = ({isYear, country, useVatNo, currentPriceId = null}) -> currency = currencyFor country vatPercent = vatFor country prices = getPrices currentPriceId period = if isYear then 'year' else 'month' if isYear then pricePerMonth = prices.year[currency].amount / 12 else pricePerMonth = prices.month[currency].amount pricePerMonthF = formatCurrency pricePerMonth, currency subtotal = if isYear then pricePerMonth * 12 else pricePerMonth subtotalF = formatCurrency subtotal, currency vat = subtotal * vatPercent / 100 vatF = formatCurrency vat, currency if useVatNo vat = 0 vatPercent = 0 total = subtotal + vat totalF = formatCurrency subtotal, currency return {total, totalF, subtotal, subtotalF, vatPercent, vat, vatF, period, pricePerMonth, pricePerMonthF} #auto_export: none_ module.exports = {isEnvProd, isEnvProdOrTest, isEnvDev, df, sleep, toShortString, ensureSpec, vatFor, isEU, isEurope, parseVAT, countryUsesStates, countryStateType, currencyFor, currencySymbol, formatPrice, formatCurrency, getPrices, getPriceFor, getPriceFor2, getPrice}
65829
{any, contains, curry, empty, isEmpty, isNil, keys, length, match, replace, test, toUpper, type} = R = require 'ramda' #auto_require: ramda {$, sf0, satisfies} = RE = require 'ramda-extras' #auto_require: ramda-extras [ːkeys] = ['keys'] #auto_sugar qq = (f) -> console.log match(/return (.*);/, f.toString())[1], f() qqq = (...args) -> console.log ...args _ = (...xs) -> xs require 'dayjs/locale/en-gb' dayjs = require 'dayjs' dayjs.locale('en-gb') # en-gb starts week on monday, en does not quarterOfYear = require 'dayjs/plugin/quarterOfYear' dayjs.extend quarterOfYear weekOfYear = require 'dayjs/plugin/weekOfYear' dayjs.extend weekOfYear {WeirdError} = require './errors' _YYYYMMDD = 'YYYY-MM-DD' ###### VERY EXPERIMENTAL, WATCH OUT #################### # Crashes popsiql and gives warning in react... not worth it :) # ramdaProxy = (o) -> # return new Proxy o, # get: (target, prop) -> # f = R[prop] # if f.length == 1 then () -> ramdaProxy f target # else if f.length == 2 then (x) -> ramdaProxy f x, target # else if f.length == 3 then throw new Error 'r() does not support functions with 3 arguments yet' # else throw new Error ':::' + prop # Object.prototype.r = () -> ramdaProxy @ ################# NEW IDEA ############################# # https://stackoverflow.com/a/20728736 # ramdaProxy = (_o) -> # if _o != Object _o then o = Object _o # else o = _o # return new Proxy o, # get: (target, prop) -> # f = R[prop] # if !f then f = RE[prop] # console.log prop # if !f then target[prop] # else if f.length == 1 then ramdaProxy f target # else if f.length == 2 then (x) -> ramdaProxy f x, target # else if f.length > 2 then throw new Error 'r() does not support functions with 3 arguments yet' # ext_obj = [ːkeys] # exts = ext_obj.concat [], [] # Object.defineProperty Object.prototype, 'r', # value: () -> # return ramdaProxy @ # for k in exts # if Object.prototype[k] then continue # Object.defineProperty Object.prototype, k, # value: () -> # f = R[k] # if !f then f = RE[k] # if f.length == 1 then () -> ramdaProxy f @ # else if f.length == 2 then (x) -> ramdaProxy f x, @ # else if f.length == 3 then throw new Error 'ramdaExt does not support functions with 3 arguments yet' # else throw new Error ':::' + prop # console.log {a: 1}.r().keys.length # test1 = {a: 1}.r().keys.length # console.log test1 # console.log test1.gt(1) # if !test1.gt(1) then console.log 'Problem' # if Boolean(false) then console.log 'Propblem x 2' # console.log Number(1) > 2 # Object.defineProperty Object.prototype, 'reverse', # value: () -> # return reverse @ # console.log [1, 2, 3] .reverse() ######################################################## # Many libraries behave different based on NODE_ENV in optimization, logging etc. # To keep environments as simialar as possible to prod we keep NODE_ENV set to production and use ENV instead. # Local: NODE_ENV=dev ENV=dev, Test: NODE_ENV=production ENV=test, Prod: NODE_ENV=production ENV=prod isEnvProd = () -> process.env.ENV == 'prod' isEnvProdOrTest = () -> process.env.ENV == 'prod' || process.env.ENV == 'test' isEnvDev = () -> process.env.ENV == 'dev' # Proxy for date related utils df = # Mo = 0, Su = 6 dayOfWeek: (date) -> dow = dayjs(date).day() if dow == 0 then 6 else dow - 1 format: curry (format, _date) -> if type(_date) == 'Number' && _date < 9000000000 then date = 1000 * _date # epoch seconds to milliseconds else date = _date if format == 'W' then dayjs(date).week() # shorthand for simple format W and Q else if format == 'Q' then dayjs(date).quarter() else if format == 'Dth' dateS = dayjs(date).format 'D' dateI = parseInt dateS ordinal = switch dateI when 1 then 'st' when 2 then 'nd' when 3 then 'rd' else 'th' return "#{dateS}#{ordinal}" else dayjs(date).format(format) diff: curry (early, late, unit) -> dayjs(late).diff(early, unit) get: curry (unit, date) -> dayjs(date).get(unit) isAfter: (date1, date2, unit = undefined) -> dayjs(date1).isAfter(date2, unit) isSame: (date1, date2, unit = undefined) -> dayjs(date1).isSame(date2, unit) yyyymmdd: (date) -> dayjs(date).format 'YYYY-MM-DD' # Tid mostly handles dates and we save quite a bit of complexity by defaulting to not care about time add: curry (num, unit, date) -> dayjs(date).add(num, unit).format(_YYYYMMDD) subtract: curry (num, unit, date) -> dayjs(date).subtract(num, unit).format(_YYYYMMDD) startOf: curry (unit, date) -> dayjs(date).startOf(unit).format(_YYYYMMDD) endOf: curry (unit, date) -> dayjs(date).endOf(unit).format(_YYYYMMDD) t: # use df.t if you need to handle time and not only date add: curry (num, unit, date) -> dayjs(date).add(num, unit).format() subtract: curry (num, unit, date) -> dayjs(date).subtract(num, unit).format() startOf: curry (unit, date) -> dayjs(date).startOf(unit).format() endOf: curry (unit, date) -> dayjs(date).endOf(unit).format() sleep = (ms) -> new Promise (resolve) -> setTimeout(resolve, ms) toShortString = (x) -> if 'Array' == type x len = length x if len == 0 then return "[] (empty)" else if len == 1 then return "[ {} ] (1 item)" else if len == 2 then return "[ {}, {} ] (2 items)" else if len > 2 then return "[ {}, {}, ... ] (#{len} items)" else if 'Object' == type x return "{ id: #{x.id}, ... }" else return res ensureSpec = (o, spec, errorMsg) -> res = satisfies o, spec if !isEmpty res then throw new Error "#{errorMsg} #{sf0 res}" vatFor = (countryCode) -> eu = AT: 20, BE: 21, BG: 20, CY: 19, CZ: 21, DE: 19, DK: 25, EE: 20, EL: 24, ES: 21, FI: 24, FR: 20, HR: 25, HU: 27, IE: 23, IT: 22, LT: 21, LU: 17, LV: 21, MT: 18, NL: 21, PL: 23, PT: 23, RO: 19, SE: 25, SI: 22, SK: 20, UK: 20 return eu[countryCode] || 0 isEU = (countryCode) -> vatFor(countryCode) > 0 isEurope = (countryCode) -> europeanOutsideEU = ['AL', 'AD', 'AM', 'BY', 'BA', 'FO', 'GE', 'GI', 'IS', 'IM', 'XK', 'LI', 'MK', 'MD', 'MC', 'MN', 'NO', 'RU', 'SM', 'RS', 'CH', 'TR', 'UA', 'GB', 'VA'] if vatFor(countryCode) > 0 then true else if contains countryCode, europeanOutsideEU then true else false parseVAT = (vat) -> if isNil vat then return [undefined, undefined] return [toUpper(vat.substr(0, 2)), vat.substr(2)] countryUsesStates = (countryCode) -> if !countryCode then return false # List from https://github.com/substack/provinces countriesUsingStates = ['US', 'GB', 'CA', 'MX', 'AU', 'CN', 'DE', 'BE', 'NL', 'DK', 'TR', 'ID', 'JO', 'IN', 'KH', 'ET', 'PE', 'CU', 'AR', 'CL', 'BO', 'ES', 'BD', 'PK', 'NG', 'JP', 'AT', 'BR', 'PH', 'VN', 'CR'] return contains countryCode, countriesUsingStates countryStateType = (countryCode) -> switch countryCode when 'US' then 'State' when 'BE' then 'Province' else 'State, provice, region' currencyFor = (countryCode) -> if countryCode == 'UK' then return 'GBP' if countryCode == 'SE' then return 'SEK' else if isEurope countryCode then return 'EUR' else return 'USD' currencySymbol = (currency) -> switch currency when 'GBP' then '£' when 'EUR' then '€' when 'USD' then '$' when 'SEK' then 'kr' else '$' # priceFor = (currency) -> # switch currency # when 'GBP' then 8000000 # when 'EUR' then 9000000 # when 'USD' then 9000000 # when 'SEK' then 90000000 # else 9000000 # monthlyToYearly = (monthlyPrice) -> monthlyPrice * 0.85 formatPrice = (n, removeZero = false) -> if removeZero && n % 100 == 0 then return '' + n/100 return '' + (n/100).toFixed(2) formatCurrency = (amount, currency, removeZero = false) -> switch currency when 'GBP' then "£#{formatPrice amount, removeZero}" when 'EUR' then "#{formatPrice amount, removeZero} €" when 'SEK' then "#{replace('.', ',', formatPrice(amount, removeZero))} kr" else "$#{formatPrice amount, removeZero}" # else throw new Error "NYI currency #{currency}" _currentDeal = 'from20201001' _deals = from20201001: test: month: USD: {priceId: 'price_1HMxiIDDW8849IySx1WgJm0m', amount: 900} EUR: {priceId: 'price_1HMxikDDW8849IySNCSZ4vGb', amount: 900} SEK: {priceId: 'price_1HACR4DDW8849IySoUIiUlUp', amount: 9000} year: USD: {priceId: 'price_1HL8waDDW8849IySoZj3eH4W', amount: 9180} EUR: {priceId: 'price_1HL8wuDDW8849IySITuWLYNu', amount: 9180} SEK: {priceId: 'price_1HL8vqDDW8849IySE16PEZQV', amount: 91800} prod: todo: 1 getPrices = (priceId) -> envKey = if isEnvProd() then '<KEY>' else '<KEY>' # ENV=dev gives 'test' here if !priceId then return _deals[_currentDeal][envKey] pricesToSearch = null for deal, envs of _deals for interval, currencies of envs[envKey] for currency, priceDef of currencies if priceId == priceDef.priceId then return envs[envKey] throw new WeirdError "priceId #{priceId} does not match any existing prices" getPriceFor = ({isYear, currency}) -> prices = getPrices() return prices[isYear && 'year' || 'month'][currency] getPriceFor2 = ({isYear, currency}) -> prices = getPrices() return prices[isYear && 'year' || 'month'][currency] getPrice = ({isYear, country, useVatNo, currentPriceId = null}) -> currency = currencyFor country vatPercent = vatFor country prices = getPrices currentPriceId period = if isYear then 'year' else 'month' if isYear then pricePerMonth = prices.year[currency].amount / 12 else pricePerMonth = prices.month[currency].amount pricePerMonthF = formatCurrency pricePerMonth, currency subtotal = if isYear then pricePerMonth * 12 else pricePerMonth subtotalF = formatCurrency subtotal, currency vat = subtotal * vatPercent / 100 vatF = formatCurrency vat, currency if useVatNo vat = 0 vatPercent = 0 total = subtotal + vat totalF = formatCurrency subtotal, currency return {total, totalF, subtotal, subtotalF, vatPercent, vat, vatF, period, pricePerMonth, pricePerMonthF} #auto_export: none_ module.exports = {isEnvProd, isEnvProdOrTest, isEnvDev, df, sleep, toShortString, ensureSpec, vatFor, isEU, isEurope, parseVAT, countryUsesStates, countryStateType, currencyFor, currencySymbol, formatPrice, formatCurrency, getPrices, getPriceFor, getPriceFor2, getPrice}
true
{any, contains, curry, empty, isEmpty, isNil, keys, length, match, replace, test, toUpper, type} = R = require 'ramda' #auto_require: ramda {$, sf0, satisfies} = RE = require 'ramda-extras' #auto_require: ramda-extras [ːkeys] = ['keys'] #auto_sugar qq = (f) -> console.log match(/return (.*);/, f.toString())[1], f() qqq = (...args) -> console.log ...args _ = (...xs) -> xs require 'dayjs/locale/en-gb' dayjs = require 'dayjs' dayjs.locale('en-gb') # en-gb starts week on monday, en does not quarterOfYear = require 'dayjs/plugin/quarterOfYear' dayjs.extend quarterOfYear weekOfYear = require 'dayjs/plugin/weekOfYear' dayjs.extend weekOfYear {WeirdError} = require './errors' _YYYYMMDD = 'YYYY-MM-DD' ###### VERY EXPERIMENTAL, WATCH OUT #################### # Crashes popsiql and gives warning in react... not worth it :) # ramdaProxy = (o) -> # return new Proxy o, # get: (target, prop) -> # f = R[prop] # if f.length == 1 then () -> ramdaProxy f target # else if f.length == 2 then (x) -> ramdaProxy f x, target # else if f.length == 3 then throw new Error 'r() does not support functions with 3 arguments yet' # else throw new Error ':::' + prop # Object.prototype.r = () -> ramdaProxy @ ################# NEW IDEA ############################# # https://stackoverflow.com/a/20728736 # ramdaProxy = (_o) -> # if _o != Object _o then o = Object _o # else o = _o # return new Proxy o, # get: (target, prop) -> # f = R[prop] # if !f then f = RE[prop] # console.log prop # if !f then target[prop] # else if f.length == 1 then ramdaProxy f target # else if f.length == 2 then (x) -> ramdaProxy f x, target # else if f.length > 2 then throw new Error 'r() does not support functions with 3 arguments yet' # ext_obj = [ːkeys] # exts = ext_obj.concat [], [] # Object.defineProperty Object.prototype, 'r', # value: () -> # return ramdaProxy @ # for k in exts # if Object.prototype[k] then continue # Object.defineProperty Object.prototype, k, # value: () -> # f = R[k] # if !f then f = RE[k] # if f.length == 1 then () -> ramdaProxy f @ # else if f.length == 2 then (x) -> ramdaProxy f x, @ # else if f.length == 3 then throw new Error 'ramdaExt does not support functions with 3 arguments yet' # else throw new Error ':::' + prop # console.log {a: 1}.r().keys.length # test1 = {a: 1}.r().keys.length # console.log test1 # console.log test1.gt(1) # if !test1.gt(1) then console.log 'Problem' # if Boolean(false) then console.log 'Propblem x 2' # console.log Number(1) > 2 # Object.defineProperty Object.prototype, 'reverse', # value: () -> # return reverse @ # console.log [1, 2, 3] .reverse() ######################################################## # Many libraries behave different based on NODE_ENV in optimization, logging etc. # To keep environments as simialar as possible to prod we keep NODE_ENV set to production and use ENV instead. # Local: NODE_ENV=dev ENV=dev, Test: NODE_ENV=production ENV=test, Prod: NODE_ENV=production ENV=prod isEnvProd = () -> process.env.ENV == 'prod' isEnvProdOrTest = () -> process.env.ENV == 'prod' || process.env.ENV == 'test' isEnvDev = () -> process.env.ENV == 'dev' # Proxy for date related utils df = # Mo = 0, Su = 6 dayOfWeek: (date) -> dow = dayjs(date).day() if dow == 0 then 6 else dow - 1 format: curry (format, _date) -> if type(_date) == 'Number' && _date < 9000000000 then date = 1000 * _date # epoch seconds to milliseconds else date = _date if format == 'W' then dayjs(date).week() # shorthand for simple format W and Q else if format == 'Q' then dayjs(date).quarter() else if format == 'Dth' dateS = dayjs(date).format 'D' dateI = parseInt dateS ordinal = switch dateI when 1 then 'st' when 2 then 'nd' when 3 then 'rd' else 'th' return "#{dateS}#{ordinal}" else dayjs(date).format(format) diff: curry (early, late, unit) -> dayjs(late).diff(early, unit) get: curry (unit, date) -> dayjs(date).get(unit) isAfter: (date1, date2, unit = undefined) -> dayjs(date1).isAfter(date2, unit) isSame: (date1, date2, unit = undefined) -> dayjs(date1).isSame(date2, unit) yyyymmdd: (date) -> dayjs(date).format 'YYYY-MM-DD' # Tid mostly handles dates and we save quite a bit of complexity by defaulting to not care about time add: curry (num, unit, date) -> dayjs(date).add(num, unit).format(_YYYYMMDD) subtract: curry (num, unit, date) -> dayjs(date).subtract(num, unit).format(_YYYYMMDD) startOf: curry (unit, date) -> dayjs(date).startOf(unit).format(_YYYYMMDD) endOf: curry (unit, date) -> dayjs(date).endOf(unit).format(_YYYYMMDD) t: # use df.t if you need to handle time and not only date add: curry (num, unit, date) -> dayjs(date).add(num, unit).format() subtract: curry (num, unit, date) -> dayjs(date).subtract(num, unit).format() startOf: curry (unit, date) -> dayjs(date).startOf(unit).format() endOf: curry (unit, date) -> dayjs(date).endOf(unit).format() sleep = (ms) -> new Promise (resolve) -> setTimeout(resolve, ms) toShortString = (x) -> if 'Array' == type x len = length x if len == 0 then return "[] (empty)" else if len == 1 then return "[ {} ] (1 item)" else if len == 2 then return "[ {}, {} ] (2 items)" else if len > 2 then return "[ {}, {}, ... ] (#{len} items)" else if 'Object' == type x return "{ id: #{x.id}, ... }" else return res ensureSpec = (o, spec, errorMsg) -> res = satisfies o, spec if !isEmpty res then throw new Error "#{errorMsg} #{sf0 res}" vatFor = (countryCode) -> eu = AT: 20, BE: 21, BG: 20, CY: 19, CZ: 21, DE: 19, DK: 25, EE: 20, EL: 24, ES: 21, FI: 24, FR: 20, HR: 25, HU: 27, IE: 23, IT: 22, LT: 21, LU: 17, LV: 21, MT: 18, NL: 21, PL: 23, PT: 23, RO: 19, SE: 25, SI: 22, SK: 20, UK: 20 return eu[countryCode] || 0 isEU = (countryCode) -> vatFor(countryCode) > 0 isEurope = (countryCode) -> europeanOutsideEU = ['AL', 'AD', 'AM', 'BY', 'BA', 'FO', 'GE', 'GI', 'IS', 'IM', 'XK', 'LI', 'MK', 'MD', 'MC', 'MN', 'NO', 'RU', 'SM', 'RS', 'CH', 'TR', 'UA', 'GB', 'VA'] if vatFor(countryCode) > 0 then true else if contains countryCode, europeanOutsideEU then true else false parseVAT = (vat) -> if isNil vat then return [undefined, undefined] return [toUpper(vat.substr(0, 2)), vat.substr(2)] countryUsesStates = (countryCode) -> if !countryCode then return false # List from https://github.com/substack/provinces countriesUsingStates = ['US', 'GB', 'CA', 'MX', 'AU', 'CN', 'DE', 'BE', 'NL', 'DK', 'TR', 'ID', 'JO', 'IN', 'KH', 'ET', 'PE', 'CU', 'AR', 'CL', 'BO', 'ES', 'BD', 'PK', 'NG', 'JP', 'AT', 'BR', 'PH', 'VN', 'CR'] return contains countryCode, countriesUsingStates countryStateType = (countryCode) -> switch countryCode when 'US' then 'State' when 'BE' then 'Province' else 'State, provice, region' currencyFor = (countryCode) -> if countryCode == 'UK' then return 'GBP' if countryCode == 'SE' then return 'SEK' else if isEurope countryCode then return 'EUR' else return 'USD' currencySymbol = (currency) -> switch currency when 'GBP' then '£' when 'EUR' then '€' when 'USD' then '$' when 'SEK' then 'kr' else '$' # priceFor = (currency) -> # switch currency # when 'GBP' then 8000000 # when 'EUR' then 9000000 # when 'USD' then 9000000 # when 'SEK' then 90000000 # else 9000000 # monthlyToYearly = (monthlyPrice) -> monthlyPrice * 0.85 formatPrice = (n, removeZero = false) -> if removeZero && n % 100 == 0 then return '' + n/100 return '' + (n/100).toFixed(2) formatCurrency = (amount, currency, removeZero = false) -> switch currency when 'GBP' then "£#{formatPrice amount, removeZero}" when 'EUR' then "#{formatPrice amount, removeZero} €" when 'SEK' then "#{replace('.', ',', formatPrice(amount, removeZero))} kr" else "$#{formatPrice amount, removeZero}" # else throw new Error "NYI currency #{currency}" _currentDeal = 'from20201001' _deals = from20201001: test: month: USD: {priceId: 'price_1HMxiIDDW8849IySx1WgJm0m', amount: 900} EUR: {priceId: 'price_1HMxikDDW8849IySNCSZ4vGb', amount: 900} SEK: {priceId: 'price_1HACR4DDW8849IySoUIiUlUp', amount: 9000} year: USD: {priceId: 'price_1HL8waDDW8849IySoZj3eH4W', amount: 9180} EUR: {priceId: 'price_1HL8wuDDW8849IySITuWLYNu', amount: 9180} SEK: {priceId: 'price_1HL8vqDDW8849IySE16PEZQV', amount: 91800} prod: todo: 1 getPrices = (priceId) -> envKey = if isEnvProd() then 'PI:KEY:<KEY>END_PI' else 'PI:KEY:<KEY>END_PI' # ENV=dev gives 'test' here if !priceId then return _deals[_currentDeal][envKey] pricesToSearch = null for deal, envs of _deals for interval, currencies of envs[envKey] for currency, priceDef of currencies if priceId == priceDef.priceId then return envs[envKey] throw new WeirdError "priceId #{priceId} does not match any existing prices" getPriceFor = ({isYear, currency}) -> prices = getPrices() return prices[isYear && 'year' || 'month'][currency] getPriceFor2 = ({isYear, currency}) -> prices = getPrices() return prices[isYear && 'year' || 'month'][currency] getPrice = ({isYear, country, useVatNo, currentPriceId = null}) -> currency = currencyFor country vatPercent = vatFor country prices = getPrices currentPriceId period = if isYear then 'year' else 'month' if isYear then pricePerMonth = prices.year[currency].amount / 12 else pricePerMonth = prices.month[currency].amount pricePerMonthF = formatCurrency pricePerMonth, currency subtotal = if isYear then pricePerMonth * 12 else pricePerMonth subtotalF = formatCurrency subtotal, currency vat = subtotal * vatPercent / 100 vatF = formatCurrency vat, currency if useVatNo vat = 0 vatPercent = 0 total = subtotal + vat totalF = formatCurrency subtotal, currency return {total, totalF, subtotal, subtotalF, vatPercent, vat, vatF, period, pricePerMonth, pricePerMonthF} #auto_export: none_ module.exports = {isEnvProd, isEnvProdOrTest, isEnvDev, df, sleep, toShortString, ensureSpec, vatFor, isEU, isEurope, parseVAT, countryUsesStates, countryStateType, currencyFor, currencySymbol, formatPrice, formatCurrency, getPrices, getPriceFor, getPriceFor2, getPrice}
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9984812140464783, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-http-proxy.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. startReq = -> nlistening++ return if nlistening < 2 client = http.get( port: PROXY_PORT path: "/test" , (res) -> console.error "got res" assert.equal 200, res.statusCode assert.equal "world", res.headers["hello"] assert.equal "text/plain", res.headers["content-type"] assert.deepEqual cookies, res.headers["set-cookie"] res.setEncoding "utf8" res.on "data", (chunk) -> body += chunk return res.on "end", -> proxy.close() backend.close() console.error "closed both" return return ) console.error "client req" return common = require("../common") assert = require("assert") http = require("http") url = require("url") PROXY_PORT = common.PORT BACKEND_PORT = common.PORT + 1 cookies = [ "session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT" "prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT" ] headers = "content-type": "text/plain" "set-cookie": cookies hello: "world" backend = http.createServer((req, res) -> console.error "backend request" res.writeHead 200, headers res.write "hello world\n" res.end() return ) proxy = http.createServer((req, res) -> console.error "proxy req headers: " + JSON.stringify(req.headers) proxy_req = http.get( port: BACKEND_PORT path: url.parse(req.url).pathname , (proxy_res) -> console.error "proxy res headers: " + JSON.stringify(proxy_res.headers) assert.equal "world", proxy_res.headers["hello"] assert.equal "text/plain", proxy_res.headers["content-type"] assert.deepEqual cookies, proxy_res.headers["set-cookie"] res.writeHead proxy_res.statusCode, proxy_res.headers proxy_res.on "data", (chunk) -> res.write chunk return proxy_res.on "end", -> res.end() console.error "proxy res" return return ) return ) body = "" nlistening = 0 console.error "listen proxy" proxy.listen PROXY_PORT, startReq console.error "listen backend" backend.listen BACKEND_PORT, startReq process.on "exit", -> assert.equal body, "hello world\n" return
53993
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. startReq = -> nlistening++ return if nlistening < 2 client = http.get( port: PROXY_PORT path: "/test" , (res) -> console.error "got res" assert.equal 200, res.statusCode assert.equal "world", res.headers["hello"] assert.equal "text/plain", res.headers["content-type"] assert.deepEqual cookies, res.headers["set-cookie"] res.setEncoding "utf8" res.on "data", (chunk) -> body += chunk return res.on "end", -> proxy.close() backend.close() console.error "closed both" return return ) console.error "client req" return common = require("../common") assert = require("assert") http = require("http") url = require("url") PROXY_PORT = common.PORT BACKEND_PORT = common.PORT + 1 cookies = [ "session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT" "prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT" ] headers = "content-type": "text/plain" "set-cookie": cookies hello: "world" backend = http.createServer((req, res) -> console.error "backend request" res.writeHead 200, headers res.write "hello world\n" res.end() return ) proxy = http.createServer((req, res) -> console.error "proxy req headers: " + JSON.stringify(req.headers) proxy_req = http.get( port: BACKEND_PORT path: url.parse(req.url).pathname , (proxy_res) -> console.error "proxy res headers: " + JSON.stringify(proxy_res.headers) assert.equal "world", proxy_res.headers["hello"] assert.equal "text/plain", proxy_res.headers["content-type"] assert.deepEqual cookies, proxy_res.headers["set-cookie"] res.writeHead proxy_res.statusCode, proxy_res.headers proxy_res.on "data", (chunk) -> res.write chunk return proxy_res.on "end", -> res.end() console.error "proxy res" return return ) return ) body = "" nlistening = 0 console.error "listen proxy" proxy.listen PROXY_PORT, startReq console.error "listen backend" backend.listen BACKEND_PORT, startReq process.on "exit", -> assert.equal body, "hello world\n" return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. startReq = -> nlistening++ return if nlistening < 2 client = http.get( port: PROXY_PORT path: "/test" , (res) -> console.error "got res" assert.equal 200, res.statusCode assert.equal "world", res.headers["hello"] assert.equal "text/plain", res.headers["content-type"] assert.deepEqual cookies, res.headers["set-cookie"] res.setEncoding "utf8" res.on "data", (chunk) -> body += chunk return res.on "end", -> proxy.close() backend.close() console.error "closed both" return return ) console.error "client req" return common = require("../common") assert = require("assert") http = require("http") url = require("url") PROXY_PORT = common.PORT BACKEND_PORT = common.PORT + 1 cookies = [ "session_token=; path=/; expires=Sun, 15-Sep-2030 13:48:52 GMT" "prefers_open_id=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT" ] headers = "content-type": "text/plain" "set-cookie": cookies hello: "world" backend = http.createServer((req, res) -> console.error "backend request" res.writeHead 200, headers res.write "hello world\n" res.end() return ) proxy = http.createServer((req, res) -> console.error "proxy req headers: " + JSON.stringify(req.headers) proxy_req = http.get( port: BACKEND_PORT path: url.parse(req.url).pathname , (proxy_res) -> console.error "proxy res headers: " + JSON.stringify(proxy_res.headers) assert.equal "world", proxy_res.headers["hello"] assert.equal "text/plain", proxy_res.headers["content-type"] assert.deepEqual cookies, proxy_res.headers["set-cookie"] res.writeHead proxy_res.statusCode, proxy_res.headers proxy_res.on "data", (chunk) -> res.write chunk return proxy_res.on "end", -> res.end() console.error "proxy res" return return ) return ) body = "" nlistening = 0 console.error "listen proxy" proxy.listen PROXY_PORT, startReq console.error "listen backend" backend.listen BACKEND_PORT, startReq process.on "exit", -> assert.equal body, "hello world\n" return
[ { "context": "unction periodically by given interval.\n * @author İsmail Demirbilek\n * @function\n###\nangular.module 'esef.frontend.re", "end": 285, "score": 0.9998935461044312, "start": 268, "tag": "NAME", "value": "İsmail Demirbilek" } ]
src/refresh/coffee/services/refresh.coffee
egemsoft/esef-frontend
0
'use strict' ###* * @ngdoc service * @name esef.frontend.refresh.services:refresh * @description * Refresh service implements a recursive periodical refresh function. * Provides easy to use simple API to run a function periodically by given interval. * @author İsmail Demirbilek * @function ### angular.module 'esef.frontend.refresh' .factory 'refresh', ($timeout) -> # set configurations timeoutPromise = null refreshInterval = 10000 working = false # create refresher refresh = (refreshCallback) -> # make self call periodically with refresh interval # timeout promise should be updated on top to cancel it inside callback! timeoutPromise = $timeout(-> refresh refreshCallback , refreshInterval) console.debug 'Auto refresh triggered.' refreshCallback() # public API ###* * @ngdoc object * @name setInterval * @methodOf esef.frontend.refresh.services:refresh * @param {number} interval - Interval in terms of milliseconds. * @returns {object} - refresh service to support chaining. * @description * Sets interval for refresh timeout which is set 10000 as default. * @function ### setInterval: (interval) -> refreshInterval = interval this ###* * @ngdoc object * @name start * @methodOf esef.frontend.refresh.services:refresh * @param {function} callback - Callback function to be run periodically. * @returns {object} - refresh service to support chaining. * @description * Main method which starts refreshing. Takes callback param that will be run on every period. * @function ### start: (callback) -> if !working working = true console.debug 'Starting refresh.' refresh callback else console.debug('Refresh is already started.'); this ###* * @ngdoc object * @name stop * @methodOf esef.frontend.refresh.services:refresh * @returns {object} - refresh service to support chaining. * @description * Stops refresh function if it is started. * @function ### stop: -> if working working = false $timeout.cancel timeoutPromise console.debug 'Stopped refreshing.' else console.debug 'Can\'t stop, already stopped refreshing.' this ###* * @ngdoc object * @name isStarted * @methodOf esef.frontend.refresh.services:refresh * @returns {object} - Refresh status true if it is started. * @description * Returns true if refresh function is running; false if it is not. * @function ### isStarted: -> working ###* * @ngdoc object * @name isStopped * @methodOf esef.frontend.refresh.services:refresh * @returns {object} - Refresh status true if it is stopped. * @description * Returns true if refresh function is not running; false if it is. * @function ### isStopped: -> !working
38076
'use strict' ###* * @ngdoc service * @name esef.frontend.refresh.services:refresh * @description * Refresh service implements a recursive periodical refresh function. * Provides easy to use simple API to run a function periodically by given interval. * @author <NAME> * @function ### angular.module 'esef.frontend.refresh' .factory 'refresh', ($timeout) -> # set configurations timeoutPromise = null refreshInterval = 10000 working = false # create refresher refresh = (refreshCallback) -> # make self call periodically with refresh interval # timeout promise should be updated on top to cancel it inside callback! timeoutPromise = $timeout(-> refresh refreshCallback , refreshInterval) console.debug 'Auto refresh triggered.' refreshCallback() # public API ###* * @ngdoc object * @name setInterval * @methodOf esef.frontend.refresh.services:refresh * @param {number} interval - Interval in terms of milliseconds. * @returns {object} - refresh service to support chaining. * @description * Sets interval for refresh timeout which is set 10000 as default. * @function ### setInterval: (interval) -> refreshInterval = interval this ###* * @ngdoc object * @name start * @methodOf esef.frontend.refresh.services:refresh * @param {function} callback - Callback function to be run periodically. * @returns {object} - refresh service to support chaining. * @description * Main method which starts refreshing. Takes callback param that will be run on every period. * @function ### start: (callback) -> if !working working = true console.debug 'Starting refresh.' refresh callback else console.debug('Refresh is already started.'); this ###* * @ngdoc object * @name stop * @methodOf esef.frontend.refresh.services:refresh * @returns {object} - refresh service to support chaining. * @description * Stops refresh function if it is started. * @function ### stop: -> if working working = false $timeout.cancel timeoutPromise console.debug 'Stopped refreshing.' else console.debug 'Can\'t stop, already stopped refreshing.' this ###* * @ngdoc object * @name isStarted * @methodOf esef.frontend.refresh.services:refresh * @returns {object} - Refresh status true if it is started. * @description * Returns true if refresh function is running; false if it is not. * @function ### isStarted: -> working ###* * @ngdoc object * @name isStopped * @methodOf esef.frontend.refresh.services:refresh * @returns {object} - Refresh status true if it is stopped. * @description * Returns true if refresh function is not running; false if it is. * @function ### isStopped: -> !working
true
'use strict' ###* * @ngdoc service * @name esef.frontend.refresh.services:refresh * @description * Refresh service implements a recursive periodical refresh function. * Provides easy to use simple API to run a function periodically by given interval. * @author PI:NAME:<NAME>END_PI * @function ### angular.module 'esef.frontend.refresh' .factory 'refresh', ($timeout) -> # set configurations timeoutPromise = null refreshInterval = 10000 working = false # create refresher refresh = (refreshCallback) -> # make self call periodically with refresh interval # timeout promise should be updated on top to cancel it inside callback! timeoutPromise = $timeout(-> refresh refreshCallback , refreshInterval) console.debug 'Auto refresh triggered.' refreshCallback() # public API ###* * @ngdoc object * @name setInterval * @methodOf esef.frontend.refresh.services:refresh * @param {number} interval - Interval in terms of milliseconds. * @returns {object} - refresh service to support chaining. * @description * Sets interval for refresh timeout which is set 10000 as default. * @function ### setInterval: (interval) -> refreshInterval = interval this ###* * @ngdoc object * @name start * @methodOf esef.frontend.refresh.services:refresh * @param {function} callback - Callback function to be run periodically. * @returns {object} - refresh service to support chaining. * @description * Main method which starts refreshing. Takes callback param that will be run on every period. * @function ### start: (callback) -> if !working working = true console.debug 'Starting refresh.' refresh callback else console.debug('Refresh is already started.'); this ###* * @ngdoc object * @name stop * @methodOf esef.frontend.refresh.services:refresh * @returns {object} - refresh service to support chaining. * @description * Stops refresh function if it is started. * @function ### stop: -> if working working = false $timeout.cancel timeoutPromise console.debug 'Stopped refreshing.' else console.debug 'Can\'t stop, already stopped refreshing.' this ###* * @ngdoc object * @name isStarted * @methodOf esef.frontend.refresh.services:refresh * @returns {object} - Refresh status true if it is started. * @description * Returns true if refresh function is running; false if it is not. * @function ### isStarted: -> working ###* * @ngdoc object * @name isStopped * @methodOf esef.frontend.refresh.services:refresh * @returns {object} - Refresh status true if it is stopped. * @description * Returns true if refresh function is not running; false if it is. * @function ### isStopped: -> !working
[ { "context": "# These are Ivan's SVG tools. They're private APIs, part of the im", "end": 16, "score": 0.8018726110458374, "start": 12, "tag": "NAME", "value": "Ivan" } ]
source/tools/svg.coffee
cdig/svga
4
# These are Ivan's SVG tools. They're private APIs, part of the implementation of SVGA. # They're not to be used by content, since they might endure breaking changes at any time. Take "DOMContentLoaded", ()-> # We give the main SVG an id in cd-core's gulpfile, so that we know which SVG to target. # There's only ever one SVGA in the current context, but there might be other SVGs # (eg: the header logo if this is a standalone deployed SVGA). # Also, we can't use getElementById because gulp-rev-all thinks it's a URL *facepalm* svg = document.querySelector "svg#svga" defs = svg.querySelector "defs" root = svg.getElementById "root" svgNS = "http://www.w3.org/2000/svg" xlinkNS = "http://www.w3.org/1999/xlink" # This is used to distinguish props from attrs, so we can set both with SVG.attr propNames = textContent: true # additional prop names will be listed here as needed # This is used to cache normalized keys, and to provide defaults for keys that shouldn't be normalized attrNames = gradientUnits: "gradientUnits" viewBox: "viewBox" SCOPE: "SCOPE" SYMBOL: "SYMBOL" # additional attr names will be listed here as needed # We want to wait until SVGReady fires before we change the structure of the DOM. # However, we can't just Take "SVGReady" at the top, because other systems want # to use these SVG tools in safe, non-structural ways before SVGReady has fired. # So we do this: SVGReady = false CheckSVGReady = ()-> SVGReady or (SVGReady = Take "SVGReady") Make "SVG", SVG = svg: svg defs: defs root: root create: (type, parent, attrs)-> elm = document.createElementNS svgNS, type SVG.attrs elm, attrs if attrs? SVG.append parent, elm if parent? elm # Composable clone: (source, parent, attrs)-> throw new Error "Clone source is undefined in SVG.clone(source, parent, attrs)" unless source? throw new Error "SVG.clone() called before SVGReady" unless CheckSVGReady() elm = document.createElementNS svgNS, "g" SVG.attr elm, attr.name, attr.value for attr in source.attributes SVG.attrs elm, id: null SVG.attrs elm, attrs if attrs? SVG.append elm, child.cloneNode true for child in source.childNodes SVG.append parent, elm if parent? elm # Composable append: (parent, child)-> throw new Error "SVG.append() called before SVGReady" unless CheckSVGReady() parent.appendChild child child # Composable prepend: (parent, child)-> throw new Error "SVG.prepend() called before SVGReady" unless CheckSVGReady() if parent.hasChildNodes() parent.insertBefore child, parent.firstChild else parent.appendChild child child # Composable remove: (parent, child)-> throw new Error "SVG.remove() called before SVGReady" unless CheckSVGReady() parent.removeChild child return child removeAllChildren: (parent)-> throw new Error "SVG.removeAllChildren() called before SVGReady" unless CheckSVGReady() while parent.children.length > 0 parent.removeChild parent.firstChild attrs: (elm, attrs)-> unless elm then throw new Error "SVG.attrs was called with a null element" unless typeof attrs is "object" then console.log attrs; throw new Error "SVG.attrs requires an object as the second argument, got ^" for k, v of attrs SVG.attr elm, k, v elm # Composable attr: (elm, k, v)-> unless elm then throw new Error "SVG.attr was called with a null element" unless typeof k is "string" then console.log k; throw new Error "SVG.attr requires a string as the second argument, got ^^^" if typeof v is "number" and isNaN v then console.log elm, k; throw new Error "SVG.attr was called with a NaN value for ^^^" elm._SVG_attr ?= {} # Note that we only do DOM->cache on a read call (not on a write call), # to slightly avoid intermingling DOM reads and writes, which causes thrashing. return elm._SVG_attr[k] ?= elm.getAttribute(k) if v is undefined # Read return v if elm._SVG_attr[k] is v # cache hit — bail elm._SVG_attr[k] = v # update cache return elm[k] = v if propNames[k]? # set DOM property ns = if k is "xlink:href" then xlinkNS else null k = attrNames[k] ?= k.replace(/([A-Z])/g,"-$1").toLowerCase() # Normalize camelCase into kebab-case if v? elm.setAttributeNS ns, k, v # set DOM attribute else # v is explicitly set to null (not undefined) elm.removeAttributeNS ns, k # remove DOM attribute return v # Not Composable styles: (elm, styles)-> unless elm then throw new Error "SVG.styles was called with a null element" unless typeof styles is "object" then console.log styles; throw new Error "SVG.styles requires an object as the second argument, got ^" SVG.style elm, k, v for k, v of styles elm # Composable style: (elm, k, v)-> unless elm then throw new Error "SVG.style was called with a null element" unless typeof k is "string" then console.log k; throw new Error "SVG.style requires a string as the second argument, got ^" if typeof v is "number" and isNaN v then console.log elm, k; throw new Error "SVG.style was called with a NaN value for ^^^" elm._SVG_style ?= {} return elm._SVG_style[k] ?= elm.style[k] if v is undefined if elm._SVG_style[k] isnt v elm.style[k] = elm._SVG_style[k] = v v # Not Composable
123388
# These are <NAME>'s SVG tools. They're private APIs, part of the implementation of SVGA. # They're not to be used by content, since they might endure breaking changes at any time. Take "DOMContentLoaded", ()-> # We give the main SVG an id in cd-core's gulpfile, so that we know which SVG to target. # There's only ever one SVGA in the current context, but there might be other SVGs # (eg: the header logo if this is a standalone deployed SVGA). # Also, we can't use getElementById because gulp-rev-all thinks it's a URL *facepalm* svg = document.querySelector "svg#svga" defs = svg.querySelector "defs" root = svg.getElementById "root" svgNS = "http://www.w3.org/2000/svg" xlinkNS = "http://www.w3.org/1999/xlink" # This is used to distinguish props from attrs, so we can set both with SVG.attr propNames = textContent: true # additional prop names will be listed here as needed # This is used to cache normalized keys, and to provide defaults for keys that shouldn't be normalized attrNames = gradientUnits: "gradientUnits" viewBox: "viewBox" SCOPE: "SCOPE" SYMBOL: "SYMBOL" # additional attr names will be listed here as needed # We want to wait until SVGReady fires before we change the structure of the DOM. # However, we can't just Take "SVGReady" at the top, because other systems want # to use these SVG tools in safe, non-structural ways before SVGReady has fired. # So we do this: SVGReady = false CheckSVGReady = ()-> SVGReady or (SVGReady = Take "SVGReady") Make "SVG", SVG = svg: svg defs: defs root: root create: (type, parent, attrs)-> elm = document.createElementNS svgNS, type SVG.attrs elm, attrs if attrs? SVG.append parent, elm if parent? elm # Composable clone: (source, parent, attrs)-> throw new Error "Clone source is undefined in SVG.clone(source, parent, attrs)" unless source? throw new Error "SVG.clone() called before SVGReady" unless CheckSVGReady() elm = document.createElementNS svgNS, "g" SVG.attr elm, attr.name, attr.value for attr in source.attributes SVG.attrs elm, id: null SVG.attrs elm, attrs if attrs? SVG.append elm, child.cloneNode true for child in source.childNodes SVG.append parent, elm if parent? elm # Composable append: (parent, child)-> throw new Error "SVG.append() called before SVGReady" unless CheckSVGReady() parent.appendChild child child # Composable prepend: (parent, child)-> throw new Error "SVG.prepend() called before SVGReady" unless CheckSVGReady() if parent.hasChildNodes() parent.insertBefore child, parent.firstChild else parent.appendChild child child # Composable remove: (parent, child)-> throw new Error "SVG.remove() called before SVGReady" unless CheckSVGReady() parent.removeChild child return child removeAllChildren: (parent)-> throw new Error "SVG.removeAllChildren() called before SVGReady" unless CheckSVGReady() while parent.children.length > 0 parent.removeChild parent.firstChild attrs: (elm, attrs)-> unless elm then throw new Error "SVG.attrs was called with a null element" unless typeof attrs is "object" then console.log attrs; throw new Error "SVG.attrs requires an object as the second argument, got ^" for k, v of attrs SVG.attr elm, k, v elm # Composable attr: (elm, k, v)-> unless elm then throw new Error "SVG.attr was called with a null element" unless typeof k is "string" then console.log k; throw new Error "SVG.attr requires a string as the second argument, got ^^^" if typeof v is "number" and isNaN v then console.log elm, k; throw new Error "SVG.attr was called with a NaN value for ^^^" elm._SVG_attr ?= {} # Note that we only do DOM->cache on a read call (not on a write call), # to slightly avoid intermingling DOM reads and writes, which causes thrashing. return elm._SVG_attr[k] ?= elm.getAttribute(k) if v is undefined # Read return v if elm._SVG_attr[k] is v # cache hit — bail elm._SVG_attr[k] = v # update cache return elm[k] = v if propNames[k]? # set DOM property ns = if k is "xlink:href" then xlinkNS else null k = attrNames[k] ?= k.replace(/([A-Z])/g,"-$1").toLowerCase() # Normalize camelCase into kebab-case if v? elm.setAttributeNS ns, k, v # set DOM attribute else # v is explicitly set to null (not undefined) elm.removeAttributeNS ns, k # remove DOM attribute return v # Not Composable styles: (elm, styles)-> unless elm then throw new Error "SVG.styles was called with a null element" unless typeof styles is "object" then console.log styles; throw new Error "SVG.styles requires an object as the second argument, got ^" SVG.style elm, k, v for k, v of styles elm # Composable style: (elm, k, v)-> unless elm then throw new Error "SVG.style was called with a null element" unless typeof k is "string" then console.log k; throw new Error "SVG.style requires a string as the second argument, got ^" if typeof v is "number" and isNaN v then console.log elm, k; throw new Error "SVG.style was called with a NaN value for ^^^" elm._SVG_style ?= {} return elm._SVG_style[k] ?= elm.style[k] if v is undefined if elm._SVG_style[k] isnt v elm.style[k] = elm._SVG_style[k] = v v # Not Composable
true
# These are PI:NAME:<NAME>END_PI's SVG tools. They're private APIs, part of the implementation of SVGA. # They're not to be used by content, since they might endure breaking changes at any time. Take "DOMContentLoaded", ()-> # We give the main SVG an id in cd-core's gulpfile, so that we know which SVG to target. # There's only ever one SVGA in the current context, but there might be other SVGs # (eg: the header logo if this is a standalone deployed SVGA). # Also, we can't use getElementById because gulp-rev-all thinks it's a URL *facepalm* svg = document.querySelector "svg#svga" defs = svg.querySelector "defs" root = svg.getElementById "root" svgNS = "http://www.w3.org/2000/svg" xlinkNS = "http://www.w3.org/1999/xlink" # This is used to distinguish props from attrs, so we can set both with SVG.attr propNames = textContent: true # additional prop names will be listed here as needed # This is used to cache normalized keys, and to provide defaults for keys that shouldn't be normalized attrNames = gradientUnits: "gradientUnits" viewBox: "viewBox" SCOPE: "SCOPE" SYMBOL: "SYMBOL" # additional attr names will be listed here as needed # We want to wait until SVGReady fires before we change the structure of the DOM. # However, we can't just Take "SVGReady" at the top, because other systems want # to use these SVG tools in safe, non-structural ways before SVGReady has fired. # So we do this: SVGReady = false CheckSVGReady = ()-> SVGReady or (SVGReady = Take "SVGReady") Make "SVG", SVG = svg: svg defs: defs root: root create: (type, parent, attrs)-> elm = document.createElementNS svgNS, type SVG.attrs elm, attrs if attrs? SVG.append parent, elm if parent? elm # Composable clone: (source, parent, attrs)-> throw new Error "Clone source is undefined in SVG.clone(source, parent, attrs)" unless source? throw new Error "SVG.clone() called before SVGReady" unless CheckSVGReady() elm = document.createElementNS svgNS, "g" SVG.attr elm, attr.name, attr.value for attr in source.attributes SVG.attrs elm, id: null SVG.attrs elm, attrs if attrs? SVG.append elm, child.cloneNode true for child in source.childNodes SVG.append parent, elm if parent? elm # Composable append: (parent, child)-> throw new Error "SVG.append() called before SVGReady" unless CheckSVGReady() parent.appendChild child child # Composable prepend: (parent, child)-> throw new Error "SVG.prepend() called before SVGReady" unless CheckSVGReady() if parent.hasChildNodes() parent.insertBefore child, parent.firstChild else parent.appendChild child child # Composable remove: (parent, child)-> throw new Error "SVG.remove() called before SVGReady" unless CheckSVGReady() parent.removeChild child return child removeAllChildren: (parent)-> throw new Error "SVG.removeAllChildren() called before SVGReady" unless CheckSVGReady() while parent.children.length > 0 parent.removeChild parent.firstChild attrs: (elm, attrs)-> unless elm then throw new Error "SVG.attrs was called with a null element" unless typeof attrs is "object" then console.log attrs; throw new Error "SVG.attrs requires an object as the second argument, got ^" for k, v of attrs SVG.attr elm, k, v elm # Composable attr: (elm, k, v)-> unless elm then throw new Error "SVG.attr was called with a null element" unless typeof k is "string" then console.log k; throw new Error "SVG.attr requires a string as the second argument, got ^^^" if typeof v is "number" and isNaN v then console.log elm, k; throw new Error "SVG.attr was called with a NaN value for ^^^" elm._SVG_attr ?= {} # Note that we only do DOM->cache on a read call (not on a write call), # to slightly avoid intermingling DOM reads and writes, which causes thrashing. return elm._SVG_attr[k] ?= elm.getAttribute(k) if v is undefined # Read return v if elm._SVG_attr[k] is v # cache hit — bail elm._SVG_attr[k] = v # update cache return elm[k] = v if propNames[k]? # set DOM property ns = if k is "xlink:href" then xlinkNS else null k = attrNames[k] ?= k.replace(/([A-Z])/g,"-$1").toLowerCase() # Normalize camelCase into kebab-case if v? elm.setAttributeNS ns, k, v # set DOM attribute else # v is explicitly set to null (not undefined) elm.removeAttributeNS ns, k # remove DOM attribute return v # Not Composable styles: (elm, styles)-> unless elm then throw new Error "SVG.styles was called with a null element" unless typeof styles is "object" then console.log styles; throw new Error "SVG.styles requires an object as the second argument, got ^" SVG.style elm, k, v for k, v of styles elm # Composable style: (elm, k, v)-> unless elm then throw new Error "SVG.style was called with a null element" unless typeof k is "string" then console.log k; throw new Error "SVG.style requires a string as the second argument, got ^" if typeof v is "number" and isNaN v then console.log elm, k; throw new Error "SVG.style was called with a NaN value for ^^^" elm._SVG_style ?= {} return elm._SVG_style[k] ?= elm.style[k] if v is undefined if elm._SVG_style[k] isnt v elm.style[k] = elm._SVG_style[k] = v v # Not Composable
[ { "context": "Table, 'foo', null, null,\n hashKeyName: 'bar'\n hashKeyType: 'S'\n .then (data) ", "end": 6663, "score": 0.5057412981987, "start": 6660, "tag": "KEY", "value": "bar" } ]
test/src/aws-translators.coffee
brianknight10/dynasty
155
chai = require('chai') expect = chai.expect chaiAsPromised = require('chai-as-promised') chai.use(chaiAsPromised) chance = require('chance').Chance() lib = require('../lib/lib')["aws-translators"] sinon = require('sinon') Promise = require('bluebird') describe 'aws-translators', () -> describe '#getKeySchema', () -> it 'should parse out a hash key from an aws response', () -> hashKeyName = chance.word() result = lib.getKeySchema( Table: KeySchema:[ AttributeName: hashKeyName KeyType: 'HASH' ] AttributeDefinitions: [ AttributeName: hashKeyName AttributeType: 'N' ] ) expect(result).to.have.property('hashKeyName') expect(result.hashKeyName).to.equal(hashKeyName) expect(result).to.have.property('hashKeyType') expect(result.hashKeyType).to.equal('N') it 'should parse out a range key from an aws response', () -> hashKeyName = chance.word() rangeKeyName = chance.word() result = lib.getKeySchema( Table: KeySchema:[ { AttributeName: hashKeyName KeyType: 'HASH' }, { AttributeName: rangeKeyName KeyType: 'RANGE' } ] AttributeDefinitions: [ { AttributeName: hashKeyName AttributeType: 'S' }, { AttributeName: rangeKeyName AttributeType: 'B' } ] ) describe '#deleteItem', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { deleteItemPromise: (params, callback) -> Promise.resolve('lol') } afterEach () -> sandbox.restore() it 'should return an object', () -> promise = lib.deleteItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(promise).to.be.an('object') it 'should return a promise', () -> promise = lib.deleteItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) promise.then((d) -> expect(d).to.equal('lol')) it 'should call deleteItem of aws', () -> sandbox.spy(dynastyTable.parent.dynamo, "deleteItemPromise") lib.deleteItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(dynastyTable.parent.dynamo.deleteItemPromise.calledOnce) it 'should call deleteItem of aws with extra params', () -> sandbox.spy(dynastyTable.parent.dynamo, "deleteItemPromise") options = ReturnValues: 'NONE' lib.deleteItem.call(dynastyTable, 'foo', options, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(dynastyTable.parent.dynamo.deleteItemPromise.calledOnce) expect(dynastyTable.parent.dynamo.deleteItemPromise.getCall(0).args[0]).to.include.keys('ReturnValues') it 'should send the table name to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "deleteItemPromise") promise = lib.deleteItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) promise.then () -> expect(dynastyTable.parent.dynamo.deleteItemPromise.calledOnce) params = dynastyTable.parent.dynamo.deleteItemPromise.getCall(0).args[0] expect(params.TableName).to.equal(dynastyTable.name) it 'should send the hash key to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "deleteItemPromise") promise = lib.deleteItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(dynastyTable.parent.dynamo.deleteItemPromise.calledOnce) params = dynastyTable.parent.dynamo.deleteItemPromise.getCall(0).args[0] expect(params.Key).to.include.keys('bar') expect(params.Key.bar).to.include.keys('S') expect(params.Key.bar.S).to.equal('foo') it 'should send the hash and range key to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "deleteItemPromise") promise = lib.deleteItem.call( dynastyTable, hash: 'lol' range: 'rofl', null, null, hashKeyName: 'bar' hashKeyType: 'S' rangeKeyName: 'foo' rangeKeyType: 'S') expect(dynastyTable.parent.dynamo.deleteItemPromise.calledOnce) params = dynastyTable.parent.dynamo.deleteItemPromise.getCall(0).args[0] expect(params.Key).to.include.keys('bar') expect(params.Key.bar).to.include.keys('S') expect(params.Key.bar.S).to.equal('lol') expect(params.Key).to.include.keys('foo') expect(params.Key.foo).to.include.keys('S') expect(params.Key.foo.S).to.equal('rofl') describe '#batchGetItem', () -> dynastyTable = null sandbox = null beforeEach () -> tableName = chance.name() sandbox = sinon.sandbox.create() dynastyTable = name: tableName parent: dynamo: batchGetItemPromise: (params, callback) -> result = {} result.Responses = {} result.Responses[tableName] = [ { foo: S: "bar" }, foo: S: "baz" bazzoo: N: 123 ] Promise.resolve(result); afterEach () -> sandbox.restore() it 'should return a sane response', () -> lib.batchGetItem .call dynastyTable, ['bar', 'baz'], null, hashKeyName: 'foo' hashKeyType: 'S' .then (data) -> expect(data).to.deep.equal([ { foo: 'bar' }, foo: 'baz' bazzoo: 123]) describe '#getItem', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { getItemPromise: (params, callback) -> Promise.resolve(Item: rofl: S: 'lol') } afterEach () -> sandbox.restore() it 'should return an object', () -> promise = lib.getItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(promise).to.be.an('object') it 'should return a promise', () -> lib.getItem .call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' .then (data) -> expect(data).to.deep.equal(rofl: 'lol') it 'should call getItem of aws', () -> sandbox.spy(dynastyTable.parent.dynamo, "getItemPromise") lib.getItem.call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' expect(dynastyTable.parent.dynamo.getItemPromise.calledOnce) expect(dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0].TableName).to.equal(dynastyTable.name) it 'should call getItem of aws with extra params', () -> sandbox.spy(dynastyTable.parent.dynamo, "getItemPromise") options = ProjectionExpression: 'id, name' lib.getItem.call dynastyTable, 'foo', options, null, hashKeyName: 'bar' hashKeyType: 'S' expect(dynastyTable.parent.dynamo.getItemPromise.calledOnce) expect(dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0].TableName).to.equal(dynastyTable.name) expect(dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0].ProjectionExpression).to.equal('id, name') it 'should send the table name to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "getItemPromise") lib.getItem .call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' .then () -> expect(dynastyTable.parent.dynamo.getItemPromise.calledOnce) params = dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0] expect(params.TableName).to.equal(dynastyTable.name) it 'should send the hash key to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "getItemPromise") promise = lib.getItem.call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' expect(dynastyTable.parent.dynamo.getItemPromise.calledOnce) params = dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0] expect(params.Key).to.include.keys('bar') expect(params.Key.bar).to.include.keys('S') expect(params.Key.bar.S).to.equal('foo') it 'should send the hash and range key to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "getItemPromise") promise = lib.getItem.call( dynastyTable, hash: 'lol' range: 'rofl', null, null, hashKeyName: 'bar' hashKeyType: 'S' rangeKeyName: 'foo' rangeKeyType: 'S') expect(dynastyTable.parent.dynamo.getItemPromise.calledOnce) params = dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0] expect(params.Key).to.include.keys('bar') expect(params.Key.bar).to.include.keys('S') expect(params.Key.bar.S).to.equal('lol') expect(params.Key).to.include.keys('foo') expect(params.Key.foo).to.include.keys('S') expect(params.Key.foo.S).to.equal('rofl') describe '#scanPromise', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { scanPromise: (params, callback) -> Promise.resolve(Items: rofl: S: 'lol') } afterEach () -> sandbox.restore() it 'should return an object', () -> promise = lib.scan.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(promise).to.be.an('object') it 'should return a promise', () -> lib.scan .call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' .then (data) -> expect(data).to.deep.equal(rofl: 'lol') it 'should call scan of aws', () -> sandbox.spy(dynastyTable.parent.dynamo, "scanPromise") lib.scan.call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' expect(dynastyTable.parent.dynamo.scanPromise.calledOnce) expect(dynastyTable.parent.dynamo.scanPromise.getCall(0).args[0].TableName).to.equal(dynastyTable.name) it 'should call scan of aws with extra params', () -> sandbox.spy(dynastyTable.parent.dynamo, "scanPromise") options = ReturnConsumedCapacity: 'NONE' lib.scan.call dynastyTable, 'foo', options, null, hashKeyName: 'bar' hashKeyType: 'S' expect(dynastyTable.parent.dynamo.scanPromise.calledOnce) expect(dynastyTable.parent.dynamo.scanPromise.getCall(0).args[0].TableName).to.equal(dynastyTable.name) expect(dynastyTable.parent.dynamo.scanPromise.getCall(0).args[0].ReturnConsumedCapacity).to.equal('NONE') describe '#queryByHashKey', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { queryPromise: (params, callback) -> Promise.resolve Items: [{ foo: {S: 'bar'}, bar: {S: 'baz'} }] } afterEach () -> sandbox.restore() it 'should translate the response', () -> lib.queryByHashKey .call dynastyTable, 'bar', null, hashKeyName: 'foo' hashKeyType: 'S' rangeKeyName: 'bar' rangeKeyType: 'S' .then (data) -> expect(data).to.deep.equal [ foo: 'bar' bar: 'baz' ] it 'should call query', () -> sandbox.spy(dynastyTable.parent.dynamo, "queryPromise") lib.queryByHashKey.call dynastyTable, 'bar', null, hashKeyName: 'foo' hashKeyType: 'S' rangeKeyName: 'bar' rangeKeyType: 'S' expect(dynastyTable.parent.dynamo.queryPromise.calledOnce) expect(dynastyTable.parent.dynamo.queryPromise.getCall(0).args[0]).to.include.keys('TableName', 'KeyConditions') it 'should send the table name and hash key to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "queryPromise") promise = lib.queryByHashKey.call dynastyTable, 'bar', null, hashKeyName: 'foo' hashKeyType: 'S' rangeKeyName: 'bar' rangeKeyType: 'S' expect(dynastyTable.parent.dynamo.queryPromise.calledOnce) params = dynastyTable.parent.dynamo.queryPromise.getCall(0).args[0] expect(params.TableName).to.equal(dynastyTable.name) expect(params.KeyConditions.foo.ComparisonOperator).to.equal('EQ') expect(params.KeyConditions.foo.AttributeValueList[0].S) .to.equal('bar') describe '#query', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { queryPromise: (params, callback) -> Promise.resolve Items: [{ foo: {S: 'bar'}, bar: {S: 'baz'} }] } afterEach () -> sandbox.restore() it 'should translate the response', () -> lib.query .call dynastyTable, { indexName: chance.name(), keyConditions: [ column: 'foo' value: 'bar' ] }, null, null, .then (data) -> expect(data).to.deep.equal [ foo: 'bar' bar: 'baz' ] it 'should call query', () -> sandbox.spy(dynastyTable.parent.dynamo, "queryPromise") lib.query.call dynastyTable, { indexName: chance.name(), keyConditions: [ column: 'foo' value: 'bar' ] }, null, null expect(dynastyTable.parent.dynamo.queryPromise.calledOnce) expect(dynastyTable.parent.dynamo.queryPromise.getCall(0).args[0]).to.include.keys('TableName', 'IndexName', 'KeyConditions') describe '#putItem', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { putItemPromise: (params, callback) -> Promise.resolve('lol') } afterEach () -> sandbox.restore() it 'should return an object', () -> promise = lib.putItem.call(dynastyTable, foo: 'bar', null, null) expect(promise).to.be.an('object') it 'should return a promise', () -> lib.putItem .call(dynastyTable, foo: 'bar', null, null) .then (data) -> expect(data).to.equal('lol') it 'should call putItem of aws', () -> sandbox.spy(dynastyTable.parent.dynamo, "putItemPromise") lib.putItem.call(dynastyTable, foo: 'bar', null, null) expect(dynastyTable.parent.dynamo.putItemPromise.calledOnce) expect(dynastyTable.parent.dynamo.putItemPromise.getCall(0).args[0]).to.include.keys('Item', 'TableName') it 'should add extra params from options', () -> sandbox.spy(dynastyTable.parent.dynamo, "putItemPromise") options = ReturnValues: 'ALL_NEW' lib.putItem.call(dynastyTable, foo: 'bar', options, null) expect(dynastyTable.parent.dynamo.putItemPromise.calledOnce) expect(dynastyTable.parent.dynamo.putItemPromise.getCall(0).args[0]).to.include.keys('Item', 'TableName', 'ReturnValues') it 'should send the table name to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "putItemPromise") lib.putItem .call(dynastyTable, foo: 'bar', null, null) .then () -> expect(dynastyTable.parent.dynamo.putItemPromise.calledOnce) params = dynastyTable.parent.dynamo.putItemPromise.getCall(0).args[0] expect(params.TableName).to.equal(dynastyTable.name) it 'should send the translated object to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "putItemPromise") promise = lib.putItem.call dynastyTable, foo: 'bar', null, null expect(dynastyTable.parent.dynamo.putItemPromise.calledOnce) params = dynastyTable.parent.dynamo.putItemPromise.getCall(0).args[0] expect(params.Item).to.be.an('object') expect(params.Item.foo).to.be.an('object') expect(params.Item.foo.S).to.equal('bar') describe '#updateItem', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { updateItemPromise: (params, callback) -> Promise.resolve('lol') } afterEach () -> sandbox.restore() it 'should automatically setup ExpressionAttributeNames mapping', () -> sandbox.spy(dynastyTable.parent.dynamo, "updateItemPromise") promise = lib.updateItem.call(dynastyTable, {}, foo: 'bar', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(dynastyTable.parent.dynamo.updateItemPromise.calledOnce) params = dynastyTable.parent.dynamo.updateItemPromise.getCall(0).args[0] expect(params.ExpressionAttributeNames).to.be.eql({"#foo": 'foo'})
209207
chai = require('chai') expect = chai.expect chaiAsPromised = require('chai-as-promised') chai.use(chaiAsPromised) chance = require('chance').Chance() lib = require('../lib/lib')["aws-translators"] sinon = require('sinon') Promise = require('bluebird') describe 'aws-translators', () -> describe '#getKeySchema', () -> it 'should parse out a hash key from an aws response', () -> hashKeyName = chance.word() result = lib.getKeySchema( Table: KeySchema:[ AttributeName: hashKeyName KeyType: 'HASH' ] AttributeDefinitions: [ AttributeName: hashKeyName AttributeType: 'N' ] ) expect(result).to.have.property('hashKeyName') expect(result.hashKeyName).to.equal(hashKeyName) expect(result).to.have.property('hashKeyType') expect(result.hashKeyType).to.equal('N') it 'should parse out a range key from an aws response', () -> hashKeyName = chance.word() rangeKeyName = chance.word() result = lib.getKeySchema( Table: KeySchema:[ { AttributeName: hashKeyName KeyType: 'HASH' }, { AttributeName: rangeKeyName KeyType: 'RANGE' } ] AttributeDefinitions: [ { AttributeName: hashKeyName AttributeType: 'S' }, { AttributeName: rangeKeyName AttributeType: 'B' } ] ) describe '#deleteItem', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { deleteItemPromise: (params, callback) -> Promise.resolve('lol') } afterEach () -> sandbox.restore() it 'should return an object', () -> promise = lib.deleteItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(promise).to.be.an('object') it 'should return a promise', () -> promise = lib.deleteItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) promise.then((d) -> expect(d).to.equal('lol')) it 'should call deleteItem of aws', () -> sandbox.spy(dynastyTable.parent.dynamo, "deleteItemPromise") lib.deleteItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(dynastyTable.parent.dynamo.deleteItemPromise.calledOnce) it 'should call deleteItem of aws with extra params', () -> sandbox.spy(dynastyTable.parent.dynamo, "deleteItemPromise") options = ReturnValues: 'NONE' lib.deleteItem.call(dynastyTable, 'foo', options, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(dynastyTable.parent.dynamo.deleteItemPromise.calledOnce) expect(dynastyTable.parent.dynamo.deleteItemPromise.getCall(0).args[0]).to.include.keys('ReturnValues') it 'should send the table name to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "deleteItemPromise") promise = lib.deleteItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) promise.then () -> expect(dynastyTable.parent.dynamo.deleteItemPromise.calledOnce) params = dynastyTable.parent.dynamo.deleteItemPromise.getCall(0).args[0] expect(params.TableName).to.equal(dynastyTable.name) it 'should send the hash key to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "deleteItemPromise") promise = lib.deleteItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(dynastyTable.parent.dynamo.deleteItemPromise.calledOnce) params = dynastyTable.parent.dynamo.deleteItemPromise.getCall(0).args[0] expect(params.Key).to.include.keys('bar') expect(params.Key.bar).to.include.keys('S') expect(params.Key.bar.S).to.equal('foo') it 'should send the hash and range key to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "deleteItemPromise") promise = lib.deleteItem.call( dynastyTable, hash: 'lol' range: 'rofl', null, null, hashKeyName: 'bar' hashKeyType: 'S' rangeKeyName: 'foo' rangeKeyType: 'S') expect(dynastyTable.parent.dynamo.deleteItemPromise.calledOnce) params = dynastyTable.parent.dynamo.deleteItemPromise.getCall(0).args[0] expect(params.Key).to.include.keys('bar') expect(params.Key.bar).to.include.keys('S') expect(params.Key.bar.S).to.equal('lol') expect(params.Key).to.include.keys('foo') expect(params.Key.foo).to.include.keys('S') expect(params.Key.foo.S).to.equal('rofl') describe '#batchGetItem', () -> dynastyTable = null sandbox = null beforeEach () -> tableName = chance.name() sandbox = sinon.sandbox.create() dynastyTable = name: tableName parent: dynamo: batchGetItemPromise: (params, callback) -> result = {} result.Responses = {} result.Responses[tableName] = [ { foo: S: "bar" }, foo: S: "baz" bazzoo: N: 123 ] Promise.resolve(result); afterEach () -> sandbox.restore() it 'should return a sane response', () -> lib.batchGetItem .call dynastyTable, ['bar', 'baz'], null, hashKeyName: 'foo' hashKeyType: 'S' .then (data) -> expect(data).to.deep.equal([ { foo: 'bar' }, foo: 'baz' bazzoo: 123]) describe '#getItem', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { getItemPromise: (params, callback) -> Promise.resolve(Item: rofl: S: 'lol') } afterEach () -> sandbox.restore() it 'should return an object', () -> promise = lib.getItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(promise).to.be.an('object') it 'should return a promise', () -> lib.getItem .call dynastyTable, 'foo', null, null, hashKeyName: '<KEY>' hashKeyType: 'S' .then (data) -> expect(data).to.deep.equal(rofl: 'lol') it 'should call getItem of aws', () -> sandbox.spy(dynastyTable.parent.dynamo, "getItemPromise") lib.getItem.call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' expect(dynastyTable.parent.dynamo.getItemPromise.calledOnce) expect(dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0].TableName).to.equal(dynastyTable.name) it 'should call getItem of aws with extra params', () -> sandbox.spy(dynastyTable.parent.dynamo, "getItemPromise") options = ProjectionExpression: 'id, name' lib.getItem.call dynastyTable, 'foo', options, null, hashKeyName: 'bar' hashKeyType: 'S' expect(dynastyTable.parent.dynamo.getItemPromise.calledOnce) expect(dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0].TableName).to.equal(dynastyTable.name) expect(dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0].ProjectionExpression).to.equal('id, name') it 'should send the table name to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "getItemPromise") lib.getItem .call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' .then () -> expect(dynastyTable.parent.dynamo.getItemPromise.calledOnce) params = dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0] expect(params.TableName).to.equal(dynastyTable.name) it 'should send the hash key to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "getItemPromise") promise = lib.getItem.call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' expect(dynastyTable.parent.dynamo.getItemPromise.calledOnce) params = dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0] expect(params.Key).to.include.keys('bar') expect(params.Key.bar).to.include.keys('S') expect(params.Key.bar.S).to.equal('foo') it 'should send the hash and range key to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "getItemPromise") promise = lib.getItem.call( dynastyTable, hash: 'lol' range: 'rofl', null, null, hashKeyName: 'bar' hashKeyType: 'S' rangeKeyName: 'foo' rangeKeyType: 'S') expect(dynastyTable.parent.dynamo.getItemPromise.calledOnce) params = dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0] expect(params.Key).to.include.keys('bar') expect(params.Key.bar).to.include.keys('S') expect(params.Key.bar.S).to.equal('lol') expect(params.Key).to.include.keys('foo') expect(params.Key.foo).to.include.keys('S') expect(params.Key.foo.S).to.equal('rofl') describe '#scanPromise', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { scanPromise: (params, callback) -> Promise.resolve(Items: rofl: S: 'lol') } afterEach () -> sandbox.restore() it 'should return an object', () -> promise = lib.scan.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(promise).to.be.an('object') it 'should return a promise', () -> lib.scan .call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' .then (data) -> expect(data).to.deep.equal(rofl: 'lol') it 'should call scan of aws', () -> sandbox.spy(dynastyTable.parent.dynamo, "scanPromise") lib.scan.call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' expect(dynastyTable.parent.dynamo.scanPromise.calledOnce) expect(dynastyTable.parent.dynamo.scanPromise.getCall(0).args[0].TableName).to.equal(dynastyTable.name) it 'should call scan of aws with extra params', () -> sandbox.spy(dynastyTable.parent.dynamo, "scanPromise") options = ReturnConsumedCapacity: 'NONE' lib.scan.call dynastyTable, 'foo', options, null, hashKeyName: 'bar' hashKeyType: 'S' expect(dynastyTable.parent.dynamo.scanPromise.calledOnce) expect(dynastyTable.parent.dynamo.scanPromise.getCall(0).args[0].TableName).to.equal(dynastyTable.name) expect(dynastyTable.parent.dynamo.scanPromise.getCall(0).args[0].ReturnConsumedCapacity).to.equal('NONE') describe '#queryByHashKey', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { queryPromise: (params, callback) -> Promise.resolve Items: [{ foo: {S: 'bar'}, bar: {S: 'baz'} }] } afterEach () -> sandbox.restore() it 'should translate the response', () -> lib.queryByHashKey .call dynastyTable, 'bar', null, hashKeyName: 'foo' hashKeyType: 'S' rangeKeyName: 'bar' rangeKeyType: 'S' .then (data) -> expect(data).to.deep.equal [ foo: 'bar' bar: 'baz' ] it 'should call query', () -> sandbox.spy(dynastyTable.parent.dynamo, "queryPromise") lib.queryByHashKey.call dynastyTable, 'bar', null, hashKeyName: 'foo' hashKeyType: 'S' rangeKeyName: 'bar' rangeKeyType: 'S' expect(dynastyTable.parent.dynamo.queryPromise.calledOnce) expect(dynastyTable.parent.dynamo.queryPromise.getCall(0).args[0]).to.include.keys('TableName', 'KeyConditions') it 'should send the table name and hash key to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "queryPromise") promise = lib.queryByHashKey.call dynastyTable, 'bar', null, hashKeyName: 'foo' hashKeyType: 'S' rangeKeyName: 'bar' rangeKeyType: 'S' expect(dynastyTable.parent.dynamo.queryPromise.calledOnce) params = dynastyTable.parent.dynamo.queryPromise.getCall(0).args[0] expect(params.TableName).to.equal(dynastyTable.name) expect(params.KeyConditions.foo.ComparisonOperator).to.equal('EQ') expect(params.KeyConditions.foo.AttributeValueList[0].S) .to.equal('bar') describe '#query', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { queryPromise: (params, callback) -> Promise.resolve Items: [{ foo: {S: 'bar'}, bar: {S: 'baz'} }] } afterEach () -> sandbox.restore() it 'should translate the response', () -> lib.query .call dynastyTable, { indexName: chance.name(), keyConditions: [ column: 'foo' value: 'bar' ] }, null, null, .then (data) -> expect(data).to.deep.equal [ foo: 'bar' bar: 'baz' ] it 'should call query', () -> sandbox.spy(dynastyTable.parent.dynamo, "queryPromise") lib.query.call dynastyTable, { indexName: chance.name(), keyConditions: [ column: 'foo' value: 'bar' ] }, null, null expect(dynastyTable.parent.dynamo.queryPromise.calledOnce) expect(dynastyTable.parent.dynamo.queryPromise.getCall(0).args[0]).to.include.keys('TableName', 'IndexName', 'KeyConditions') describe '#putItem', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { putItemPromise: (params, callback) -> Promise.resolve('lol') } afterEach () -> sandbox.restore() it 'should return an object', () -> promise = lib.putItem.call(dynastyTable, foo: 'bar', null, null) expect(promise).to.be.an('object') it 'should return a promise', () -> lib.putItem .call(dynastyTable, foo: 'bar', null, null) .then (data) -> expect(data).to.equal('lol') it 'should call putItem of aws', () -> sandbox.spy(dynastyTable.parent.dynamo, "putItemPromise") lib.putItem.call(dynastyTable, foo: 'bar', null, null) expect(dynastyTable.parent.dynamo.putItemPromise.calledOnce) expect(dynastyTable.parent.dynamo.putItemPromise.getCall(0).args[0]).to.include.keys('Item', 'TableName') it 'should add extra params from options', () -> sandbox.spy(dynastyTable.parent.dynamo, "putItemPromise") options = ReturnValues: 'ALL_NEW' lib.putItem.call(dynastyTable, foo: 'bar', options, null) expect(dynastyTable.parent.dynamo.putItemPromise.calledOnce) expect(dynastyTable.parent.dynamo.putItemPromise.getCall(0).args[0]).to.include.keys('Item', 'TableName', 'ReturnValues') it 'should send the table name to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "putItemPromise") lib.putItem .call(dynastyTable, foo: 'bar', null, null) .then () -> expect(dynastyTable.parent.dynamo.putItemPromise.calledOnce) params = dynastyTable.parent.dynamo.putItemPromise.getCall(0).args[0] expect(params.TableName).to.equal(dynastyTable.name) it 'should send the translated object to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "putItemPromise") promise = lib.putItem.call dynastyTable, foo: 'bar', null, null expect(dynastyTable.parent.dynamo.putItemPromise.calledOnce) params = dynastyTable.parent.dynamo.putItemPromise.getCall(0).args[0] expect(params.Item).to.be.an('object') expect(params.Item.foo).to.be.an('object') expect(params.Item.foo.S).to.equal('bar') describe '#updateItem', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { updateItemPromise: (params, callback) -> Promise.resolve('lol') } afterEach () -> sandbox.restore() it 'should automatically setup ExpressionAttributeNames mapping', () -> sandbox.spy(dynastyTable.parent.dynamo, "updateItemPromise") promise = lib.updateItem.call(dynastyTable, {}, foo: 'bar', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(dynastyTable.parent.dynamo.updateItemPromise.calledOnce) params = dynastyTable.parent.dynamo.updateItemPromise.getCall(0).args[0] expect(params.ExpressionAttributeNames).to.be.eql({"#foo": 'foo'})
true
chai = require('chai') expect = chai.expect chaiAsPromised = require('chai-as-promised') chai.use(chaiAsPromised) chance = require('chance').Chance() lib = require('../lib/lib')["aws-translators"] sinon = require('sinon') Promise = require('bluebird') describe 'aws-translators', () -> describe '#getKeySchema', () -> it 'should parse out a hash key from an aws response', () -> hashKeyName = chance.word() result = lib.getKeySchema( Table: KeySchema:[ AttributeName: hashKeyName KeyType: 'HASH' ] AttributeDefinitions: [ AttributeName: hashKeyName AttributeType: 'N' ] ) expect(result).to.have.property('hashKeyName') expect(result.hashKeyName).to.equal(hashKeyName) expect(result).to.have.property('hashKeyType') expect(result.hashKeyType).to.equal('N') it 'should parse out a range key from an aws response', () -> hashKeyName = chance.word() rangeKeyName = chance.word() result = lib.getKeySchema( Table: KeySchema:[ { AttributeName: hashKeyName KeyType: 'HASH' }, { AttributeName: rangeKeyName KeyType: 'RANGE' } ] AttributeDefinitions: [ { AttributeName: hashKeyName AttributeType: 'S' }, { AttributeName: rangeKeyName AttributeType: 'B' } ] ) describe '#deleteItem', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { deleteItemPromise: (params, callback) -> Promise.resolve('lol') } afterEach () -> sandbox.restore() it 'should return an object', () -> promise = lib.deleteItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(promise).to.be.an('object') it 'should return a promise', () -> promise = lib.deleteItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) promise.then((d) -> expect(d).to.equal('lol')) it 'should call deleteItem of aws', () -> sandbox.spy(dynastyTable.parent.dynamo, "deleteItemPromise") lib.deleteItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(dynastyTable.parent.dynamo.deleteItemPromise.calledOnce) it 'should call deleteItem of aws with extra params', () -> sandbox.spy(dynastyTable.parent.dynamo, "deleteItemPromise") options = ReturnValues: 'NONE' lib.deleteItem.call(dynastyTable, 'foo', options, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(dynastyTable.parent.dynamo.deleteItemPromise.calledOnce) expect(dynastyTable.parent.dynamo.deleteItemPromise.getCall(0).args[0]).to.include.keys('ReturnValues') it 'should send the table name to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "deleteItemPromise") promise = lib.deleteItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) promise.then () -> expect(dynastyTable.parent.dynamo.deleteItemPromise.calledOnce) params = dynastyTable.parent.dynamo.deleteItemPromise.getCall(0).args[0] expect(params.TableName).to.equal(dynastyTable.name) it 'should send the hash key to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "deleteItemPromise") promise = lib.deleteItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(dynastyTable.parent.dynamo.deleteItemPromise.calledOnce) params = dynastyTable.parent.dynamo.deleteItemPromise.getCall(0).args[0] expect(params.Key).to.include.keys('bar') expect(params.Key.bar).to.include.keys('S') expect(params.Key.bar.S).to.equal('foo') it 'should send the hash and range key to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "deleteItemPromise") promise = lib.deleteItem.call( dynastyTable, hash: 'lol' range: 'rofl', null, null, hashKeyName: 'bar' hashKeyType: 'S' rangeKeyName: 'foo' rangeKeyType: 'S') expect(dynastyTable.parent.dynamo.deleteItemPromise.calledOnce) params = dynastyTable.parent.dynamo.deleteItemPromise.getCall(0).args[0] expect(params.Key).to.include.keys('bar') expect(params.Key.bar).to.include.keys('S') expect(params.Key.bar.S).to.equal('lol') expect(params.Key).to.include.keys('foo') expect(params.Key.foo).to.include.keys('S') expect(params.Key.foo.S).to.equal('rofl') describe '#batchGetItem', () -> dynastyTable = null sandbox = null beforeEach () -> tableName = chance.name() sandbox = sinon.sandbox.create() dynastyTable = name: tableName parent: dynamo: batchGetItemPromise: (params, callback) -> result = {} result.Responses = {} result.Responses[tableName] = [ { foo: S: "bar" }, foo: S: "baz" bazzoo: N: 123 ] Promise.resolve(result); afterEach () -> sandbox.restore() it 'should return a sane response', () -> lib.batchGetItem .call dynastyTable, ['bar', 'baz'], null, hashKeyName: 'foo' hashKeyType: 'S' .then (data) -> expect(data).to.deep.equal([ { foo: 'bar' }, foo: 'baz' bazzoo: 123]) describe '#getItem', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { getItemPromise: (params, callback) -> Promise.resolve(Item: rofl: S: 'lol') } afterEach () -> sandbox.restore() it 'should return an object', () -> promise = lib.getItem.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(promise).to.be.an('object') it 'should return a promise', () -> lib.getItem .call dynastyTable, 'foo', null, null, hashKeyName: 'PI:KEY:<KEY>END_PI' hashKeyType: 'S' .then (data) -> expect(data).to.deep.equal(rofl: 'lol') it 'should call getItem of aws', () -> sandbox.spy(dynastyTable.parent.dynamo, "getItemPromise") lib.getItem.call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' expect(dynastyTable.parent.dynamo.getItemPromise.calledOnce) expect(dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0].TableName).to.equal(dynastyTable.name) it 'should call getItem of aws with extra params', () -> sandbox.spy(dynastyTable.parent.dynamo, "getItemPromise") options = ProjectionExpression: 'id, name' lib.getItem.call dynastyTable, 'foo', options, null, hashKeyName: 'bar' hashKeyType: 'S' expect(dynastyTable.parent.dynamo.getItemPromise.calledOnce) expect(dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0].TableName).to.equal(dynastyTable.name) expect(dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0].ProjectionExpression).to.equal('id, name') it 'should send the table name to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "getItemPromise") lib.getItem .call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' .then () -> expect(dynastyTable.parent.dynamo.getItemPromise.calledOnce) params = dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0] expect(params.TableName).to.equal(dynastyTable.name) it 'should send the hash key to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "getItemPromise") promise = lib.getItem.call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' expect(dynastyTable.parent.dynamo.getItemPromise.calledOnce) params = dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0] expect(params.Key).to.include.keys('bar') expect(params.Key.bar).to.include.keys('S') expect(params.Key.bar.S).to.equal('foo') it 'should send the hash and range key to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "getItemPromise") promise = lib.getItem.call( dynastyTable, hash: 'lol' range: 'rofl', null, null, hashKeyName: 'bar' hashKeyType: 'S' rangeKeyName: 'foo' rangeKeyType: 'S') expect(dynastyTable.parent.dynamo.getItemPromise.calledOnce) params = dynastyTable.parent.dynamo.getItemPromise.getCall(0).args[0] expect(params.Key).to.include.keys('bar') expect(params.Key.bar).to.include.keys('S') expect(params.Key.bar.S).to.equal('lol') expect(params.Key).to.include.keys('foo') expect(params.Key.foo).to.include.keys('S') expect(params.Key.foo.S).to.equal('rofl') describe '#scanPromise', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { scanPromise: (params, callback) -> Promise.resolve(Items: rofl: S: 'lol') } afterEach () -> sandbox.restore() it 'should return an object', () -> promise = lib.scan.call(dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(promise).to.be.an('object') it 'should return a promise', () -> lib.scan .call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' .then (data) -> expect(data).to.deep.equal(rofl: 'lol') it 'should call scan of aws', () -> sandbox.spy(dynastyTable.parent.dynamo, "scanPromise") lib.scan.call dynastyTable, 'foo', null, null, hashKeyName: 'bar' hashKeyType: 'S' expect(dynastyTable.parent.dynamo.scanPromise.calledOnce) expect(dynastyTable.parent.dynamo.scanPromise.getCall(0).args[0].TableName).to.equal(dynastyTable.name) it 'should call scan of aws with extra params', () -> sandbox.spy(dynastyTable.parent.dynamo, "scanPromise") options = ReturnConsumedCapacity: 'NONE' lib.scan.call dynastyTable, 'foo', options, null, hashKeyName: 'bar' hashKeyType: 'S' expect(dynastyTable.parent.dynamo.scanPromise.calledOnce) expect(dynastyTable.parent.dynamo.scanPromise.getCall(0).args[0].TableName).to.equal(dynastyTable.name) expect(dynastyTable.parent.dynamo.scanPromise.getCall(0).args[0].ReturnConsumedCapacity).to.equal('NONE') describe '#queryByHashKey', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { queryPromise: (params, callback) -> Promise.resolve Items: [{ foo: {S: 'bar'}, bar: {S: 'baz'} }] } afterEach () -> sandbox.restore() it 'should translate the response', () -> lib.queryByHashKey .call dynastyTable, 'bar', null, hashKeyName: 'foo' hashKeyType: 'S' rangeKeyName: 'bar' rangeKeyType: 'S' .then (data) -> expect(data).to.deep.equal [ foo: 'bar' bar: 'baz' ] it 'should call query', () -> sandbox.spy(dynastyTable.parent.dynamo, "queryPromise") lib.queryByHashKey.call dynastyTable, 'bar', null, hashKeyName: 'foo' hashKeyType: 'S' rangeKeyName: 'bar' rangeKeyType: 'S' expect(dynastyTable.parent.dynamo.queryPromise.calledOnce) expect(dynastyTable.parent.dynamo.queryPromise.getCall(0).args[0]).to.include.keys('TableName', 'KeyConditions') it 'should send the table name and hash key to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "queryPromise") promise = lib.queryByHashKey.call dynastyTable, 'bar', null, hashKeyName: 'foo' hashKeyType: 'S' rangeKeyName: 'bar' rangeKeyType: 'S' expect(dynastyTable.parent.dynamo.queryPromise.calledOnce) params = dynastyTable.parent.dynamo.queryPromise.getCall(0).args[0] expect(params.TableName).to.equal(dynastyTable.name) expect(params.KeyConditions.foo.ComparisonOperator).to.equal('EQ') expect(params.KeyConditions.foo.AttributeValueList[0].S) .to.equal('bar') describe '#query', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { queryPromise: (params, callback) -> Promise.resolve Items: [{ foo: {S: 'bar'}, bar: {S: 'baz'} }] } afterEach () -> sandbox.restore() it 'should translate the response', () -> lib.query .call dynastyTable, { indexName: chance.name(), keyConditions: [ column: 'foo' value: 'bar' ] }, null, null, .then (data) -> expect(data).to.deep.equal [ foo: 'bar' bar: 'baz' ] it 'should call query', () -> sandbox.spy(dynastyTable.parent.dynamo, "queryPromise") lib.query.call dynastyTable, { indexName: chance.name(), keyConditions: [ column: 'foo' value: 'bar' ] }, null, null expect(dynastyTable.parent.dynamo.queryPromise.calledOnce) expect(dynastyTable.parent.dynamo.queryPromise.getCall(0).args[0]).to.include.keys('TableName', 'IndexName', 'KeyConditions') describe '#putItem', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { putItemPromise: (params, callback) -> Promise.resolve('lol') } afterEach () -> sandbox.restore() it 'should return an object', () -> promise = lib.putItem.call(dynastyTable, foo: 'bar', null, null) expect(promise).to.be.an('object') it 'should return a promise', () -> lib.putItem .call(dynastyTable, foo: 'bar', null, null) .then (data) -> expect(data).to.equal('lol') it 'should call putItem of aws', () -> sandbox.spy(dynastyTable.parent.dynamo, "putItemPromise") lib.putItem.call(dynastyTable, foo: 'bar', null, null) expect(dynastyTable.parent.dynamo.putItemPromise.calledOnce) expect(dynastyTable.parent.dynamo.putItemPromise.getCall(0).args[0]).to.include.keys('Item', 'TableName') it 'should add extra params from options', () -> sandbox.spy(dynastyTable.parent.dynamo, "putItemPromise") options = ReturnValues: 'ALL_NEW' lib.putItem.call(dynastyTable, foo: 'bar', options, null) expect(dynastyTable.parent.dynamo.putItemPromise.calledOnce) expect(dynastyTable.parent.dynamo.putItemPromise.getCall(0).args[0]).to.include.keys('Item', 'TableName', 'ReturnValues') it 'should send the table name to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "putItemPromise") lib.putItem .call(dynastyTable, foo: 'bar', null, null) .then () -> expect(dynastyTable.parent.dynamo.putItemPromise.calledOnce) params = dynastyTable.parent.dynamo.putItemPromise.getCall(0).args[0] expect(params.TableName).to.equal(dynastyTable.name) it 'should send the translated object to AWS', () -> sandbox.spy(dynastyTable.parent.dynamo, "putItemPromise") promise = lib.putItem.call dynastyTable, foo: 'bar', null, null expect(dynastyTable.parent.dynamo.putItemPromise.calledOnce) params = dynastyTable.parent.dynamo.putItemPromise.getCall(0).args[0] expect(params.Item).to.be.an('object') expect(params.Item.foo).to.be.an('object') expect(params.Item.foo.S).to.equal('bar') describe '#updateItem', () -> dynastyTable = null sandbox = null beforeEach () -> sandbox = sinon.sandbox.create() dynastyTable = name: chance.name() parent: dynamo: { updateItemPromise: (params, callback) -> Promise.resolve('lol') } afterEach () -> sandbox.restore() it 'should automatically setup ExpressionAttributeNames mapping', () -> sandbox.spy(dynastyTable.parent.dynamo, "updateItemPromise") promise = lib.updateItem.call(dynastyTable, {}, foo: 'bar', null, null, hashKeyName: 'bar' hashKeyType: 'S' ) expect(dynastyTable.parent.dynamo.updateItemPromise.calledOnce) params = dynastyTable.parent.dynamo.updateItemPromise.getCall(0).args[0] expect(params.ExpressionAttributeNames).to.be.eql({"#foo": 'foo'})
[ { "context": "# Copyright 2012 Joshua Carver \n# \n# Licensed under the Apache License, Versio", "end": 30, "score": 0.9998742938041687, "start": 17, "tag": "NAME", "value": "Joshua Carver" } ]
src/coffeescript/charts/bezier.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. # @import point.coffee class Bezier @create_path: (points, smoothing = 0.5) -> path = "M#{points[0].x}, #{points[0].y}" for point, i in points continue if i == 0 [b1, b2] = Bezier.get_control_points(points, i-1, smoothing) path += "C#{b1.x},#{b1.y} #{b2.x},#{b2.y} #{points[i].x},#{points[i].y}" path # hermite interpolation with bezier curve # smoothing: 0 to 1 (0 not smooth, 1 ultra smooth) @get_control_points: (points, i, smoothing, divisor = 3) -> [p0, p2] = @get_prev_and_next_points(points, i) # i-1 & i+1 [p1, p3] = @get_prev_and_next_points(points, i+1) # i & i+2 # tan1 entering the point, tan2 leaving the point [tan1_x, tan1_y] = @get_tangent(p0, p2) [tan2_x, tan2_y] = @get_tangent(p1, p3) b1_x = p1.x + (tan1_x * smoothing)/divisor b1_y = p1.y + (tan1_y * smoothing)/divisor b2_x = p2.x - (tan2_x * smoothing)/divisor b2_y = p2.y - (tan2_y * smoothing)/divisor b1 = new Point(b1_x, b1_y) b2 = new Point(b2_x, b2_y) return [b1, b2] @get_prev_and_next_points = (points, i) -> prev = i-1 next = i+1 prev = 0 if prev < 0 next = points.length-1 if next >= points.length return [points[prev], points[next]] @get_tangent = (p0, p1) -> tan_x = p1.x - p0.x tan_y = p1.y - p0.y return [tan_x, tan_y] exports.Bezier = Bezier
188073
# 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. # @import point.coffee class Bezier @create_path: (points, smoothing = 0.5) -> path = "M#{points[0].x}, #{points[0].y}" for point, i in points continue if i == 0 [b1, b2] = Bezier.get_control_points(points, i-1, smoothing) path += "C#{b1.x},#{b1.y} #{b2.x},#{b2.y} #{points[i].x},#{points[i].y}" path # hermite interpolation with bezier curve # smoothing: 0 to 1 (0 not smooth, 1 ultra smooth) @get_control_points: (points, i, smoothing, divisor = 3) -> [p0, p2] = @get_prev_and_next_points(points, i) # i-1 & i+1 [p1, p3] = @get_prev_and_next_points(points, i+1) # i & i+2 # tan1 entering the point, tan2 leaving the point [tan1_x, tan1_y] = @get_tangent(p0, p2) [tan2_x, tan2_y] = @get_tangent(p1, p3) b1_x = p1.x + (tan1_x * smoothing)/divisor b1_y = p1.y + (tan1_y * smoothing)/divisor b2_x = p2.x - (tan2_x * smoothing)/divisor b2_y = p2.y - (tan2_y * smoothing)/divisor b1 = new Point(b1_x, b1_y) b2 = new Point(b2_x, b2_y) return [b1, b2] @get_prev_and_next_points = (points, i) -> prev = i-1 next = i+1 prev = 0 if prev < 0 next = points.length-1 if next >= points.length return [points[prev], points[next]] @get_tangent = (p0, p1) -> tan_x = p1.x - p0.x tan_y = p1.y - p0.y return [tan_x, tan_y] exports.Bezier = Bezier
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. # @import point.coffee class Bezier @create_path: (points, smoothing = 0.5) -> path = "M#{points[0].x}, #{points[0].y}" for point, i in points continue if i == 0 [b1, b2] = Bezier.get_control_points(points, i-1, smoothing) path += "C#{b1.x},#{b1.y} #{b2.x},#{b2.y} #{points[i].x},#{points[i].y}" path # hermite interpolation with bezier curve # smoothing: 0 to 1 (0 not smooth, 1 ultra smooth) @get_control_points: (points, i, smoothing, divisor = 3) -> [p0, p2] = @get_prev_and_next_points(points, i) # i-1 & i+1 [p1, p3] = @get_prev_and_next_points(points, i+1) # i & i+2 # tan1 entering the point, tan2 leaving the point [tan1_x, tan1_y] = @get_tangent(p0, p2) [tan2_x, tan2_y] = @get_tangent(p1, p3) b1_x = p1.x + (tan1_x * smoothing)/divisor b1_y = p1.y + (tan1_y * smoothing)/divisor b2_x = p2.x - (tan2_x * smoothing)/divisor b2_y = p2.y - (tan2_y * smoothing)/divisor b1 = new Point(b1_x, b1_y) b2 = new Point(b2_x, b2_y) return [b1, b2] @get_prev_and_next_points = (points, i) -> prev = i-1 next = i+1 prev = 0 if prev < 0 next = points.length-1 if next >= points.length return [points[prev], points[next]] @get_tangent = (p0, p1) -> tan_x = p1.x - p0.x tan_y = p1.y - p0.y return [tan_x, tan_y] exports.Bezier = Bezier
[ { "context": "p root'\n\nhost.promptPassword()\n\nhost.setPassword('hello')\n", "end": 360, "score": 0.9980704188346863, "start": 355, "tag": "PASSWORD", "value": "hello" } ]
manual-test/sudo.coffee
dvidelabs/poly.shell
1
host = require('..').shell(host:"example.com", log:true) host.run 'ls /var/log', -> host.log = true host.sudo 'tail /var/log/auth.log', -> host.sudo 'head /var/log/auth.log' # test concurrent password acquisition host.sudo 'ls ~' # test sudo detector host.run 'sudo tail /var/log/auth.log | grep root' host.promptPassword() host.setPassword('hello')
30090
host = require('..').shell(host:"example.com", log:true) host.run 'ls /var/log', -> host.log = true host.sudo 'tail /var/log/auth.log', -> host.sudo 'head /var/log/auth.log' # test concurrent password acquisition host.sudo 'ls ~' # test sudo detector host.run 'sudo tail /var/log/auth.log | grep root' host.promptPassword() host.setPassword('<PASSWORD>')
true
host = require('..').shell(host:"example.com", log:true) host.run 'ls /var/log', -> host.log = true host.sudo 'tail /var/log/auth.log', -> host.sudo 'head /var/log/auth.log' # test concurrent password acquisition host.sudo 'ls ~' # test sudo detector host.run 'sudo tail /var/log/auth.log | grep root' host.promptPassword() host.setPassword('PI:PASSWORD:<PASSWORD>END_PI')
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999135136604309, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/react/contest-voting/entry-list.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 { BaseEntryList } from './base-entry-list' import { Entry } from './entry' import { VoteSummary } from './vote-summary' import * as React from 'react' import { div,a,i,span } from 'react-dom-factories' el = React.createElement export class EntryList extends BaseEntryList render: -> if @state.contest.best_of && @state.contest.entries.length == 0 return div className: 'contest__voting-notice', if currentUser.id? osu.trans('contest.voting.best_of.none_played') else osu.trans('contest.voting.login_required') return null unless @state.contest.entries.length > 0 if @state.contest.show_votes totalVotes = _.sumBy @state.contest.entries, (i) -> i.results.votes entries = @state.contest.entries.map (entry, index) => el Entry, key: entry.id, rank: index + 1, entry: entry, waitingForResponse: @state.waitingForResponse, options: @state.options, contest: @state.contest, selected: @state.selected, winnerVotes: if @state.contest.show_votes then _.maxBy(@state.contest.entries, (i) -> i.results.votes).results.votes totalVotes: if @state.contest.show_votes then totalVotes div className: 'contest-voting-list__table', div className: 'contest-voting-list__header', if @state.options.showPreview div className: 'contest-voting-list__icon' if @state.options.showLink div className: 'contest-voting-list__icon' div className: 'contest-voting-list__header-wrapper', div className: 'contest-voting-list__header-title', osu.trans('contest.entry._') div className: 'contest-voting-list__header-votesummary', div className: 'contest__vote-summary-text', osu.trans('contest.vote.list') el VoteSummary, voteCount: @state.selected.length, maxVotes: @state.contest.max_votes div {}, entries
102224
# 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 { BaseEntryList } from './base-entry-list' import { Entry } from './entry' import { VoteSummary } from './vote-summary' import * as React from 'react' import { div,a,i,span } from 'react-dom-factories' el = React.createElement export class EntryList extends BaseEntryList render: -> if @state.contest.best_of && @state.contest.entries.length == 0 return div className: 'contest__voting-notice', if currentUser.id? osu.trans('contest.voting.best_of.none_played') else osu.trans('contest.voting.login_required') return null unless @state.contest.entries.length > 0 if @state.contest.show_votes totalVotes = _.sumBy @state.contest.entries, (i) -> i.results.votes entries = @state.contest.entries.map (entry, index) => el Entry, key: entry.id, rank: index + 1, entry: entry, waitingForResponse: @state.waitingForResponse, options: @state.options, contest: @state.contest, selected: @state.selected, winnerVotes: if @state.contest.show_votes then _.maxBy(@state.contest.entries, (i) -> i.results.votes).results.votes totalVotes: if @state.contest.show_votes then totalVotes div className: 'contest-voting-list__table', div className: 'contest-voting-list__header', if @state.options.showPreview div className: 'contest-voting-list__icon' if @state.options.showLink div className: 'contest-voting-list__icon' div className: 'contest-voting-list__header-wrapper', div className: 'contest-voting-list__header-title', osu.trans('contest.entry._') div className: 'contest-voting-list__header-votesummary', div className: 'contest__vote-summary-text', osu.trans('contest.vote.list') el VoteSummary, voteCount: @state.selected.length, maxVotes: @state.contest.max_votes div {}, entries
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 { BaseEntryList } from './base-entry-list' import { Entry } from './entry' import { VoteSummary } from './vote-summary' import * as React from 'react' import { div,a,i,span } from 'react-dom-factories' el = React.createElement export class EntryList extends BaseEntryList render: -> if @state.contest.best_of && @state.contest.entries.length == 0 return div className: 'contest__voting-notice', if currentUser.id? osu.trans('contest.voting.best_of.none_played') else osu.trans('contest.voting.login_required') return null unless @state.contest.entries.length > 0 if @state.contest.show_votes totalVotes = _.sumBy @state.contest.entries, (i) -> i.results.votes entries = @state.contest.entries.map (entry, index) => el Entry, key: entry.id, rank: index + 1, entry: entry, waitingForResponse: @state.waitingForResponse, options: @state.options, contest: @state.contest, selected: @state.selected, winnerVotes: if @state.contest.show_votes then _.maxBy(@state.contest.entries, (i) -> i.results.votes).results.votes totalVotes: if @state.contest.show_votes then totalVotes div className: 'contest-voting-list__table', div className: 'contest-voting-list__header', if @state.options.showPreview div className: 'contest-voting-list__icon' if @state.options.showLink div className: 'contest-voting-list__icon' div className: 'contest-voting-list__header-wrapper', div className: 'contest-voting-list__header-title', osu.trans('contest.entry._') div className: 'contest-voting-list__header-votesummary', div className: 'contest__vote-summary-text', osu.trans('contest.vote.list') el VoteSummary, voteCount: @state.selected.length, maxVotes: @state.contest.max_votes div {}, entries
[ { "context": "L_PASSWORD\n\n imap = new ImapBot\n username: @username\n password: @password\n host: process", "end": 431, "score": 0.992734432220459, "start": 422, "tag": "USERNAME", "value": "@username" }, { "context": " ImapBot\n username: @username\n ...
src/adapters/third-party/email.coffee
poshboytl/hubot
1
Robot = require('hubot').robot() Adapter = require('hubot').adapter() ImapConnection = require('imap').ImapConnection EventEmitter = require('events').EventEmitter util = require('util') CRLF = "\r\n" class Email extends Adapter run: -> self = @ @username = process.env.HUBOT_EMAIL_USERNAME @password = process.env.HUBOT_EMAIL_PASSWORD imap = new ImapBot username: @username password: @password host: process.env.HUBOT_IMAP_HOST port: process.env.HUBOT_IMAP_PORT secure: process.env.HUBOT_IMAP_SECURE && true mailbox: process.env.HUBOT_MAILBOX || 'Inbox' imap.listen (email) -> console.log email imap.connect() exports.use = (robot) -> new Email robot class ImapBot extends EventEmitter constructor: (options) -> @username = options.username @password = options.password @host = options.host @port = options.port @secure = options.secure @mailbox = options.mailbox @imap = new ImapConnection username: @username password: @password host: @host port: (Number) @port secure: @secure connect: (callback) -> @imap.connect (err) => throw err if err? @open() open: -> @imap.openBox @mailbox, (err) => throw err if err? @imap.on 'error', (err) -> throw err @imap.on 'mail', @recieve recieve: => @imap.search [ 'UNSEEN' ], (_, ids) => @fetch ids... fetch: (ids...) -> @fetchHeaders ids, (msg) => @fetchBody msg, (email) -> console.log(email) fetchHeaders: (ids, callback) -> fetch = @imap.fetch ids, markSeen: true fetch.on 'message', (msg) -> msg.on 'end', -> callback(msg) fetchBody: (headerMsg, callback) -> fetch = @imap.fetch headerMsg.id, request: headers: false body: true fetch.on 'message', (bodyMsg) -> message = new Message headerMsg, bodyMsg bodyMsg.on 'data', (chunk) -> message.recieveData(chunk) bodyMsg.on 'end', -> message.endData -> console.log(util.inspect(message)) listen: (callback) -> @imap.on 'Email', (mail...) -> console.log(mail) class Message constructor: (headerMsg, bodyMsg) -> @headerMsg = headerMsg @bodyMsg = bodyMsg @rawBody = '' @buffer = '' @state = 'INIT' recieveData: (buff) -> @buffer += buff.toString('ascii') endData: (callback) -> @rawBody = @buffer.toString() @parse(callback) parse: (callback) -> while @buffer switch @state when 'INIT' then @readBoundry() when 'HEADERS' then @readHeaders() when 'BODY' then @readBody() when 'FIN' then @readFinish(callback) readBoundry: -> throw "Boundary Missing" if @buffer.indexOf(CRLF) == -1 lines = @buffer.split(CRLF) @boundary = lines.shift() @buffer = lines.join(CRLF) @state = 'HEADERS' readHeaders: -> throw "Header(s) Missing" if @buffer.indexOf(CRLF + CRLF) == -1 # throw away the body headers for now [_, parts...] = @buffer.split(CRLF + CRLF) @buffer = parts.join(CRLF + CRLF) @state = 'BODY' readBody: -> throw "Plain Body Missing" if @buffer.indexOf(@boundary) == -1 @body = @buffer.split(@boundary, 1)[0] @state = 'FIN' readFinish: (callback) -> @buffer = '' callback()
74745
Robot = require('hubot').robot() Adapter = require('hubot').adapter() ImapConnection = require('imap').ImapConnection EventEmitter = require('events').EventEmitter util = require('util') CRLF = "\r\n" class Email extends Adapter run: -> self = @ @username = process.env.HUBOT_EMAIL_USERNAME @password = process.env.HUBOT_EMAIL_PASSWORD imap = new ImapBot username: @username password: <PASSWORD> host: process.env.HUBOT_IMAP_HOST port: process.env.HUBOT_IMAP_PORT secure: process.env.HUBOT_IMAP_SECURE && true mailbox: process.env.HUBOT_MAILBOX || 'Inbox' imap.listen (email) -> console.log email imap.connect() exports.use = (robot) -> new Email robot class ImapBot extends EventEmitter constructor: (options) -> @username = options.username @password = <PASSWORD> @host = options.host @port = options.port @secure = options.secure @mailbox = options.mailbox @imap = new ImapConnection username: @username password: <PASSWORD> host: @host port: (Number) @port secure: @secure connect: (callback) -> @imap.connect (err) => throw err if err? @open() open: -> @imap.openBox @mailbox, (err) => throw err if err? @imap.on 'error', (err) -> throw err @imap.on 'mail', @recieve recieve: => @imap.search [ 'UNSEEN' ], (_, ids) => @fetch ids... fetch: (ids...) -> @fetchHeaders ids, (msg) => @fetchBody msg, (email) -> console.log(email) fetchHeaders: (ids, callback) -> fetch = @imap.fetch ids, markSeen: true fetch.on 'message', (msg) -> msg.on 'end', -> callback(msg) fetchBody: (headerMsg, callback) -> fetch = @imap.fetch headerMsg.id, request: headers: false body: true fetch.on 'message', (bodyMsg) -> message = new Message headerMsg, bodyMsg bodyMsg.on 'data', (chunk) -> message.recieveData(chunk) bodyMsg.on 'end', -> message.endData -> console.log(util.inspect(message)) listen: (callback) -> @imap.on 'Email', (mail...) -> console.log(mail) class Message constructor: (headerMsg, bodyMsg) -> @headerMsg = headerMsg @bodyMsg = bodyMsg @rawBody = '' @buffer = '' @state = 'INIT' recieveData: (buff) -> @buffer += buff.toString('ascii') endData: (callback) -> @rawBody = @buffer.toString() @parse(callback) parse: (callback) -> while @buffer switch @state when 'INIT' then @readBoundry() when 'HEADERS' then @readHeaders() when 'BODY' then @readBody() when 'FIN' then @readFinish(callback) readBoundry: -> throw "Boundary Missing" if @buffer.indexOf(CRLF) == -1 lines = @buffer.split(CRLF) @boundary = lines.shift() @buffer = lines.join(CRLF) @state = 'HEADERS' readHeaders: -> throw "Header(s) Missing" if @buffer.indexOf(CRLF + CRLF) == -1 # throw away the body headers for now [_, parts...] = @buffer.split(CRLF + CRLF) @buffer = parts.join(CRLF + CRLF) @state = 'BODY' readBody: -> throw "Plain Body Missing" if @buffer.indexOf(@boundary) == -1 @body = @buffer.split(@boundary, 1)[0] @state = 'FIN' readFinish: (callback) -> @buffer = '' callback()
true
Robot = require('hubot').robot() Adapter = require('hubot').adapter() ImapConnection = require('imap').ImapConnection EventEmitter = require('events').EventEmitter util = require('util') CRLF = "\r\n" class Email extends Adapter run: -> self = @ @username = process.env.HUBOT_EMAIL_USERNAME @password = process.env.HUBOT_EMAIL_PASSWORD imap = new ImapBot username: @username password: PI:PASSWORD:<PASSWORD>END_PI host: process.env.HUBOT_IMAP_HOST port: process.env.HUBOT_IMAP_PORT secure: process.env.HUBOT_IMAP_SECURE && true mailbox: process.env.HUBOT_MAILBOX || 'Inbox' imap.listen (email) -> console.log email imap.connect() exports.use = (robot) -> new Email robot class ImapBot extends EventEmitter constructor: (options) -> @username = options.username @password = PI:PASSWORD:<PASSWORD>END_PI @host = options.host @port = options.port @secure = options.secure @mailbox = options.mailbox @imap = new ImapConnection username: @username password: PI:PASSWORD:<PASSWORD>END_PI host: @host port: (Number) @port secure: @secure connect: (callback) -> @imap.connect (err) => throw err if err? @open() open: -> @imap.openBox @mailbox, (err) => throw err if err? @imap.on 'error', (err) -> throw err @imap.on 'mail', @recieve recieve: => @imap.search [ 'UNSEEN' ], (_, ids) => @fetch ids... fetch: (ids...) -> @fetchHeaders ids, (msg) => @fetchBody msg, (email) -> console.log(email) fetchHeaders: (ids, callback) -> fetch = @imap.fetch ids, markSeen: true fetch.on 'message', (msg) -> msg.on 'end', -> callback(msg) fetchBody: (headerMsg, callback) -> fetch = @imap.fetch headerMsg.id, request: headers: false body: true fetch.on 'message', (bodyMsg) -> message = new Message headerMsg, bodyMsg bodyMsg.on 'data', (chunk) -> message.recieveData(chunk) bodyMsg.on 'end', -> message.endData -> console.log(util.inspect(message)) listen: (callback) -> @imap.on 'Email', (mail...) -> console.log(mail) class Message constructor: (headerMsg, bodyMsg) -> @headerMsg = headerMsg @bodyMsg = bodyMsg @rawBody = '' @buffer = '' @state = 'INIT' recieveData: (buff) -> @buffer += buff.toString('ascii') endData: (callback) -> @rawBody = @buffer.toString() @parse(callback) parse: (callback) -> while @buffer switch @state when 'INIT' then @readBoundry() when 'HEADERS' then @readHeaders() when 'BODY' then @readBody() when 'FIN' then @readFinish(callback) readBoundry: -> throw "Boundary Missing" if @buffer.indexOf(CRLF) == -1 lines = @buffer.split(CRLF) @boundary = lines.shift() @buffer = lines.join(CRLF) @state = 'HEADERS' readHeaders: -> throw "Header(s) Missing" if @buffer.indexOf(CRLF + CRLF) == -1 # throw away the body headers for now [_, parts...] = @buffer.split(CRLF + CRLF) @buffer = parts.join(CRLF + CRLF) @state = 'BODY' readBody: -> throw "Plain Body Missing" if @buffer.indexOf(@boundary) == -1 @body = @buffer.split(@boundary, 1)[0] @state = 'FIN' readFinish: (callback) -> @buffer = '' callback()
[ { "context": "ts.VideoSphere extends Entity\n\n\tentity :\n\t\tname: \"VideoSphere\"\n\t\ttype: \"a-videosphere\"\n\n\t# --------------------", "end": 120, "score": 0.8951374292373657, "start": 109, "tag": "NAME", "value": "VideoSphere" } ]
src/VideoSphere.coffee
etiennepinchon/hologram
89
{entityAttribute, Entity} = require "./Entity" class exports.VideoSphere extends Entity entity : name: "VideoSphere" type: "a-videosphere" # ---------------------------------------------------------------------------- # PROPERTIES @define "radius", entityAttribute("radius", "radius", 5000) @define "segmentsWidth", entityAttribute("segmentsWidth", "segments-width", 64) @define "segmentsHeight", entityAttribute("segmentsHeight", "segments-height", 64) @define "crossOrigin", entityAttribute("crossOrigin", "crossOrigin", "anonymous") @define "autoplay", entityAttribute("autoplay", "autoplay", no) @define "loop", entityAttribute("loop", "loop", no) @define "volume", entityAttribute("volume", "volume", 1)
48775
{entityAttribute, Entity} = require "./Entity" class exports.VideoSphere extends Entity entity : name: "<NAME>" type: "a-videosphere" # ---------------------------------------------------------------------------- # PROPERTIES @define "radius", entityAttribute("radius", "radius", 5000) @define "segmentsWidth", entityAttribute("segmentsWidth", "segments-width", 64) @define "segmentsHeight", entityAttribute("segmentsHeight", "segments-height", 64) @define "crossOrigin", entityAttribute("crossOrigin", "crossOrigin", "anonymous") @define "autoplay", entityAttribute("autoplay", "autoplay", no) @define "loop", entityAttribute("loop", "loop", no) @define "volume", entityAttribute("volume", "volume", 1)
true
{entityAttribute, Entity} = require "./Entity" class exports.VideoSphere extends Entity entity : name: "PI:NAME:<NAME>END_PI" type: "a-videosphere" # ---------------------------------------------------------------------------- # PROPERTIES @define "radius", entityAttribute("radius", "radius", 5000) @define "segmentsWidth", entityAttribute("segmentsWidth", "segments-width", 64) @define "segmentsHeight", entityAttribute("segmentsHeight", "segments-height", 64) @define "crossOrigin", entityAttribute("crossOrigin", "crossOrigin", "anonymous") @define "autoplay", entityAttribute("autoplay", "autoplay", no) @define "loop", entityAttribute("loop", "loop", no) @define "volume", entityAttribute("volume", "volume", 1)
[ { "context": "= process.env.SURESPOT_REDIS_SENTINEL_HOSTNAME ? \"127.0.0.1\"\ndontUseSSL = process.env.SURESPOT_DONT_USE_SSL i", "end": 542, "score": 0.9997019171714783, "start": 533, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "\"true\"\n\n\npool = new helenus.Connecti...
test/test/externalInviteTests.coffee
SchoolOfFreelancing/SureSpot
1
request = require("request") assert = require("assert") should = require("should") redis = require("redis") util = require("util") fs = require("fs") io = require 'socket.io-client' crypto = require 'crypto' dcrypt = require 'dcrypt' async = require 'async' redisSentinel = require 'redis-sentinel-client' helenus = require 'helenus' socketPort = process.env.SURESPOT_SOCKET ? 8080 redisSentinelPort = parseInt(process.env.SURESPOT_REDIS_SENTINEL_PORT) ? 6379 redisSentinelHostname = process.env.SURESPOT_REDIS_SENTINEL_HOSTNAME ? "127.0.0.1" dontUseSSL = process.env.SURESPOT_DONT_USE_SSL is "true" baseUri = process.env.SURESPOT_TEST_BASEURI cleanupDb = process.env.SURESPOT_TEST_CLEANDB is "true" useRedisSentinel = process.env.SURESPOT_USE_REDIS_SENTINEL is "true" pool = new helenus.ConnectionPool({host:'127.0.0.1', port:9160, keyspace:'surespot'}); rc = if useRedisSentinel then redisSentinel.createClient(redisSentinelPort, redisSentinelHostname) else redis.createClient(redisSentinelPort, redisSentinelHostname) port = socketPort jar1 = undefined jar2 = undefined jar3 = undefined jar4 = undefined cookie1 = undefined cookie2 = undefined cookie3 = undefined cleanup = (done) -> keys = [ "u:test0", "u:test1", "u:test2", "u:test3", "f:test0", "f:test1", "is:test0", "ir:test0", "is:test1", "is:test2", "is:test3", "ir:test1", "ir:test2", "ir:test3", "c:test1", "c:test0", "c:test2", "kt:test0" "kv:test0", "k:test0", "kv:test1", "k:test1", "kv:test2", "k:test2", "kv:test3", "k:test3"] multi = rc.multi() multi.del keys multi.hdel "mcounters", "test0:test1" multi.hdel "ucmcounters", "test0" multi.hdel "ucmcounters", "test1" multi.hdel "ucmcounters", "test2" multi.hdel "ucmcounters", "test3" multi.srem "u", "test0", "test1", "test2", "test3" multi.exec (err, results) -> return done err if err? pool.connect (err, keyspace) -> return done err if err? cql = "begin batch delete from chatmessages where username = ? delete from chatmessages where username = ? delete from usercontrolmessages where username = ? delete from usercontrolmessages where username = ? delete from usercontrolmessages where username = ? delete from usercontrolmessages where username = ? apply batch" pool.cql cql, ["test0", "test1", "test0", "test1","test2","test3"], (err, results) -> if err done err else done() login = (username, password, jar, authSig, referrers, done, callback) -> request.post url: baseUri + "/login" jar: jar json: username: username password: password authSig: authSig referrers: referrers version: 56 platform:'android' (err, res, body) -> if err done err else cookie = jar.get({ url: baseUri }).map((c) -> c.name + "=" + c.value).join("; ") callback res, body, cookie signup = (username, password, jar, dhPub, dsaPub, authSig, referrers, done, callback) -> request.post url: baseUri + "/users" jar: jar json: username: username password: password dhPub: dhPub dsaPub: dsaPub authSig: authSig referrers: referrers version: 56 platform:'android' (err, res, body) -> if err done err else cookie = jar.get({ url: baseUri }).map((c) -> c.name + "=" + c.value).join("; ") callback res, body, cookie generateKey = (i, callback) -> ecdsa = new dcrypt.keypair.newECDSA 'secp521r1' ecdh = new dcrypt.keypair.newECDSA 'secp521r1' random = crypto.randomBytes 16 dsaPubSig = crypto .createSign('sha256') .update(new Buffer("test#{i}")) .update(new Buffer("test#{i}")) .update(random) .sign(ecdsa.pem_priv, 'base64') sig = Buffer.concat([random, new Buffer(dsaPubSig, 'base64')]).toString('base64') callback null, { ecdsa: ecdsa ecdh: ecdh sig: sig } makeKeys = (i) -> return (callback) -> generateKey i, callback createKeys = (number, done) -> keys = [] for i in [0..number] keys.push makeKeys(i) async.parallel keys, (err, results) -> if err? done err else done null, results describe "external invite tests", () -> keys = undefined before (done) -> createKeys 3, (err, keyss) -> keys = keyss if cleanupDb cleanup done else done() client = undefined client1 = undefined jsonMessage = {type: "message", to: "test0", toVersion: "1", from: "test1", fromVersion: "1", iv: 1, data: "message data", mimeType: "text/plain"} it 'signup with auto invite user should send invite control message to auto invite user', (done) -> receivedSignupResponse = false gotControlMessage = false jar1 = request.jar() signup 'test0', 'test0', jar1, keys[0].ecdh.pem_pub, keys[0].ecdsa.pem_pub, keys[0].sig, null, done, (res, body, cookie) -> client = io.connect baseUri, { 'force new connection': true}, cookie client.once 'connect', -> jar2 = request.jar() signup 'test1', 'test1', jar2, keys[1].ecdh.pem_pub, keys[1].ecdsa.pem_pub, keys[1].sig, JSON.stringify([{ utm_content: "test0"}]), done , (res, body, cookie) -> receivedSignupResponse = true done() if gotControlMessage client.once 'control', (data) -> receivedControlMessage = JSON.parse data receivedControlMessage.type.should.equal 'user' receivedControlMessage.action.should.equal 'invite' receivedControlMessage.data.should.equal 'test1' should.not.exist receivedControlMessage.localid should.not.exist receivedControlMessage.moredata gotControlMessage = true done() if receivedSignupResponse describe 'get friends after signup', () -> it 'should have user marked invited', (done) -> request.get jar: jar1 url: baseUri + "/friends" (err, res, body) -> if err done err else res.statusCode.should.equal 200 friendData = JSON.parse(body) friendData.friends[0].flags.should.equal 32 done() it 'should have created an invite user control message', (done) -> request.get jar: jar1 url: baseUri + "/latestids/0" (err, res, body) -> if err done err else res.statusCode.should.equal 200 messageData = JSON.parse(body) controlData = messageData.userControlMessages controlData.length.should.equal 1 receivedControlMessage = JSON.parse(controlData[0]) receivedControlMessage.type.should.equal "user" receivedControlMessage.action.should.equal "invite" receivedControlMessage.data.should.equal "test1" receivedControlMessage.id.should.equal 1 should.not.exist receivedControlMessage.moredata should.not.exist receivedControlMessage.from done() # it 'login with auto invite user should send invite control message to auto invite user', (done) -> # receivedSignupResponse = false # gotControlMessage = false # jar3 = request.jar() # jar4 = request.jar() # # signup 'test2', 'test2', jar3, keys[2].ecdh.pem_pub, keys[2].ecdsa.pem_pub, keys[2].sig, null, done, (res, body, cookie) -> # client2 = io.connect baseUri, { 'force new connection': true}, cookie # client2.once 'connect', -> # signup 'test3', 'test3', jar4, keys[3].ecdh.pem_pub, keys[3].ecdsa.pem_pub, keys[3].sig, null, done, (res, body, cookie) -> # request.get # jar: jar4 # url: baseUri + "/logout" # (err, res, body) -> # if err # done err # else # login "test3", "test3", jar4, keys[3].sig, JSON.stringify([{ utm_content: "test2"}]), done, (res, body) -> # receivedSignupResponse = true # done() if gotControlMessage # # client2.once 'control', (data) -> # receivedControlMessage = JSON.parse data # receivedControlMessage.type.should.equal 'user' # receivedControlMessage.action.should.equal 'invite' # receivedControlMessage.data.should.equal 'test3' # should.not.exist receivedControlMessage.localid # should.not.exist receivedControlMessage.moredata # gotControlMessage = true # done() if receivedSignupResponse # describe 'get friends after login', () -> # it 'should have user marked invited', (done) -> # request.get # jar: jar3 # url: baseUri + "/friends" # (err, res, body) -> # if err # done err # else # res.statusCode.should.equal 200 # messageData = JSON.parse(body) # messageData.friends[0].flags.should.equal 32 # done() # # it 'should have created an invite user control message', (done) -> # request.get # jar: jar3 # url: baseUri + "/latestids/0" # (err, res, body) -> # if err # done err # else # res.statusCode.should.equal 200 # messageData = JSON.parse(body) # # controlData = messageData.userControlMessages # controlData.length.should.equal 1 # receivedControlMessage = JSON.parse(controlData[0]) # receivedControlMessage.type.should.equal "user" # receivedControlMessage.action.should.equal "invite" # receivedControlMessage.data.should.equal "test3" # receivedControlMessage.id.should.equal 1 # should.not.exist receivedControlMessage.localid # should.not.exist receivedControlMessage.moredata # should.not.exist receivedControlMessage.from # done() after (done) -> client.disconnect() if cleanupDb cleanup done else done()
147720
request = require("request") assert = require("assert") should = require("should") redis = require("redis") util = require("util") fs = require("fs") io = require 'socket.io-client' crypto = require 'crypto' dcrypt = require 'dcrypt' async = require 'async' redisSentinel = require 'redis-sentinel-client' helenus = require 'helenus' socketPort = process.env.SURESPOT_SOCKET ? 8080 redisSentinelPort = parseInt(process.env.SURESPOT_REDIS_SENTINEL_PORT) ? 6379 redisSentinelHostname = process.env.SURESPOT_REDIS_SENTINEL_HOSTNAME ? "127.0.0.1" dontUseSSL = process.env.SURESPOT_DONT_USE_SSL is "true" baseUri = process.env.SURESPOT_TEST_BASEURI cleanupDb = process.env.SURESPOT_TEST_CLEANDB is "true" useRedisSentinel = process.env.SURESPOT_USE_REDIS_SENTINEL is "true" pool = new helenus.ConnectionPool({host:'127.0.0.1', port:9160, keyspace:'surespot'}); rc = if useRedisSentinel then redisSentinel.createClient(redisSentinelPort, redisSentinelHostname) else redis.createClient(redisSentinelPort, redisSentinelHostname) port = socketPort jar1 = undefined jar2 = undefined jar3 = undefined jar4 = undefined cookie1 = undefined cookie2 = undefined cookie3 = undefined cleanup = (done) -> keys = [ "u:test0", "u:test1", "u:test2", "u:test3", "f:test0", "f:test1", "is:test0", "ir:test0", "is:test1", "is:test2", "is:test3", "ir:test1", "ir:test2", "ir:test3", "c:test1", "c:test0", "c:test2", "kt:test0" "kv:test0", "k:test0", "kv:test1", "k:test1", "kv:test2", "k:test2", "kv:test3", "k:test3"] multi = rc.multi() multi.del keys multi.hdel "mcounters", "test0:test1" multi.hdel "ucmcounters", "test0" multi.hdel "ucmcounters", "test1" multi.hdel "ucmcounters", "test2" multi.hdel "ucmcounters", "test3" multi.srem "u", "test0", "test1", "test2", "test3" multi.exec (err, results) -> return done err if err? pool.connect (err, keyspace) -> return done err if err? cql = "begin batch delete from chatmessages where username = ? delete from chatmessages where username = ? delete from usercontrolmessages where username = ? delete from usercontrolmessages where username = ? delete from usercontrolmessages where username = ? delete from usercontrolmessages where username = ? apply batch" pool.cql cql, ["test0", "test1", "test0", "test1","test2","test3"], (err, results) -> if err done err else done() login = (username, password, jar, authSig, referrers, done, callback) -> request.post url: baseUri + "/login" jar: jar json: username: username password: <PASSWORD> authSig: authSig referrers: referrers version: 56 platform:'android' (err, res, body) -> if err done err else cookie = jar.get({ url: baseUri }).map((c) -> c.name + "=" + c.value).join("; ") callback res, body, cookie signup = (username, <PASSWORD>, jar, dhPub, dsaPub, authSig, referrers, done, callback) -> request.post url: baseUri + "/users" jar: jar json: username: username password: <PASSWORD> dhPub: dhPub dsaPub: dsaPub authSig: authSig referrers: referrers version: 56 platform:'android' (err, res, body) -> if err done err else cookie = jar.get({ url: baseUri }).map((c) -> c.name + "=" + c.value).join("; ") callback res, body, cookie generateKey = (i, callback) -> ecdsa = new dcrypt.keypair.newECDSA 'secp521r1' ecdh = new dcrypt.keypair.newECDSA 'secp<KEY>21r1' random = crypto.randomBytes 16 dsaPubSig = crypto .createSign('sha256') .update(new Buffer("test#{i}")) .update(new Buffer("test#{i}")) .update(random) .sign(ecdsa.pem_priv, 'base64') sig = Buffer.concat([random, new Buffer(dsaPubSig, 'base64')]).toString('base64') callback null, { ecdsa: ecdsa ecdh: ecdh sig: sig } makeKeys = (i) -> return (callback) -> generateKey i, callback createKeys = (number, done) -> keys = [] for i in [0..number] keys.push makeKeys(i) async.parallel keys, (err, results) -> if err? done err else done null, results describe "external invite tests", () -> keys = undefined before (done) -> createKeys 3, (err, keyss) -> keys = keyss if cleanupDb cleanup done else done() client = undefined client1 = undefined jsonMessage = {type: "message", to: "test0", toVersion: "1", from: "test1", fromVersion: "1", iv: 1, data: "message data", mimeType: "text/plain"} it 'signup with auto invite user should send invite control message to auto invite user', (done) -> receivedSignupResponse = false gotControlMessage = false jar1 = request.jar() signup 'test0', 'test0', jar1, keys[0].ecdh.pem_pub, keys[0].ecdsa.pem_pub, keys[0].sig, null, done, (res, body, cookie) -> client = io.connect baseUri, { 'force new connection': true}, cookie client.once 'connect', -> jar2 = request.jar() signup 'test1', 'test1', jar2, keys[1].ecdh.pem_pub, keys[1].ecdsa.pem_pub, keys[1].sig, JSON.stringify([{ utm_content: "test0"}]), done , (res, body, cookie) -> receivedSignupResponse = true done() if gotControlMessage client.once 'control', (data) -> receivedControlMessage = JSON.parse data receivedControlMessage.type.should.equal 'user' receivedControlMessage.action.should.equal 'invite' receivedControlMessage.data.should.equal 'test1' should.not.exist receivedControlMessage.localid should.not.exist receivedControlMessage.moredata gotControlMessage = true done() if receivedSignupResponse describe 'get friends after signup', () -> it 'should have user marked invited', (done) -> request.get jar: jar1 url: baseUri + "/friends" (err, res, body) -> if err done err else res.statusCode.should.equal 200 friendData = JSON.parse(body) friendData.friends[0].flags.should.equal 32 done() it 'should have created an invite user control message', (done) -> request.get jar: jar1 url: baseUri + "/latestids/0" (err, res, body) -> if err done err else res.statusCode.should.equal 200 messageData = JSON.parse(body) controlData = messageData.userControlMessages controlData.length.should.equal 1 receivedControlMessage = JSON.parse(controlData[0]) receivedControlMessage.type.should.equal "user" receivedControlMessage.action.should.equal "invite" receivedControlMessage.data.should.equal "test1" receivedControlMessage.id.should.equal 1 should.not.exist receivedControlMessage.moredata should.not.exist receivedControlMessage.from done() # it 'login with auto invite user should send invite control message to auto invite user', (done) -> # receivedSignupResponse = false # gotControlMessage = false # jar3 = request.jar() # jar4 = request.jar() # # signup 'test2', 'test2', jar3, keys[2].ecdh.pem_pub, keys[2].ecdsa.pem_pub, keys[2].sig, null, done, (res, body, cookie) -> # client2 = io.connect baseUri, { 'force new connection': true}, cookie # client2.once 'connect', -> # signup 'test3', 'test3', jar4, keys[3].ecdh.pem_pub, keys[3].ecdsa.pem_pub, keys[3].sig, null, done, (res, body, cookie) -> # request.get # jar: jar4 # url: baseUri + "/logout" # (err, res, body) -> # if err # done err # else # login "test3", "test3", jar4, keys[3].sig, JSON.stringify([{ utm_content: "test2"}]), done, (res, body) -> # receivedSignupResponse = true # done() if gotControlMessage # # client2.once 'control', (data) -> # receivedControlMessage = JSON.parse data # receivedControlMessage.type.should.equal 'user' # receivedControlMessage.action.should.equal 'invite' # receivedControlMessage.data.should.equal 'test3' # should.not.exist receivedControlMessage.localid # should.not.exist receivedControlMessage.moredata # gotControlMessage = true # done() if receivedSignupResponse # describe 'get friends after login', () -> # it 'should have user marked invited', (done) -> # request.get # jar: jar3 # url: baseUri + "/friends" # (err, res, body) -> # if err # done err # else # res.statusCode.should.equal 200 # messageData = JSON.parse(body) # messageData.friends[0].flags.should.equal 32 # done() # # it 'should have created an invite user control message', (done) -> # request.get # jar: jar3 # url: baseUri + "/latestids/0" # (err, res, body) -> # if err # done err # else # res.statusCode.should.equal 200 # messageData = JSON.parse(body) # # controlData = messageData.userControlMessages # controlData.length.should.equal 1 # receivedControlMessage = JSON.parse(controlData[0]) # receivedControlMessage.type.should.equal "user" # receivedControlMessage.action.should.equal "invite" # receivedControlMessage.data.should.equal "test3" # receivedControlMessage.id.should.equal 1 # should.not.exist receivedControlMessage.localid # should.not.exist receivedControlMessage.moredata # should.not.exist receivedControlMessage.from # done() after (done) -> client.disconnect() if cleanupDb cleanup done else done()
true
request = require("request") assert = require("assert") should = require("should") redis = require("redis") util = require("util") fs = require("fs") io = require 'socket.io-client' crypto = require 'crypto' dcrypt = require 'dcrypt' async = require 'async' redisSentinel = require 'redis-sentinel-client' helenus = require 'helenus' socketPort = process.env.SURESPOT_SOCKET ? 8080 redisSentinelPort = parseInt(process.env.SURESPOT_REDIS_SENTINEL_PORT) ? 6379 redisSentinelHostname = process.env.SURESPOT_REDIS_SENTINEL_HOSTNAME ? "127.0.0.1" dontUseSSL = process.env.SURESPOT_DONT_USE_SSL is "true" baseUri = process.env.SURESPOT_TEST_BASEURI cleanupDb = process.env.SURESPOT_TEST_CLEANDB is "true" useRedisSentinel = process.env.SURESPOT_USE_REDIS_SENTINEL is "true" pool = new helenus.ConnectionPool({host:'127.0.0.1', port:9160, keyspace:'surespot'}); rc = if useRedisSentinel then redisSentinel.createClient(redisSentinelPort, redisSentinelHostname) else redis.createClient(redisSentinelPort, redisSentinelHostname) port = socketPort jar1 = undefined jar2 = undefined jar3 = undefined jar4 = undefined cookie1 = undefined cookie2 = undefined cookie3 = undefined cleanup = (done) -> keys = [ "u:test0", "u:test1", "u:test2", "u:test3", "f:test0", "f:test1", "is:test0", "ir:test0", "is:test1", "is:test2", "is:test3", "ir:test1", "ir:test2", "ir:test3", "c:test1", "c:test0", "c:test2", "kt:test0" "kv:test0", "k:test0", "kv:test1", "k:test1", "kv:test2", "k:test2", "kv:test3", "k:test3"] multi = rc.multi() multi.del keys multi.hdel "mcounters", "test0:test1" multi.hdel "ucmcounters", "test0" multi.hdel "ucmcounters", "test1" multi.hdel "ucmcounters", "test2" multi.hdel "ucmcounters", "test3" multi.srem "u", "test0", "test1", "test2", "test3" multi.exec (err, results) -> return done err if err? pool.connect (err, keyspace) -> return done err if err? cql = "begin batch delete from chatmessages where username = ? delete from chatmessages where username = ? delete from usercontrolmessages where username = ? delete from usercontrolmessages where username = ? delete from usercontrolmessages where username = ? delete from usercontrolmessages where username = ? apply batch" pool.cql cql, ["test0", "test1", "test0", "test1","test2","test3"], (err, results) -> if err done err else done() login = (username, password, jar, authSig, referrers, done, callback) -> request.post url: baseUri + "/login" jar: jar json: username: username password: PI:PASSWORD:<PASSWORD>END_PI authSig: authSig referrers: referrers version: 56 platform:'android' (err, res, body) -> if err done err else cookie = jar.get({ url: baseUri }).map((c) -> c.name + "=" + c.value).join("; ") callback res, body, cookie signup = (username, PI:PASSWORD:<PASSWORD>END_PI, jar, dhPub, dsaPub, authSig, referrers, done, callback) -> request.post url: baseUri + "/users" jar: jar json: username: username password: PI:PASSWORD:<PASSWORD>END_PI dhPub: dhPub dsaPub: dsaPub authSig: authSig referrers: referrers version: 56 platform:'android' (err, res, body) -> if err done err else cookie = jar.get({ url: baseUri }).map((c) -> c.name + "=" + c.value).join("; ") callback res, body, cookie generateKey = (i, callback) -> ecdsa = new dcrypt.keypair.newECDSA 'secp521r1' ecdh = new dcrypt.keypair.newECDSA 'secpPI:KEY:<KEY>END_PI21r1' random = crypto.randomBytes 16 dsaPubSig = crypto .createSign('sha256') .update(new Buffer("test#{i}")) .update(new Buffer("test#{i}")) .update(random) .sign(ecdsa.pem_priv, 'base64') sig = Buffer.concat([random, new Buffer(dsaPubSig, 'base64')]).toString('base64') callback null, { ecdsa: ecdsa ecdh: ecdh sig: sig } makeKeys = (i) -> return (callback) -> generateKey i, callback createKeys = (number, done) -> keys = [] for i in [0..number] keys.push makeKeys(i) async.parallel keys, (err, results) -> if err? done err else done null, results describe "external invite tests", () -> keys = undefined before (done) -> createKeys 3, (err, keyss) -> keys = keyss if cleanupDb cleanup done else done() client = undefined client1 = undefined jsonMessage = {type: "message", to: "test0", toVersion: "1", from: "test1", fromVersion: "1", iv: 1, data: "message data", mimeType: "text/plain"} it 'signup with auto invite user should send invite control message to auto invite user', (done) -> receivedSignupResponse = false gotControlMessage = false jar1 = request.jar() signup 'test0', 'test0', jar1, keys[0].ecdh.pem_pub, keys[0].ecdsa.pem_pub, keys[0].sig, null, done, (res, body, cookie) -> client = io.connect baseUri, { 'force new connection': true}, cookie client.once 'connect', -> jar2 = request.jar() signup 'test1', 'test1', jar2, keys[1].ecdh.pem_pub, keys[1].ecdsa.pem_pub, keys[1].sig, JSON.stringify([{ utm_content: "test0"}]), done , (res, body, cookie) -> receivedSignupResponse = true done() if gotControlMessage client.once 'control', (data) -> receivedControlMessage = JSON.parse data receivedControlMessage.type.should.equal 'user' receivedControlMessage.action.should.equal 'invite' receivedControlMessage.data.should.equal 'test1' should.not.exist receivedControlMessage.localid should.not.exist receivedControlMessage.moredata gotControlMessage = true done() if receivedSignupResponse describe 'get friends after signup', () -> it 'should have user marked invited', (done) -> request.get jar: jar1 url: baseUri + "/friends" (err, res, body) -> if err done err else res.statusCode.should.equal 200 friendData = JSON.parse(body) friendData.friends[0].flags.should.equal 32 done() it 'should have created an invite user control message', (done) -> request.get jar: jar1 url: baseUri + "/latestids/0" (err, res, body) -> if err done err else res.statusCode.should.equal 200 messageData = JSON.parse(body) controlData = messageData.userControlMessages controlData.length.should.equal 1 receivedControlMessage = JSON.parse(controlData[0]) receivedControlMessage.type.should.equal "user" receivedControlMessage.action.should.equal "invite" receivedControlMessage.data.should.equal "test1" receivedControlMessage.id.should.equal 1 should.not.exist receivedControlMessage.moredata should.not.exist receivedControlMessage.from done() # it 'login with auto invite user should send invite control message to auto invite user', (done) -> # receivedSignupResponse = false # gotControlMessage = false # jar3 = request.jar() # jar4 = request.jar() # # signup 'test2', 'test2', jar3, keys[2].ecdh.pem_pub, keys[2].ecdsa.pem_pub, keys[2].sig, null, done, (res, body, cookie) -> # client2 = io.connect baseUri, { 'force new connection': true}, cookie # client2.once 'connect', -> # signup 'test3', 'test3', jar4, keys[3].ecdh.pem_pub, keys[3].ecdsa.pem_pub, keys[3].sig, null, done, (res, body, cookie) -> # request.get # jar: jar4 # url: baseUri + "/logout" # (err, res, body) -> # if err # done err # else # login "test3", "test3", jar4, keys[3].sig, JSON.stringify([{ utm_content: "test2"}]), done, (res, body) -> # receivedSignupResponse = true # done() if gotControlMessage # # client2.once 'control', (data) -> # receivedControlMessage = JSON.parse data # receivedControlMessage.type.should.equal 'user' # receivedControlMessage.action.should.equal 'invite' # receivedControlMessage.data.should.equal 'test3' # should.not.exist receivedControlMessage.localid # should.not.exist receivedControlMessage.moredata # gotControlMessage = true # done() if receivedSignupResponse # describe 'get friends after login', () -> # it 'should have user marked invited', (done) -> # request.get # jar: jar3 # url: baseUri + "/friends" # (err, res, body) -> # if err # done err # else # res.statusCode.should.equal 200 # messageData = JSON.parse(body) # messageData.friends[0].flags.should.equal 32 # done() # # it 'should have created an invite user control message', (done) -> # request.get # jar: jar3 # url: baseUri + "/latestids/0" # (err, res, body) -> # if err # done err # else # res.statusCode.should.equal 200 # messageData = JSON.parse(body) # # controlData = messageData.userControlMessages # controlData.length.should.equal 1 # receivedControlMessage = JSON.parse(controlData[0]) # receivedControlMessage.type.should.equal "user" # receivedControlMessage.action.should.equal "invite" # receivedControlMessage.data.should.equal "test3" # receivedControlMessage.id.should.equal 1 # should.not.exist receivedControlMessage.localid # should.not.exist receivedControlMessage.moredata # should.not.exist receivedControlMessage.from # done() after (done) -> client.disconnect() if cleanupDb cleanup done else done()
[ { "context": "roject)=>\n @capTable = [\n {name: 'Glenn', address: 'addy1', amount: 300},\n {name", "end": 395, "score": 0.9997422099113464, "start": 390, "tag": "NAME", "value": "Glenn" }, { "context": "address: 'addy1', amount: 300},\n {name: 'Duke...
test/views/projects/cap-table-view-tests.coffee
citizencode/swarmbot
21
{ createProject } = require '../../helpers/test-helper' Project = require '../../../src/models/project.coffee' CapTableView = require '../../../src/views/projects/cap-table-view.coffee' describe 'CapTableView', -> describe 'render', -> it 'returns a string with a sweet Google chart api url', -> createProject() .then (@project)=> @capTable = [ {name: 'Glenn', address: 'addy1', amount: 300}, {name: 'Duke', address: 'addy2', amount: 400}, {name: 'Harlan', address: 'addy3', amount: 500}, ] view = new CapTableView({@project, @capTable}) result = view.render() result[0].title.should.eq 'some project id' result[0].image_url.should.match ///https://chart.googleapis.com/chart\?/// result[0].image_url.should.match ///chs=450x200/// result[0].image_url.should.match ///chd=t:25,33.333333333333336,41.666666666666664/// result[0].image_url.should.match ///cht=p3/// result[0].image_url.should.match ///&chma=30,30,30,30/// result[0].image_url.should.match ///chl=Glenn%2025%25|Duke%2033%25|Harlan%2042%25"///
145532
{ createProject } = require '../../helpers/test-helper' Project = require '../../../src/models/project.coffee' CapTableView = require '../../../src/views/projects/cap-table-view.coffee' describe 'CapTableView', -> describe 'render', -> it 'returns a string with a sweet Google chart api url', -> createProject() .then (@project)=> @capTable = [ {name: '<NAME>', address: 'addy1', amount: 300}, {name: '<NAME>', address: 'addy2', amount: 400}, {name: '<NAME>', address: 'addy3', amount: 500}, ] view = new CapTableView({@project, @capTable}) result = view.render() result[0].title.should.eq 'some project id' result[0].image_url.should.match ///https://chart.googleapis.com/chart\?/// result[0].image_url.should.match ///chs=450x200/// result[0].image_url.should.match ///chd=t:25,33.333333333333336,41.666666666666664/// result[0].image_url.should.match ///cht=p3/// result[0].image_url.should.match ///&chma=30,30,30,30/// result[0].image_url.should.match ///chl=Glenn%2025%25|Duke%2033%25|Har<NAME>%2042%25"///
true
{ createProject } = require '../../helpers/test-helper' Project = require '../../../src/models/project.coffee' CapTableView = require '../../../src/views/projects/cap-table-view.coffee' describe 'CapTableView', -> describe 'render', -> it 'returns a string with a sweet Google chart api url', -> createProject() .then (@project)=> @capTable = [ {name: 'PI:NAME:<NAME>END_PI', address: 'addy1', amount: 300}, {name: 'PI:NAME:<NAME>END_PI', address: 'addy2', amount: 400}, {name: 'PI:NAME:<NAME>END_PI', address: 'addy3', amount: 500}, ] view = new CapTableView({@project, @capTable}) result = view.render() result[0].title.should.eq 'some project id' result[0].image_url.should.match ///https://chart.googleapis.com/chart\?/// result[0].image_url.should.match ///chs=450x200/// result[0].image_url.should.match ///chd=t:25,33.333333333333336,41.666666666666664/// result[0].image_url.should.match ///cht=p3/// result[0].image_url.should.match ///&chma=30,30,30,30/// result[0].image_url.should.match ///chl=Glenn%2025%25|Duke%2033%25|HarPI:NAME:<NAME>END_PI%2042%25"///
[ { "context": " ]\n 'clients': ->\n [\n {\n 'name': 'Le Château'\n 'description': ->\n TAPi18n.__ '", "end": 1120, "score": 0.9987743496894836, "start": 1110, "tag": "NAME", "value": "Le Château" }, { "context": "eau_description'\n }\n {\n ...
client/views/home/home.coffee
boogieprod/midzone
0
Template.home.helpers 'feature': -> [ { 'text': -> TAPi18n.__ 'our_services' 'icon': 'archive' 'path': '#services' } { 'text': -> TAPi18n.__ 'our_clients' 'icon': 'users' 'path': '#clients' } { 'text': -> TAPi18n.__ 'proposal' 'icon': 'edit' 'color': 'hover-orange' 'path': '#proposal' } { 'text': -> TAPi18n.__ 'about_us' 'icon': 'find' 'path': '#about' } ] 'services': -> [ { 'name': -> TAPi18n.__ 'pos_integ' } { 'name': -> TAPi18n.__ 'proj_manag' } { 'name': -> TAPi18n.__ 'bank_certif' } { 'name': -> TAPi18n.__ 'net_architecture' } { 'name': -> TAPi18n.__ 'tech_training' } { 'name': -> TAPi18n.__ 'func_training' } { 'name': 'Installation' } ] 'clients': -> [ { 'name': 'Le Château' 'description': -> TAPi18n.__ 'chateau_description' } { 'name': 'Stokes' 'description': -> TAPi18n.__ 'stokes_description' } { 'name': 'Exemple' 'description': -> TAPi18n.__ 'ex_description' } { 'name': 'Exemple' 'description': -> TAPi18n.__ 'ex_description' } { 'name': 'Exemple' 'description': -> TAPi18n.__ 'ex_description' } { 'name': 'Exemple' 'description': -> TAPi18n.__ 'ex_description' } { 'name': 'Exemple' 'description': -> TAPi18n.__ 'ex_description' } ] 'semanticElement': -> [ { 'what': -> TAPi18n.__ 'large_buttons' 'withBootstrap': 'btn btn-lg' 'withSemanticUI': 'ui large button' } { 'what': -> TAPi18n.__ 'one_column' 'withBootstrap': 'col-md-1' 'withSemanticUI': 'one wide column' } { 'what': -> TAPi18n.__ 'vertical_menu' 'withBootstrap': 'nav nav-pills' 'withSemanticUI': 'ui vertical menu' } ] 'owner': -> [ { 'name': 'Example' 'img': 'person.gif' 'description': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer a ex gravida, malesuada neque id, ullamcorper dui. Mauris nec ultrices felis, nec rutrum libero. Cras vel lacinia ex. Integer vulputate rutrum magna, vel egestas nunc tincidunt in. Phasellus metus orci, sodales eu nisi posuere, vehicula feugiat dolor. Aenean id euismod.' } { 'name': 'Example' 'img': 'person.gif' 'description': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer a ex gravida, malesuada neque id, ullamcorper dui. Mauris nec ultrices felis, nec rutrum libero. Cras vel lacinia ex. Integer vulputate rutrum magna, vel egestas nunc tincidunt in. Phasellus metus orci, sodales eu nisi posuere, vehicula feugiat dolor. Aenean id euismod.' } ] Template.home.events {} Template.home.rendered = -> # @see: http://stackoverflow.com/questions/5284814/jquery-scroll-to-div $('a[href*=#]:not([href=#])').click -> if location.pathname.replace(/^\//, '') == @pathname.replace(/^\//, '') and location.hostname == @hostname target = $(@hash) target = if target.length then target else $('[name=' + @hash.slice(1) + ']') if target.length $('html, body').animate { scrollTop: target.offset().top }, 1000 return false true return
67555
Template.home.helpers 'feature': -> [ { 'text': -> TAPi18n.__ 'our_services' 'icon': 'archive' 'path': '#services' } { 'text': -> TAPi18n.__ 'our_clients' 'icon': 'users' 'path': '#clients' } { 'text': -> TAPi18n.__ 'proposal' 'icon': 'edit' 'color': 'hover-orange' 'path': '#proposal' } { 'text': -> TAPi18n.__ 'about_us' 'icon': 'find' 'path': '#about' } ] 'services': -> [ { 'name': -> TAPi18n.__ 'pos_integ' } { 'name': -> TAPi18n.__ 'proj_manag' } { 'name': -> TAPi18n.__ 'bank_certif' } { 'name': -> TAPi18n.__ 'net_architecture' } { 'name': -> TAPi18n.__ 'tech_training' } { 'name': -> TAPi18n.__ 'func_training' } { 'name': 'Installation' } ] 'clients': -> [ { 'name': '<NAME>' 'description': -> TAPi18n.__ 'chateau_description' } { 'name': '<NAME>' 'description': -> TAPi18n.__ 'stokes_description' } { 'name': 'Exemple' 'description': -> TAPi18n.__ 'ex_description' } { 'name': 'Exemple' 'description': -> TAPi18n.__ 'ex_description' } { 'name': 'Exemple' 'description': -> TAPi18n.__ 'ex_description' } { 'name': 'Exemple' 'description': -> TAPi18n.__ 'ex_description' } { 'name': '<NAME>' 'description': -> TAPi18n.__ 'ex_description' } ] 'semanticElement': -> [ { 'what': -> TAPi18n.__ 'large_buttons' 'withBootstrap': 'btn btn-lg' 'withSemanticUI': 'ui large button' } { 'what': -> TAPi18n.__ 'one_column' 'withBootstrap': 'col-md-1' 'withSemanticUI': 'one wide column' } { 'what': -> TAPi18n.__ 'vertical_menu' 'withBootstrap': 'nav nav-pills' 'withSemanticUI': 'ui vertical menu' } ] 'owner': -> [ { 'name': '<NAME>' 'img': 'person.gif' 'description': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer a ex gravida, malesuada neque id, ullamcorper dui. Mauris nec ultrices felis, nec rutrum libero. Cras vel lacinia ex. Integer vulputate rutrum magna, vel egestas nunc tincidunt in. Phasellus metus orci, sodales eu nisi posuere, vehicula feugiat dolor. Aenean id euismod.' } { 'name': '<NAME>' 'img': 'person.gif' 'description': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer a ex gravida, malesuada neque id, ullamcorper dui. Mauris nec ultrices felis, nec rutrum libero. Cras vel lacinia ex. Integer vulputate rutrum magna, vel egestas nunc tincidunt in. Phasellus metus orci, sodales eu nisi posuere, vehicula feugiat dolor. Aenean id euismod.' } ] Template.home.events {} Template.home.rendered = -> # @see: http://stackoverflow.com/questions/5284814/jquery-scroll-to-div $('a[href*=#]:not([href=#])').click -> if location.pathname.replace(/^\//, '') == @pathname.replace(/^\//, '') and location.hostname == @hostname target = $(@hash) target = if target.length then target else $('[name=' + @hash.slice(1) + ']') if target.length $('html, body').animate { scrollTop: target.offset().top }, 1000 return false true return
true
Template.home.helpers 'feature': -> [ { 'text': -> TAPi18n.__ 'our_services' 'icon': 'archive' 'path': '#services' } { 'text': -> TAPi18n.__ 'our_clients' 'icon': 'users' 'path': '#clients' } { 'text': -> TAPi18n.__ 'proposal' 'icon': 'edit' 'color': 'hover-orange' 'path': '#proposal' } { 'text': -> TAPi18n.__ 'about_us' 'icon': 'find' 'path': '#about' } ] 'services': -> [ { 'name': -> TAPi18n.__ 'pos_integ' } { 'name': -> TAPi18n.__ 'proj_manag' } { 'name': -> TAPi18n.__ 'bank_certif' } { 'name': -> TAPi18n.__ 'net_architecture' } { 'name': -> TAPi18n.__ 'tech_training' } { 'name': -> TAPi18n.__ 'func_training' } { 'name': 'Installation' } ] 'clients': -> [ { 'name': 'PI:NAME:<NAME>END_PI' 'description': -> TAPi18n.__ 'chateau_description' } { 'name': 'PI:NAME:<NAME>END_PI' 'description': -> TAPi18n.__ 'stokes_description' } { 'name': 'Exemple' 'description': -> TAPi18n.__ 'ex_description' } { 'name': 'Exemple' 'description': -> TAPi18n.__ 'ex_description' } { 'name': 'Exemple' 'description': -> TAPi18n.__ 'ex_description' } { 'name': 'Exemple' 'description': -> TAPi18n.__ 'ex_description' } { 'name': 'PI:NAME:<NAME>END_PI' 'description': -> TAPi18n.__ 'ex_description' } ] 'semanticElement': -> [ { 'what': -> TAPi18n.__ 'large_buttons' 'withBootstrap': 'btn btn-lg' 'withSemanticUI': 'ui large button' } { 'what': -> TAPi18n.__ 'one_column' 'withBootstrap': 'col-md-1' 'withSemanticUI': 'one wide column' } { 'what': -> TAPi18n.__ 'vertical_menu' 'withBootstrap': 'nav nav-pills' 'withSemanticUI': 'ui vertical menu' } ] 'owner': -> [ { 'name': 'PI:NAME:<NAME>END_PI' 'img': 'person.gif' 'description': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer a ex gravida, malesuada neque id, ullamcorper dui. Mauris nec ultrices felis, nec rutrum libero. Cras vel lacinia ex. Integer vulputate rutrum magna, vel egestas nunc tincidunt in. Phasellus metus orci, sodales eu nisi posuere, vehicula feugiat dolor. Aenean id euismod.' } { 'name': 'PI:NAME:<NAME>END_PI' 'img': 'person.gif' 'description': 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer a ex gravida, malesuada neque id, ullamcorper dui. Mauris nec ultrices felis, nec rutrum libero. Cras vel lacinia ex. Integer vulputate rutrum magna, vel egestas nunc tincidunt in. Phasellus metus orci, sodales eu nisi posuere, vehicula feugiat dolor. Aenean id euismod.' } ] Template.home.events {} Template.home.rendered = -> # @see: http://stackoverflow.com/questions/5284814/jquery-scroll-to-div $('a[href*=#]:not([href=#])').click -> if location.pathname.replace(/^\//, '') == @pathname.replace(/^\//, '') and location.hostname == @hostname target = $(@hash) target = if target.length then target else $('[name=' + @hash.slice(1) + ']') if target.length $('html, body').animate { scrollTop: target.offset().top }, 1000 return false true return
[ { "context": "gDir: \"./greenlock.d\"\n maintainerEmail: \"contact@microstudio.dev\"\n cluster: false\n .ready (glx)=>\n", "end": 3907, "score": 0.9999184012413025, "start": 3884, "tag": "EMAIL", "value": "contact@microstudio.dev" }, { "context": "= require(\...
server/server.coffee
karlmolina/microstudio
0
compression = require "compression" express = require "express" cookieParser = require('cookie-parser') fs = require "fs" path = require "path" DB = require __dirname+"/db/db.js" FileStorage = require __dirname+"/filestorage/filestorage.js" Content = require __dirname+"/content/content.js" WebApp = require __dirname+"/webapp.js" Session = require __dirname+"/session/session.js" RateLimiter = require __dirname+"/ratelimiter.js" BuildManager = require __dirname+"/build/buildmanager.js" WebSocket = require "ws" process = require "process" class @Server constructor:(@config={},@callback)-> process.chdir __dirname @app_data = @config.app_data or ".." @mailer = # STUB sendMail:(recipient,subject,text)-> console.info "send mail to:#{recipient} subject:#{subject} text:#{text}" @stats = # STUB set:(name,value)-> max:(name,value)-> unique:(name,id)-> inc:(name)-> stop:()-> @last_backup_time = 0 if @config.realm == "production" @PORT = 443 @PROD = true else if @config.standalone @PORT = @config.port or 0 else @PORT = @config.port or 8080 @PROD = false @loadPlugins ()=> @create() create:()-> app = express() static_files = "../static" @date_started = Date.now() @rate_limiter = new RateLimiter @ app.use (req,res,next)=> if @rate_limiter.accept("request","general") and @rate_limiter.accept("request_ip",req.connection.remoteAddress) next() else res.status(500).send "" @stats.inc("http_requests") @stats.unique("ip_addresses",req.connection.remoteAddress) referrer = req.get("Referrer") if referrer? and not referrer.startsWith("http://localhost") and not referrer.startsWith("https://microstudio.io") and not referrer.startsWith("https://microstudio.dev") @stats.unique("referrer|"+referrer,req.connection.remoteAddress) app.use(compression()) app.use(cookieParser()) for plugin in @plugins if plugin.getStaticFolder? folder = plugin.getStaticFolder() app.use(express.static(folder)) app.use(express.static(static_files)) app.use("/lib/fontlib/ubuntu",express.static("node_modules/@fontsource/ubuntu")) app.use("/lib/fontlib/ubuntu-mono",express.static("node_modules/@fontsource/ubuntu-mono")) app.use("/lib/fontlib/source-sans-pro",express.static("node_modules/@fontsource/source-sans-pro")) app.use("/lib/fontlib/fontawesome",express.static("node_modules/@fortawesome/fontawesome-free")) app.use("/lib/ace",express.static("node_modules/ace-builds/src-min")) app.use("/lib/marked/marked.js",express.static("node_modules/marked/marked.min.js")) app.use("/lib/dompurify/purify.js",express.static("node_modules/dompurify/dist/purify.min.js")) app.use("/lib/jquery/jquery.js",express.static("node_modules/jquery/dist/jquery.min.js")) app.use("/lib/jquery-ui",express.static("node_modules/jquery-ui-dist")) app.use("/lib/pixijs",express.static("node_modules/pixi.js/dist/browser")) app.use("/lib/babylonjs",express.static("node_modules/babylonjs")) app.use("/lib/babylonjs",express.static("node_modules/babylonjs-loaders")) app.use("/lib/matterjs",express.static("node_modules/matter-js/build")) app.use("/lib/cannonjs",express.static("node_modules/cannon/build")) app.use("/lib/brython",express.static("node_modules/brython")) app.use("/lib/fengari",express.static("node_modules/fengari-web/dist")) app.use("/lib/qrcode",express.static("node_modules/qrcode/build")) @db = new DB "#{@app_data}/data",(db)=> for plugin in @plugins if plugin.dbLoaded? plugin.dbLoaded(db) if @PROD require('greenlock-express').init packageRoot: __dirname configDir: "./greenlock.d" maintainerEmail: "contact@microstudio.dev" cluster: false .ready (glx)=> @httpserver = glx.httpsServer() @use_cache = true glx.serveApp app @start(app,db) else if @config.standalone @use_cache = false @httpserver = require("http").createServer(app).listen @PORT,"127.0.0.1",()=> @PORT = @httpserver.address().port @start(app,db) console.info "standalone running on port #{@PORT}" @callback() if @callback? else @httpserver = require("http").createServer(app).listen(@PORT) @use_cache = false @start(app,db) start:(app,db)-> @active_users = 0 @io = new WebSocket.Server server: @httpserver maxPayload: 40000000 @sessions = [] @io.on "connection",(socket,request)=> socket.request = request socket.remoteAddress = request.connection.remoteAddress @sessions.push new Session @,socket console.info "MAX PAYLOAD = "+@io.options.maxPayload @session_check = setInterval (()=>@sessionCheck()),10000 @content = new Content @,db,new FileStorage "#{@app_data}/files" @build_manager = new BuildManager @ @webapp = new WebApp @,app for l in @webapp.languages @content.translator.createLanguage l process.on 'SIGINT', ()=> console.log "caught INT signal" @exit() process.on 'SIGTERM', ()=> console.log "caught TERM signal" @exit() #process.on 'SIGKILL', ()=> # console.log "caught KILL signal" # @exit() @exitcheck = setInterval (()=> if fs.existsSync("exit") @exit() fs.unlinkSync("exit") if fs.existsSync("update") @webapp.concatenator.refresh() fs.unlinkSync("update") ),2000 exit:()=> if @exited process.exit(0) @httpserver.close() @stats.stop() @rate_limiter.close() @io.close() @db.close() @content.close() clearInterval @exitcheck clearInterval @session_check @exited = true setTimeout (()=>@exit()),5000 sessionCheck:()-> for s in @sessions if s? s.timeCheck() return sessionClosed:(session)-> index = @sessions.indexOf(session) if index>=0 @sessions.splice index,1 loadPlugins:(callback)-> @plugins = [] fs.readdir "../plugins",(err,files)=> files = [] if not files? funk = ()=> if files.length==0 callback() else f = files.splice(0,1)[0] @loadPlugin "../plugins/#{f}",funk funk() loadPlugin:(folder,callback)-> if fs.existsSync "#{folder}/index.js" try Plugin = require "#{folder}/index.js" p = new Plugin(@) @plugins.push p console.info "loaded plugin #{folder}" catch err console.error err callback() else console.info "plugin #{folder} has no index.js" callback() module.exports = @Server
72626
compression = require "compression" express = require "express" cookieParser = require('cookie-parser') fs = require "fs" path = require "path" DB = require __dirname+"/db/db.js" FileStorage = require __dirname+"/filestorage/filestorage.js" Content = require __dirname+"/content/content.js" WebApp = require __dirname+"/webapp.js" Session = require __dirname+"/session/session.js" RateLimiter = require __dirname+"/ratelimiter.js" BuildManager = require __dirname+"/build/buildmanager.js" WebSocket = require "ws" process = require "process" class @Server constructor:(@config={},@callback)-> process.chdir __dirname @app_data = @config.app_data or ".." @mailer = # STUB sendMail:(recipient,subject,text)-> console.info "send mail to:#{recipient} subject:#{subject} text:#{text}" @stats = # STUB set:(name,value)-> max:(name,value)-> unique:(name,id)-> inc:(name)-> stop:()-> @last_backup_time = 0 if @config.realm == "production" @PORT = 443 @PROD = true else if @config.standalone @PORT = @config.port or 0 else @PORT = @config.port or 8080 @PROD = false @loadPlugins ()=> @create() create:()-> app = express() static_files = "../static" @date_started = Date.now() @rate_limiter = new RateLimiter @ app.use (req,res,next)=> if @rate_limiter.accept("request","general") and @rate_limiter.accept("request_ip",req.connection.remoteAddress) next() else res.status(500).send "" @stats.inc("http_requests") @stats.unique("ip_addresses",req.connection.remoteAddress) referrer = req.get("Referrer") if referrer? and not referrer.startsWith("http://localhost") and not referrer.startsWith("https://microstudio.io") and not referrer.startsWith("https://microstudio.dev") @stats.unique("referrer|"+referrer,req.connection.remoteAddress) app.use(compression()) app.use(cookieParser()) for plugin in @plugins if plugin.getStaticFolder? folder = plugin.getStaticFolder() app.use(express.static(folder)) app.use(express.static(static_files)) app.use("/lib/fontlib/ubuntu",express.static("node_modules/@fontsource/ubuntu")) app.use("/lib/fontlib/ubuntu-mono",express.static("node_modules/@fontsource/ubuntu-mono")) app.use("/lib/fontlib/source-sans-pro",express.static("node_modules/@fontsource/source-sans-pro")) app.use("/lib/fontlib/fontawesome",express.static("node_modules/@fortawesome/fontawesome-free")) app.use("/lib/ace",express.static("node_modules/ace-builds/src-min")) app.use("/lib/marked/marked.js",express.static("node_modules/marked/marked.min.js")) app.use("/lib/dompurify/purify.js",express.static("node_modules/dompurify/dist/purify.min.js")) app.use("/lib/jquery/jquery.js",express.static("node_modules/jquery/dist/jquery.min.js")) app.use("/lib/jquery-ui",express.static("node_modules/jquery-ui-dist")) app.use("/lib/pixijs",express.static("node_modules/pixi.js/dist/browser")) app.use("/lib/babylonjs",express.static("node_modules/babylonjs")) app.use("/lib/babylonjs",express.static("node_modules/babylonjs-loaders")) app.use("/lib/matterjs",express.static("node_modules/matter-js/build")) app.use("/lib/cannonjs",express.static("node_modules/cannon/build")) app.use("/lib/brython",express.static("node_modules/brython")) app.use("/lib/fengari",express.static("node_modules/fengari-web/dist")) app.use("/lib/qrcode",express.static("node_modules/qrcode/build")) @db = new DB "#{@app_data}/data",(db)=> for plugin in @plugins if plugin.dbLoaded? plugin.dbLoaded(db) if @PROD require('greenlock-express').init packageRoot: __dirname configDir: "./greenlock.d" maintainerEmail: "<EMAIL>" cluster: false .ready (glx)=> @httpserver = glx.httpsServer() @use_cache = true glx.serveApp app @start(app,db) else if @config.standalone @use_cache = false @httpserver = require("http").createServer(app).listen @PORT,"127.0.0.1",()=> @PORT = @httpserver.address().port @start(app,db) console.info "standalone running on port #{@PORT}" @callback() if @callback? else @httpserver = require("http").createServer(app).listen(@PORT) @use_cache = false @start(app,db) start:(app,db)-> @active_users = 0 @io = new WebSocket.Server server: @httpserver maxPayload: 40000000 @sessions = [] @io.on "connection",(socket,request)=> socket.request = request socket.remoteAddress = request.connection.remoteAddress @sessions.push new Session @,socket console.info "MAX PAYLOAD = "+@io.options.maxPayload @session_check = setInterval (()=>@sessionCheck()),10000 @content = new Content @,db,new FileStorage "#{@app_data}/files" @build_manager = new BuildManager @ @webapp = new WebApp @,app for l in @webapp.languages @content.translator.createLanguage l process.on 'SIGINT', ()=> console.log "caught INT signal" @exit() process.on 'SIGTERM', ()=> console.log "caught TERM signal" @exit() #process.on 'SIGKILL', ()=> # console.log "caught KILL signal" # @exit() @exitcheck = setInterval (()=> if fs.existsSync("exit") @exit() fs.unlinkSync("exit") if fs.existsSync("update") @webapp.concatenator.refresh() fs.unlinkSync("update") ),2000 exit:()=> if @exited process.exit(0) @httpserver.close() @stats.stop() @rate_limiter.close() @io.close() @db.close() @content.close() clearInterval @exitcheck clearInterval @session_check @exited = true setTimeout (()=>@exit()),5000 sessionCheck:()-> for s in @sessions if s? s.timeCheck() return sessionClosed:(session)-> index = @sessions.indexOf(session) if index>=0 @sessions.splice index,1 loadPlugins:(callback)-> @plugins = [] fs.readdir "../plugins",(err,files)=> files = [] if not files? funk = ()=> if files.length==0 callback() else f = files.splice(0,1)[0] @loadPlugin "../plugins/#{f}",funk funk() loadPlugin:(folder,callback)-> if fs.existsSync "#{folder}/index.js" try Plugin = require "#{folder}/index.js" p = new Plugin(@) @plugins.push p console.info "loaded plugin #{folder}" catch err console.error err callback() else console.info "plugin #{folder} has no index.js" callback() module.exports = @Server
true
compression = require "compression" express = require "express" cookieParser = require('cookie-parser') fs = require "fs" path = require "path" DB = require __dirname+"/db/db.js" FileStorage = require __dirname+"/filestorage/filestorage.js" Content = require __dirname+"/content/content.js" WebApp = require __dirname+"/webapp.js" Session = require __dirname+"/session/session.js" RateLimiter = require __dirname+"/ratelimiter.js" BuildManager = require __dirname+"/build/buildmanager.js" WebSocket = require "ws" process = require "process" class @Server constructor:(@config={},@callback)-> process.chdir __dirname @app_data = @config.app_data or ".." @mailer = # STUB sendMail:(recipient,subject,text)-> console.info "send mail to:#{recipient} subject:#{subject} text:#{text}" @stats = # STUB set:(name,value)-> max:(name,value)-> unique:(name,id)-> inc:(name)-> stop:()-> @last_backup_time = 0 if @config.realm == "production" @PORT = 443 @PROD = true else if @config.standalone @PORT = @config.port or 0 else @PORT = @config.port or 8080 @PROD = false @loadPlugins ()=> @create() create:()-> app = express() static_files = "../static" @date_started = Date.now() @rate_limiter = new RateLimiter @ app.use (req,res,next)=> if @rate_limiter.accept("request","general") and @rate_limiter.accept("request_ip",req.connection.remoteAddress) next() else res.status(500).send "" @stats.inc("http_requests") @stats.unique("ip_addresses",req.connection.remoteAddress) referrer = req.get("Referrer") if referrer? and not referrer.startsWith("http://localhost") and not referrer.startsWith("https://microstudio.io") and not referrer.startsWith("https://microstudio.dev") @stats.unique("referrer|"+referrer,req.connection.remoteAddress) app.use(compression()) app.use(cookieParser()) for plugin in @plugins if plugin.getStaticFolder? folder = plugin.getStaticFolder() app.use(express.static(folder)) app.use(express.static(static_files)) app.use("/lib/fontlib/ubuntu",express.static("node_modules/@fontsource/ubuntu")) app.use("/lib/fontlib/ubuntu-mono",express.static("node_modules/@fontsource/ubuntu-mono")) app.use("/lib/fontlib/source-sans-pro",express.static("node_modules/@fontsource/source-sans-pro")) app.use("/lib/fontlib/fontawesome",express.static("node_modules/@fortawesome/fontawesome-free")) app.use("/lib/ace",express.static("node_modules/ace-builds/src-min")) app.use("/lib/marked/marked.js",express.static("node_modules/marked/marked.min.js")) app.use("/lib/dompurify/purify.js",express.static("node_modules/dompurify/dist/purify.min.js")) app.use("/lib/jquery/jquery.js",express.static("node_modules/jquery/dist/jquery.min.js")) app.use("/lib/jquery-ui",express.static("node_modules/jquery-ui-dist")) app.use("/lib/pixijs",express.static("node_modules/pixi.js/dist/browser")) app.use("/lib/babylonjs",express.static("node_modules/babylonjs")) app.use("/lib/babylonjs",express.static("node_modules/babylonjs-loaders")) app.use("/lib/matterjs",express.static("node_modules/matter-js/build")) app.use("/lib/cannonjs",express.static("node_modules/cannon/build")) app.use("/lib/brython",express.static("node_modules/brython")) app.use("/lib/fengari",express.static("node_modules/fengari-web/dist")) app.use("/lib/qrcode",express.static("node_modules/qrcode/build")) @db = new DB "#{@app_data}/data",(db)=> for plugin in @plugins if plugin.dbLoaded? plugin.dbLoaded(db) if @PROD require('greenlock-express').init packageRoot: __dirname configDir: "./greenlock.d" maintainerEmail: "PI:EMAIL:<EMAIL>END_PI" cluster: false .ready (glx)=> @httpserver = glx.httpsServer() @use_cache = true glx.serveApp app @start(app,db) else if @config.standalone @use_cache = false @httpserver = require("http").createServer(app).listen @PORT,"127.0.0.1",()=> @PORT = @httpserver.address().port @start(app,db) console.info "standalone running on port #{@PORT}" @callback() if @callback? else @httpserver = require("http").createServer(app).listen(@PORT) @use_cache = false @start(app,db) start:(app,db)-> @active_users = 0 @io = new WebSocket.Server server: @httpserver maxPayload: 40000000 @sessions = [] @io.on "connection",(socket,request)=> socket.request = request socket.remoteAddress = request.connection.remoteAddress @sessions.push new Session @,socket console.info "MAX PAYLOAD = "+@io.options.maxPayload @session_check = setInterval (()=>@sessionCheck()),10000 @content = new Content @,db,new FileStorage "#{@app_data}/files" @build_manager = new BuildManager @ @webapp = new WebApp @,app for l in @webapp.languages @content.translator.createLanguage l process.on 'SIGINT', ()=> console.log "caught INT signal" @exit() process.on 'SIGTERM', ()=> console.log "caught TERM signal" @exit() #process.on 'SIGKILL', ()=> # console.log "caught KILL signal" # @exit() @exitcheck = setInterval (()=> if fs.existsSync("exit") @exit() fs.unlinkSync("exit") if fs.existsSync("update") @webapp.concatenator.refresh() fs.unlinkSync("update") ),2000 exit:()=> if @exited process.exit(0) @httpserver.close() @stats.stop() @rate_limiter.close() @io.close() @db.close() @content.close() clearInterval @exitcheck clearInterval @session_check @exited = true setTimeout (()=>@exit()),5000 sessionCheck:()-> for s in @sessions if s? s.timeCheck() return sessionClosed:(session)-> index = @sessions.indexOf(session) if index>=0 @sessions.splice index,1 loadPlugins:(callback)-> @plugins = [] fs.readdir "../plugins",(err,files)=> files = [] if not files? funk = ()=> if files.length==0 callback() else f = files.splice(0,1)[0] @loadPlugin "../plugins/#{f}",funk funk() loadPlugin:(folder,callback)-> if fs.existsSync "#{folder}/index.js" try Plugin = require "#{folder}/index.js" p = new Plugin(@) @plugins.push p console.info "loaded plugin #{folder}" catch err console.error err callback() else console.info "plugin #{folder} has no index.js" callback() module.exports = @Server
[ { "context": "###\nCopyright 2015, Christopher Joakim <christopher.joakim@gmail.com>\n###\n\n# grunt ; moc", "end": 38, "score": 0.9998778104782104, "start": 20, "tag": "NAME", "value": "Christopher Joakim" }, { "context": "###\nCopyright 2015, Christopher Joakim <christopher.joakim@...
sb-js/src/test/sb_js_test.coffee
cjoakim/oss
0
### Copyright 2015, Christopher Joakim <christopher.joakim@gmail.com> ### # grunt ; mocha test/sb_js_test.js assert = require("assert") should = require('should') os = require('os') StringBuffer = require('../lib/sb-js.js').StringBuffer describe 'StringBuffer', -> describe 'VERSION number is exposed by the API', -> it 'defines VERSION', -> (StringBuffer.VERSION).should.eql('0.3.0') describe 'original snake_case API', -> it "should construct an empty instance with no constructor argument", -> sb = new StringBuffer() (sb.to_string()).should.eql('') (sb.is_empty()).should.eql(true) sb.add('x') (sb.to_string()).should.eql('x') (sb.is_empty()).should.eql(false) it "should construct a populated instance with a constructor String argument", -> sb = new StringBuffer('git') (sb.is_empty()).should.eql(false) (sb.to_string()).should.eql('git') sb.add(' push') (sb.to_string()).should.eql('git push') it "should implement method 'as_lines'", -> sb = new StringBuffer("first" + os.EOL + "second") sb.newline() sb.add_line(null) sb.add_line(undefined) sb.add_line("third") (sb.as_lines()).should.eql(['first', 'second', 'third', '']) it "should optionally trim the result of to_string", -> sb1 = new StringBuffer(' git ') (sb1.to_string()).should.eql(' git ') sb2 = new StringBuffer(' git ') (sb1.to_string(true)).should.eql('git') describe 'new camelCase API', -> it "should construct an empty instance with no constructor argument", -> sb = new StringBuffer() (sb.toString()).should.eql('') (sb.isEmpty()).should.eql(true) sb.add('x') (sb.toString()).should.eql('x') (sb.isEmpty()).should.eql(false) it "should construct a populated instance with a constructor String argument", -> sb = new StringBuffer('git') (sb.isEmpty()).should.eql(false) (sb.toString()).should.eql('git') sb.add(' push') (sb.toString()).should.eql('git push') it "should implement method 'asLines'", -> sb = new StringBuffer("first" + os.EOL + "second") sb.newLine() sb.addLine(null) sb.addLine(undefined) sb.addLine("third") (sb.asLines()).should.eql(['first', 'second', 'third', '']) it "should optionally trim the result of toString", -> sb1 = new StringBuffer(' git ') (sb1.toString()).should.eql(' git ') sb2 = new StringBuffer(' git ') (sb1.toString(true)).should.eql('git')
224268
### Copyright 2015, <NAME> <<EMAIL>> ### # grunt ; mocha test/sb_js_test.js assert = require("assert") should = require('should') os = require('os') StringBuffer = require('../lib/sb-js.js').StringBuffer describe 'StringBuffer', -> describe 'VERSION number is exposed by the API', -> it 'defines VERSION', -> (StringBuffer.VERSION).should.eql('0.3.0') describe 'original snake_case API', -> it "should construct an empty instance with no constructor argument", -> sb = new StringBuffer() (sb.to_string()).should.eql('') (sb.is_empty()).should.eql(true) sb.add('x') (sb.to_string()).should.eql('x') (sb.is_empty()).should.eql(false) it "should construct a populated instance with a constructor String argument", -> sb = new StringBuffer('git') (sb.is_empty()).should.eql(false) (sb.to_string()).should.eql('git') sb.add(' push') (sb.to_string()).should.eql('git push') it "should implement method 'as_lines'", -> sb = new StringBuffer("first" + os.EOL + "second") sb.newline() sb.add_line(null) sb.add_line(undefined) sb.add_line("third") (sb.as_lines()).should.eql(['first', 'second', 'third', '']) it "should optionally trim the result of to_string", -> sb1 = new StringBuffer(' git ') (sb1.to_string()).should.eql(' git ') sb2 = new StringBuffer(' git ') (sb1.to_string(true)).should.eql('git') describe 'new camelCase API', -> it "should construct an empty instance with no constructor argument", -> sb = new StringBuffer() (sb.toString()).should.eql('') (sb.isEmpty()).should.eql(true) sb.add('x') (sb.toString()).should.eql('x') (sb.isEmpty()).should.eql(false) it "should construct a populated instance with a constructor String argument", -> sb = new StringBuffer('git') (sb.isEmpty()).should.eql(false) (sb.toString()).should.eql('git') sb.add(' push') (sb.toString()).should.eql('git push') it "should implement method 'asLines'", -> sb = new StringBuffer("first" + os.EOL + "second") sb.newLine() sb.addLine(null) sb.addLine(undefined) sb.addLine("third") (sb.asLines()).should.eql(['first', 'second', 'third', '']) it "should optionally trim the result of toString", -> sb1 = new StringBuffer(' git ') (sb1.toString()).should.eql(' git ') sb2 = new StringBuffer(' git ') (sb1.toString(true)).should.eql('git')
true
### Copyright 2015, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### # grunt ; mocha test/sb_js_test.js assert = require("assert") should = require('should') os = require('os') StringBuffer = require('../lib/sb-js.js').StringBuffer describe 'StringBuffer', -> describe 'VERSION number is exposed by the API', -> it 'defines VERSION', -> (StringBuffer.VERSION).should.eql('0.3.0') describe 'original snake_case API', -> it "should construct an empty instance with no constructor argument", -> sb = new StringBuffer() (sb.to_string()).should.eql('') (sb.is_empty()).should.eql(true) sb.add('x') (sb.to_string()).should.eql('x') (sb.is_empty()).should.eql(false) it "should construct a populated instance with a constructor String argument", -> sb = new StringBuffer('git') (sb.is_empty()).should.eql(false) (sb.to_string()).should.eql('git') sb.add(' push') (sb.to_string()).should.eql('git push') it "should implement method 'as_lines'", -> sb = new StringBuffer("first" + os.EOL + "second") sb.newline() sb.add_line(null) sb.add_line(undefined) sb.add_line("third") (sb.as_lines()).should.eql(['first', 'second', 'third', '']) it "should optionally trim the result of to_string", -> sb1 = new StringBuffer(' git ') (sb1.to_string()).should.eql(' git ') sb2 = new StringBuffer(' git ') (sb1.to_string(true)).should.eql('git') describe 'new camelCase API', -> it "should construct an empty instance with no constructor argument", -> sb = new StringBuffer() (sb.toString()).should.eql('') (sb.isEmpty()).should.eql(true) sb.add('x') (sb.toString()).should.eql('x') (sb.isEmpty()).should.eql(false) it "should construct a populated instance with a constructor String argument", -> sb = new StringBuffer('git') (sb.isEmpty()).should.eql(false) (sb.toString()).should.eql('git') sb.add(' push') (sb.toString()).should.eql('git push') it "should implement method 'asLines'", -> sb = new StringBuffer("first" + os.EOL + "second") sb.newLine() sb.addLine(null) sb.addLine(undefined) sb.addLine("third") (sb.asLines()).should.eql(['first', 'second', 'third', '']) it "should optionally trim the result of toString", -> sb1 = new StringBuffer(' git ') (sb1.toString()).should.eql(' git ') sb2 = new StringBuffer(' git ') (sb1.toString(true)).should.eql('git')
[ { "context": "tract_username: (node_name) -> @extract_property 'username', node_name\n\textract_password: (node_name) -> @ex", "end": 2022, "score": 0.900924801826477, "start": 2014, "tag": "USERNAME", "value": "username" }, { "context": "_port < 1\n\t\telse\n\t\t\tssh_port = 22\n\t\...
src/provider_amazon.coffee
websecurify/node-vortex
49
fs = require 'fs' async = require 'async' aws_sdk = require 'aws-sdk' logsmith = require 'logsmith' path_extra = require 'path-extra' portchecker = require 'portchecker' # --- exports.Provider = class ### This class exposes Amazon as a provider to Vortex. ### constructor: (@manifest) -> ### The provider accepts a manifest as a parameter by specification. ### aws_sdk.config.update @extract_client_options() get_node: (node_name) -> ### This method returns a node by looking up its name. It throws an error if the node is not found. ### return @manifest.nodes[node_name] if @manifest.nodes? and @manifest.nodes[node_name]? throw new Error "node #{node_name} does not exist" extract_property: (property_name, node_name) -> ### Extracts a property by looking into a node and upper layers of the manifest. ### try node = @get_node node_name catch e node = null return node.amazon[property_name] if node?.amazon?[property_name]? return @manifest.amazon[property_name] if @manifest.amazon?[property_name]? return null # # Helper functions for extracting various properties. # extract_access_key_id: (node_name) -> @extract_property 'accessKeyId', node_name extract_secret_access_key: (node_name) -> @extract_property 'secretAccessKey', node_name extract_region: (node_name) -> @extract_property 'region', node_name extract_max_retries: (node_name) -> @extract_property 'maxRetries', node_name extract_image_id: (node_name) -> @extract_property 'imageId', node_name extract_instance_type: (node_name) -> @extract_property 'instanceType', node_name extract_key_name: (node_name) -> @extract_property 'keyName', node_name extract_security_groups: (node_name) -> @extract_property 'securityGroups', node_name extract_user_data: (node_name) -> @extract_property 'userData', node_name extract_disable_api_termination: (node_name) -> @extract_property 'disableApiTermination', node_name extract_username: (node_name) -> @extract_property 'username', node_name extract_password: (node_name) -> @extract_property 'password', node_name extract_private_key: (node_name) -> @extract_property 'privateKey', node_name extract_passphrase: (node_name) -> @extract_property 'passphrase', node_name extract_ssh_port: (node_name) -> @extract_property 'sshPort', node_name # # # extract_namespace: (node_name) -> ### Extracts a namespace by looking it up in the node itself and upper layers of the manifest ### try node = @get_node node_name catch node = null return node.namespace if node?.namespace? return @manifest.namespace if @manifest.namespace? extract_client_options: (node_name) -> ### Extracts options related to the AWS client. ### access_key_id = @extract_access_key_id node_name secret_access_key = @extract_secret_access_key node_name region = @extract_region node_name max_retries = @extract_max_retries node_name options = {} options.accessKeyId = access_key_id if access_key_id options.secretAccessKey = secret_access_key if secret_access_key options.region = region if region options.maxRetries = max_retries if max_retries return options extract_instance_options: (node_name) -> ### Extracts options related to AWS instances. ### image_id = this.extract_image_id node_name instance_type = this.extract_instance_type node_name key_name = this.extract_key_name node_name security_groups = this.extract_security_groups node_name user_data = this.extract_user_data node_name disable_api_termination = this.extract_disable_api_termination node_name options = {} options.ImageId = image_id if image_id options.InstanceType = instance_type if instance_type options.KeyName = key_name if key_name options.SecurityGroups = security_groups if security_groups options.UserData = user_data if user_data options.DisableApiTermination = disable_api_termination if disable_api_termination return options get_client: (node_name) -> ### Obtain a client for EC2. ### return new aws_sdk.EC2 @extract_client_options node_name create_error: (error, node_name) -> ### Creates a friendlier error message. ### if error.code == 'NetworkingError' return error else tokens = error.toString().split(':') type = tokens[0] message = tokens[1].trim() parts = message.split('.') message = parts.shift().toLowerCase().trim() if node_name message = "#{message} for node #{node_name}" if parts.length > 0 message = "#{message} (#{parts.join('.').trim()})" message = message.replace /\s'(\w+)'\s/, (match, group) -> param = group.toLowerCase() switch param when 'accesskeyid' then param = 'accessKeyId' when 'secretaccesskey' then param = 'secretAccessKey' when 'region' then param = 'region' when 'maxretries' then param = 'maxRetries' when 'imageid' then param = 'imageId' when 'instancetype' then param = 'instanceType' when 'keyname' then param = 'keyName' when 'securitygroups' then param = 'securityGroups' when 'userdata' then param = 'userData' when 'disableapitermination' then param = 'disableApiTermination' return ' "' + param + '" ' message = message[0] + message.substring 1, message.length return new Error message bootstrap: (node_name, callback) -> ### Provider-specific method for bootstrapping a node. ### # # First we verify the status of the node to check if the state is correct. # verify_status = (callback) => @status node_name, (err, state, address) -> return callback err if err return callback new Error "node #{node_name} is not ready" if state != 'running' return callback null # # Next we obtain shell spec. # obtain_shell_spec = (callback) => @shell_spec node_name, (err, spec) -> return callback err if err return callback null, spec # # Next we check the exposed files and folders. # prepare_exposed = (spec, callback) => try node = @get_node node_name catch e node = null return callback null if not node?.expose? handle_exposure = (exposure, callback) => source_path = path_extra.resolve path_extra.dirname(@manifest.meta.location), exposure.src fs.stat source_path, (err, stats) => return callback new Error "cannot expose #{exposure.src} because it does not exist" if err return callback null async.eachSeries ({src: src, dst: dst} for src, dst of node.expose), handle_exposure, callback # # Action on the tasks. # async.waterfall [verify_status, obtain_shell_spec, prepare_exposed], (err, state, address) -> return callback err if err return callback null status: (node_name, callback) -> ### Provider-specific method for checking the status of a node. ### try client = @get_client node_name catch e return callback @create_error e, node_name options = Filters: [ {Name: 'tag:vortex-node-name', Values: [node_name]} {Name: 'tag:vortex-node-namespace', Values: [this.extract_namespace(node_name)]} ] logsmith.debug 'describe instances with options', options client.describeInstances options, (err, result) => return callback @create_error err, node_name if err instances = [] for reservation in result.Reservations for instance in reservation.Instances instances.push { id: instance.InstanceId state: instance.State.Name address: instance.PublicDnsName } return callback null, 'stopped' if instances.length == 0 logsmith.debug 'discovered instances', instances selected_instance = instances[instances.length - 1] return callback new Error "could not obtain instance for node #{node_name}" if not selected_instance logsmith.debug 'selected instance', selected_instance for instance in instances if instance.state not in ['shutting-down', 'terminated', 'stopping', 'stopped'] and selected_instance != instance logsmith.warn "duplicate node #{node_name} with instance id #{instance.id} detected" state = switch selected_instance.state when 'pending' then 'booting' when 'running' then 'running' when 'stopped' then 'stopped' when 'stopping' then 'halting' when 'terminated' then 'stopped' when 'shutting-down' then 'halting' else null return callback new Error "undefined state for node #{node_name}" if not state logsmith.debug "node #{node_name} with instance id #{selected_instance.id} has state #{state}" address = selected_instance.address if not address state = 'booting' if state != 'running' address = null return callback null, state, address, selected_instance.id boot: (node_name, callback) -> ### Provider-specific method for booting a node. ### try client = @get_client node_name catch e return callback @create_error e, node_name # # First we verify the status of the node to check if the state is correct. # verify_status = (callback) => @status node_name, (err, state, address) -> return callback err if err return callback new Error "node #{node_name} is already booting" if state == 'booting' return callback new Error "node #{node_name} is already running" if state == 'running' return callback new Error "node #{node_name} is halting" if state == 'halting' return callback null # # Next we run the instance. # run_instance = (callback) => options = @extract_instance_options node_name options.MinCount = 1 options.MaxCount = 1 logsmith.debug 'run instances with options', options client.runInstances options, (err, result) => return callback @create_error err, node_name if err instances = [] for instance in result.Instances instances.push { id: instance.InstanceId } return callback new Error "no instances run for node #{node_name}" if instances.length == 0 logsmith.debug 'ran instances', instances selected_instance = instances[instances.length - 1] return callback new Error "could not create instance for node #{node_name}" if not selected_instance logsmith.debug 'selected instance', selected_instance for instance in instances if selected_instance != instance logsmith.warn "duplicate node #{node_name} with instance id #{instance_id} detected" return callback null, selected_instance.id # # Finally we unmap any tags on the instance. # map_tags = (instance_id, callback) => options = Resources: [instance_id] Tags: [ {Key: 'vortex-node-name', Value: node_name} {Key: 'vortex-node-namespace', Value: @extract_namespace node_name} ] logsmith.debug 'create tags with options', options client.createTags options, (err, result) => return callback @create_error err, node_name if err return callback null, instance_id # # Action on the tasks. # async.waterfall [verify_status, run_instance, map_tags], (err) => return callback err if err return @status node_name, callback halt: (node_name, callback) -> ### Provider-specific method for halting a node. ### try client = @get_client node_name catch e return callback @create_error e, node_name # # First we verify the status of the node to check if the state is correct. # verify_status = (callback) => @status node_name, (err, state, address, instance_id) -> return callback err if err return callback new Error "#{node_name} is already halting" if state == 'halting' return callback new Error "#{node_name} is already stopped" if state == 'stopped' return callback null, instance_id # # Next we terminate the instance. # terminate_instance = (instance_id, callback) => options = InstanceIds: [instance_id] logsmith.debug 'terminate instances with options', options client.terminateInstances options, (err, result) => return callback @create_error err, node_name if err return callback null, instance_id # # Finally we unmap any tags on the instance. # unmap_tags = (instance_id, callback) => options = Resources: [instance_id] Tags: [ {Key: 'vortex-node-name', Value: node_name} {Key: 'vortex-node-namespace', Value: @extract_namespace node_name} ] logsmith.debug 'delete tags with options', options client.deleteTags options, (err, result) => return callback @create_error err, node_name if err return callback null, instance_id # # Action on the tasks. # async.waterfall [verify_status, terminate_instance, unmap_tags], (err) => return callback err if err return @status node_name, callback pause: (node_name, callback) -> ### Provider-specific method for pausing a machine. ### return callback new Error "cannot pause node #{node_name} due to pause not implemented" resume: (node_name, callback) -> ### Provider-specific method for resuming a machine. ### return callback new Error "cannot resume node #{node_name} due to resume not implemented" shell_spec: (node_name, callback) -> ### Provider-specific method for obtaining a shell spec from a node. ### password = @extract_password node_name private_key = @extract_private_key node_name return callback new Error "no password or privateKey provided for node #{node_name}" if not password and not private_key ssh_port = @extract_ssh_port node_name if ssh_port ssh_port = parseInt ssh_port, 10 return callback new Error "ssh port for node #{node_name} is incorrect" if isNaN ssh_port or ssh_port < 1 else ssh_port = 22 username = @extract_username node_name if not username username = 'vortex' passphrase = @extract_passphrase node_name # # First we obtain the node status by looking for the address and to check if the state is correct. # obtain_status = (callback) => @status node_name, (err, state, address) -> return callback err if err return callback new Error "node #{node_name} is halting" if state == 'halting' return callback new Error "node #{node_name} is stopped" if state == 'stopped' return callback new Error "cannot find network address for node #{node_name}" if not address return callback null, address # # Next we continiusly check if the ssh port is open. # ensure_port = (address, callback) -> portchecker.isOpen ssh_port, address, (is_open) -> return callback null, address if is_open callee = arguments.callee milliseconds = 10000 timeout = () -> portchecker.isOpen ssh_port, address, callee logsmith.debug "repeat check for ssh port open for node #{node_name} in #{milliseconds} milliseconds" setTimeout timeout, milliseconds # # Finally we build the spec and send it off. # build_spec = (address, callback) -> parts = [] parts.push 'ssh://' parts.push encodeURIComponent username parts.push ':' + encodeURIComponent password if password parts.push '@' parts.push address parts.push ':' + ssh_port parts.push ';privateKey=' + encodeURIComponent private_key if private_key parts.push ';passphrase=' + encodeURIComponent passphrase if passphrase spec = parts.join '' spec_options = username: username password: password host: address port: ssh_port privateKey: private_key passphrase: passphrase return callback null, spec, spec_options # # Action on the tasks. # async.waterfall [obtain_status, ensure_port, build_spec], callback
185455
fs = require 'fs' async = require 'async' aws_sdk = require 'aws-sdk' logsmith = require 'logsmith' path_extra = require 'path-extra' portchecker = require 'portchecker' # --- exports.Provider = class ### This class exposes Amazon as a provider to Vortex. ### constructor: (@manifest) -> ### The provider accepts a manifest as a parameter by specification. ### aws_sdk.config.update @extract_client_options() get_node: (node_name) -> ### This method returns a node by looking up its name. It throws an error if the node is not found. ### return @manifest.nodes[node_name] if @manifest.nodes? and @manifest.nodes[node_name]? throw new Error "node #{node_name} does not exist" extract_property: (property_name, node_name) -> ### Extracts a property by looking into a node and upper layers of the manifest. ### try node = @get_node node_name catch e node = null return node.amazon[property_name] if node?.amazon?[property_name]? return @manifest.amazon[property_name] if @manifest.amazon?[property_name]? return null # # Helper functions for extracting various properties. # extract_access_key_id: (node_name) -> @extract_property 'accessKeyId', node_name extract_secret_access_key: (node_name) -> @extract_property 'secretAccessKey', node_name extract_region: (node_name) -> @extract_property 'region', node_name extract_max_retries: (node_name) -> @extract_property 'maxRetries', node_name extract_image_id: (node_name) -> @extract_property 'imageId', node_name extract_instance_type: (node_name) -> @extract_property 'instanceType', node_name extract_key_name: (node_name) -> @extract_property 'keyName', node_name extract_security_groups: (node_name) -> @extract_property 'securityGroups', node_name extract_user_data: (node_name) -> @extract_property 'userData', node_name extract_disable_api_termination: (node_name) -> @extract_property 'disableApiTermination', node_name extract_username: (node_name) -> @extract_property 'username', node_name extract_password: (node_name) -> @extract_property 'password', node_name extract_private_key: (node_name) -> @extract_property 'privateKey', node_name extract_passphrase: (node_name) -> @extract_property 'passphrase', node_name extract_ssh_port: (node_name) -> @extract_property 'sshPort', node_name # # # extract_namespace: (node_name) -> ### Extracts a namespace by looking it up in the node itself and upper layers of the manifest ### try node = @get_node node_name catch node = null return node.namespace if node?.namespace? return @manifest.namespace if @manifest.namespace? extract_client_options: (node_name) -> ### Extracts options related to the AWS client. ### access_key_id = @extract_access_key_id node_name secret_access_key = @extract_secret_access_key node_name region = @extract_region node_name max_retries = @extract_max_retries node_name options = {} options.accessKeyId = access_key_id if access_key_id options.secretAccessKey = secret_access_key if secret_access_key options.region = region if region options.maxRetries = max_retries if max_retries return options extract_instance_options: (node_name) -> ### Extracts options related to AWS instances. ### image_id = this.extract_image_id node_name instance_type = this.extract_instance_type node_name key_name = this.extract_key_name node_name security_groups = this.extract_security_groups node_name user_data = this.extract_user_data node_name disable_api_termination = this.extract_disable_api_termination node_name options = {} options.ImageId = image_id if image_id options.InstanceType = instance_type if instance_type options.KeyName = key_name if key_name options.SecurityGroups = security_groups if security_groups options.UserData = user_data if user_data options.DisableApiTermination = disable_api_termination if disable_api_termination return options get_client: (node_name) -> ### Obtain a client for EC2. ### return new aws_sdk.EC2 @extract_client_options node_name create_error: (error, node_name) -> ### Creates a friendlier error message. ### if error.code == 'NetworkingError' return error else tokens = error.toString().split(':') type = tokens[0] message = tokens[1].trim() parts = message.split('.') message = parts.shift().toLowerCase().trim() if node_name message = "#{message} for node #{node_name}" if parts.length > 0 message = "#{message} (#{parts.join('.').trim()})" message = message.replace /\s'(\w+)'\s/, (match, group) -> param = group.toLowerCase() switch param when 'accesskeyid' then param = 'accessKeyId' when 'secretaccesskey' then param = 'secretAccessKey' when 'region' then param = 'region' when 'maxretries' then param = 'maxRetries' when 'imageid' then param = 'imageId' when 'instancetype' then param = 'instanceType' when 'keyname' then param = 'keyName' when 'securitygroups' then param = 'securityGroups' when 'userdata' then param = 'userData' when 'disableapitermination' then param = 'disableApiTermination' return ' "' + param + '" ' message = message[0] + message.substring 1, message.length return new Error message bootstrap: (node_name, callback) -> ### Provider-specific method for bootstrapping a node. ### # # First we verify the status of the node to check if the state is correct. # verify_status = (callback) => @status node_name, (err, state, address) -> return callback err if err return callback new Error "node #{node_name} is not ready" if state != 'running' return callback null # # Next we obtain shell spec. # obtain_shell_spec = (callback) => @shell_spec node_name, (err, spec) -> return callback err if err return callback null, spec # # Next we check the exposed files and folders. # prepare_exposed = (spec, callback) => try node = @get_node node_name catch e node = null return callback null if not node?.expose? handle_exposure = (exposure, callback) => source_path = path_extra.resolve path_extra.dirname(@manifest.meta.location), exposure.src fs.stat source_path, (err, stats) => return callback new Error "cannot expose #{exposure.src} because it does not exist" if err return callback null async.eachSeries ({src: src, dst: dst} for src, dst of node.expose), handle_exposure, callback # # Action on the tasks. # async.waterfall [verify_status, obtain_shell_spec, prepare_exposed], (err, state, address) -> return callback err if err return callback null status: (node_name, callback) -> ### Provider-specific method for checking the status of a node. ### try client = @get_client node_name catch e return callback @create_error e, node_name options = Filters: [ {Name: 'tag:vortex-node-name', Values: [node_name]} {Name: 'tag:vortex-node-namespace', Values: [this.extract_namespace(node_name)]} ] logsmith.debug 'describe instances with options', options client.describeInstances options, (err, result) => return callback @create_error err, node_name if err instances = [] for reservation in result.Reservations for instance in reservation.Instances instances.push { id: instance.InstanceId state: instance.State.Name address: instance.PublicDnsName } return callback null, 'stopped' if instances.length == 0 logsmith.debug 'discovered instances', instances selected_instance = instances[instances.length - 1] return callback new Error "could not obtain instance for node #{node_name}" if not selected_instance logsmith.debug 'selected instance', selected_instance for instance in instances if instance.state not in ['shutting-down', 'terminated', 'stopping', 'stopped'] and selected_instance != instance logsmith.warn "duplicate node #{node_name} with instance id #{instance.id} detected" state = switch selected_instance.state when 'pending' then 'booting' when 'running' then 'running' when 'stopped' then 'stopped' when 'stopping' then 'halting' when 'terminated' then 'stopped' when 'shutting-down' then 'halting' else null return callback new Error "undefined state for node #{node_name}" if not state logsmith.debug "node #{node_name} with instance id #{selected_instance.id} has state #{state}" address = selected_instance.address if not address state = 'booting' if state != 'running' address = null return callback null, state, address, selected_instance.id boot: (node_name, callback) -> ### Provider-specific method for booting a node. ### try client = @get_client node_name catch e return callback @create_error e, node_name # # First we verify the status of the node to check if the state is correct. # verify_status = (callback) => @status node_name, (err, state, address) -> return callback err if err return callback new Error "node #{node_name} is already booting" if state == 'booting' return callback new Error "node #{node_name} is already running" if state == 'running' return callback new Error "node #{node_name} is halting" if state == 'halting' return callback null # # Next we run the instance. # run_instance = (callback) => options = @extract_instance_options node_name options.MinCount = 1 options.MaxCount = 1 logsmith.debug 'run instances with options', options client.runInstances options, (err, result) => return callback @create_error err, node_name if err instances = [] for instance in result.Instances instances.push { id: instance.InstanceId } return callback new Error "no instances run for node #{node_name}" if instances.length == 0 logsmith.debug 'ran instances', instances selected_instance = instances[instances.length - 1] return callback new Error "could not create instance for node #{node_name}" if not selected_instance logsmith.debug 'selected instance', selected_instance for instance in instances if selected_instance != instance logsmith.warn "duplicate node #{node_name} with instance id #{instance_id} detected" return callback null, selected_instance.id # # Finally we unmap any tags on the instance. # map_tags = (instance_id, callback) => options = Resources: [instance_id] Tags: [ {Key: 'vortex-node-name', Value: node_name} {Key: 'vortex-node-namespace', Value: @extract_namespace node_name} ] logsmith.debug 'create tags with options', options client.createTags options, (err, result) => return callback @create_error err, node_name if err return callback null, instance_id # # Action on the tasks. # async.waterfall [verify_status, run_instance, map_tags], (err) => return callback err if err return @status node_name, callback halt: (node_name, callback) -> ### Provider-specific method for halting a node. ### try client = @get_client node_name catch e return callback @create_error e, node_name # # First we verify the status of the node to check if the state is correct. # verify_status = (callback) => @status node_name, (err, state, address, instance_id) -> return callback err if err return callback new Error "#{node_name} is already halting" if state == 'halting' return callback new Error "#{node_name} is already stopped" if state == 'stopped' return callback null, instance_id # # Next we terminate the instance. # terminate_instance = (instance_id, callback) => options = InstanceIds: [instance_id] logsmith.debug 'terminate instances with options', options client.terminateInstances options, (err, result) => return callback @create_error err, node_name if err return callback null, instance_id # # Finally we unmap any tags on the instance. # unmap_tags = (instance_id, callback) => options = Resources: [instance_id] Tags: [ {Key: 'vortex-node-name', Value: node_name} {Key: 'vortex-node-namespace', Value: @extract_namespace node_name} ] logsmith.debug 'delete tags with options', options client.deleteTags options, (err, result) => return callback @create_error err, node_name if err return callback null, instance_id # # Action on the tasks. # async.waterfall [verify_status, terminate_instance, unmap_tags], (err) => return callback err if err return @status node_name, callback pause: (node_name, callback) -> ### Provider-specific method for pausing a machine. ### return callback new Error "cannot pause node #{node_name} due to pause not implemented" resume: (node_name, callback) -> ### Provider-specific method for resuming a machine. ### return callback new Error "cannot resume node #{node_name} due to resume not implemented" shell_spec: (node_name, callback) -> ### Provider-specific method for obtaining a shell spec from a node. ### password = @extract_password node_name private_key = @extract_private_key node_name return callback new Error "no password or privateKey provided for node #{node_name}" if not password and not private_key ssh_port = @extract_ssh_port node_name if ssh_port ssh_port = parseInt ssh_port, 10 return callback new Error "ssh port for node #{node_name} is incorrect" if isNaN ssh_port or ssh_port < 1 else ssh_port = 22 username = @extract_username node_name if not username username = 'vortex' passphrase = @extract_passphrase node_name # # First we obtain the node status by looking for the address and to check if the state is correct. # obtain_status = (callback) => @status node_name, (err, state, address) -> return callback err if err return callback new Error "node #{node_name} is halting" if state == 'halting' return callback new Error "node #{node_name} is stopped" if state == 'stopped' return callback new Error "cannot find network address for node #{node_name}" if not address return callback null, address # # Next we continiusly check if the ssh port is open. # ensure_port = (address, callback) -> portchecker.isOpen ssh_port, address, (is_open) -> return callback null, address if is_open callee = arguments.callee milliseconds = 10000 timeout = () -> portchecker.isOpen ssh_port, address, callee logsmith.debug "repeat check for ssh port open for node #{node_name} in #{milliseconds} milliseconds" setTimeout timeout, milliseconds # # Finally we build the spec and send it off. # build_spec = (address, callback) -> parts = [] parts.push 'ssh://' parts.push encodeURIComponent username parts.push ':' + encodeURIComponent password if password parts.push '@' parts.push address parts.push ':' + ssh_port parts.push ';privateKey=' + encodeURIComponent private_key if private_key parts.push ';passphrase=' + encodeURIComponent passphrase if passphrase spec = parts.join '' spec_options = username: username password: <PASSWORD> host: address port: ssh_port privateKey: private_key passphrase: <PASSWORD> return callback null, spec, spec_options # # Action on the tasks. # async.waterfall [obtain_status, ensure_port, build_spec], callback
true
fs = require 'fs' async = require 'async' aws_sdk = require 'aws-sdk' logsmith = require 'logsmith' path_extra = require 'path-extra' portchecker = require 'portchecker' # --- exports.Provider = class ### This class exposes Amazon as a provider to Vortex. ### constructor: (@manifest) -> ### The provider accepts a manifest as a parameter by specification. ### aws_sdk.config.update @extract_client_options() get_node: (node_name) -> ### This method returns a node by looking up its name. It throws an error if the node is not found. ### return @manifest.nodes[node_name] if @manifest.nodes? and @manifest.nodes[node_name]? throw new Error "node #{node_name} does not exist" extract_property: (property_name, node_name) -> ### Extracts a property by looking into a node and upper layers of the manifest. ### try node = @get_node node_name catch e node = null return node.amazon[property_name] if node?.amazon?[property_name]? return @manifest.amazon[property_name] if @manifest.amazon?[property_name]? return null # # Helper functions for extracting various properties. # extract_access_key_id: (node_name) -> @extract_property 'accessKeyId', node_name extract_secret_access_key: (node_name) -> @extract_property 'secretAccessKey', node_name extract_region: (node_name) -> @extract_property 'region', node_name extract_max_retries: (node_name) -> @extract_property 'maxRetries', node_name extract_image_id: (node_name) -> @extract_property 'imageId', node_name extract_instance_type: (node_name) -> @extract_property 'instanceType', node_name extract_key_name: (node_name) -> @extract_property 'keyName', node_name extract_security_groups: (node_name) -> @extract_property 'securityGroups', node_name extract_user_data: (node_name) -> @extract_property 'userData', node_name extract_disable_api_termination: (node_name) -> @extract_property 'disableApiTermination', node_name extract_username: (node_name) -> @extract_property 'username', node_name extract_password: (node_name) -> @extract_property 'password', node_name extract_private_key: (node_name) -> @extract_property 'privateKey', node_name extract_passphrase: (node_name) -> @extract_property 'passphrase', node_name extract_ssh_port: (node_name) -> @extract_property 'sshPort', node_name # # # extract_namespace: (node_name) -> ### Extracts a namespace by looking it up in the node itself and upper layers of the manifest ### try node = @get_node node_name catch node = null return node.namespace if node?.namespace? return @manifest.namespace if @manifest.namespace? extract_client_options: (node_name) -> ### Extracts options related to the AWS client. ### access_key_id = @extract_access_key_id node_name secret_access_key = @extract_secret_access_key node_name region = @extract_region node_name max_retries = @extract_max_retries node_name options = {} options.accessKeyId = access_key_id if access_key_id options.secretAccessKey = secret_access_key if secret_access_key options.region = region if region options.maxRetries = max_retries if max_retries return options extract_instance_options: (node_name) -> ### Extracts options related to AWS instances. ### image_id = this.extract_image_id node_name instance_type = this.extract_instance_type node_name key_name = this.extract_key_name node_name security_groups = this.extract_security_groups node_name user_data = this.extract_user_data node_name disable_api_termination = this.extract_disable_api_termination node_name options = {} options.ImageId = image_id if image_id options.InstanceType = instance_type if instance_type options.KeyName = key_name if key_name options.SecurityGroups = security_groups if security_groups options.UserData = user_data if user_data options.DisableApiTermination = disable_api_termination if disable_api_termination return options get_client: (node_name) -> ### Obtain a client for EC2. ### return new aws_sdk.EC2 @extract_client_options node_name create_error: (error, node_name) -> ### Creates a friendlier error message. ### if error.code == 'NetworkingError' return error else tokens = error.toString().split(':') type = tokens[0] message = tokens[1].trim() parts = message.split('.') message = parts.shift().toLowerCase().trim() if node_name message = "#{message} for node #{node_name}" if parts.length > 0 message = "#{message} (#{parts.join('.').trim()})" message = message.replace /\s'(\w+)'\s/, (match, group) -> param = group.toLowerCase() switch param when 'accesskeyid' then param = 'accessKeyId' when 'secretaccesskey' then param = 'secretAccessKey' when 'region' then param = 'region' when 'maxretries' then param = 'maxRetries' when 'imageid' then param = 'imageId' when 'instancetype' then param = 'instanceType' when 'keyname' then param = 'keyName' when 'securitygroups' then param = 'securityGroups' when 'userdata' then param = 'userData' when 'disableapitermination' then param = 'disableApiTermination' return ' "' + param + '" ' message = message[0] + message.substring 1, message.length return new Error message bootstrap: (node_name, callback) -> ### Provider-specific method for bootstrapping a node. ### # # First we verify the status of the node to check if the state is correct. # verify_status = (callback) => @status node_name, (err, state, address) -> return callback err if err return callback new Error "node #{node_name} is not ready" if state != 'running' return callback null # # Next we obtain shell spec. # obtain_shell_spec = (callback) => @shell_spec node_name, (err, spec) -> return callback err if err return callback null, spec # # Next we check the exposed files and folders. # prepare_exposed = (spec, callback) => try node = @get_node node_name catch e node = null return callback null if not node?.expose? handle_exposure = (exposure, callback) => source_path = path_extra.resolve path_extra.dirname(@manifest.meta.location), exposure.src fs.stat source_path, (err, stats) => return callback new Error "cannot expose #{exposure.src} because it does not exist" if err return callback null async.eachSeries ({src: src, dst: dst} for src, dst of node.expose), handle_exposure, callback # # Action on the tasks. # async.waterfall [verify_status, obtain_shell_spec, prepare_exposed], (err, state, address) -> return callback err if err return callback null status: (node_name, callback) -> ### Provider-specific method for checking the status of a node. ### try client = @get_client node_name catch e return callback @create_error e, node_name options = Filters: [ {Name: 'tag:vortex-node-name', Values: [node_name]} {Name: 'tag:vortex-node-namespace', Values: [this.extract_namespace(node_name)]} ] logsmith.debug 'describe instances with options', options client.describeInstances options, (err, result) => return callback @create_error err, node_name if err instances = [] for reservation in result.Reservations for instance in reservation.Instances instances.push { id: instance.InstanceId state: instance.State.Name address: instance.PublicDnsName } return callback null, 'stopped' if instances.length == 0 logsmith.debug 'discovered instances', instances selected_instance = instances[instances.length - 1] return callback new Error "could not obtain instance for node #{node_name}" if not selected_instance logsmith.debug 'selected instance', selected_instance for instance in instances if instance.state not in ['shutting-down', 'terminated', 'stopping', 'stopped'] and selected_instance != instance logsmith.warn "duplicate node #{node_name} with instance id #{instance.id} detected" state = switch selected_instance.state when 'pending' then 'booting' when 'running' then 'running' when 'stopped' then 'stopped' when 'stopping' then 'halting' when 'terminated' then 'stopped' when 'shutting-down' then 'halting' else null return callback new Error "undefined state for node #{node_name}" if not state logsmith.debug "node #{node_name} with instance id #{selected_instance.id} has state #{state}" address = selected_instance.address if not address state = 'booting' if state != 'running' address = null return callback null, state, address, selected_instance.id boot: (node_name, callback) -> ### Provider-specific method for booting a node. ### try client = @get_client node_name catch e return callback @create_error e, node_name # # First we verify the status of the node to check if the state is correct. # verify_status = (callback) => @status node_name, (err, state, address) -> return callback err if err return callback new Error "node #{node_name} is already booting" if state == 'booting' return callback new Error "node #{node_name} is already running" if state == 'running' return callback new Error "node #{node_name} is halting" if state == 'halting' return callback null # # Next we run the instance. # run_instance = (callback) => options = @extract_instance_options node_name options.MinCount = 1 options.MaxCount = 1 logsmith.debug 'run instances with options', options client.runInstances options, (err, result) => return callback @create_error err, node_name if err instances = [] for instance in result.Instances instances.push { id: instance.InstanceId } return callback new Error "no instances run for node #{node_name}" if instances.length == 0 logsmith.debug 'ran instances', instances selected_instance = instances[instances.length - 1] return callback new Error "could not create instance for node #{node_name}" if not selected_instance logsmith.debug 'selected instance', selected_instance for instance in instances if selected_instance != instance logsmith.warn "duplicate node #{node_name} with instance id #{instance_id} detected" return callback null, selected_instance.id # # Finally we unmap any tags on the instance. # map_tags = (instance_id, callback) => options = Resources: [instance_id] Tags: [ {Key: 'vortex-node-name', Value: node_name} {Key: 'vortex-node-namespace', Value: @extract_namespace node_name} ] logsmith.debug 'create tags with options', options client.createTags options, (err, result) => return callback @create_error err, node_name if err return callback null, instance_id # # Action on the tasks. # async.waterfall [verify_status, run_instance, map_tags], (err) => return callback err if err return @status node_name, callback halt: (node_name, callback) -> ### Provider-specific method for halting a node. ### try client = @get_client node_name catch e return callback @create_error e, node_name # # First we verify the status of the node to check if the state is correct. # verify_status = (callback) => @status node_name, (err, state, address, instance_id) -> return callback err if err return callback new Error "#{node_name} is already halting" if state == 'halting' return callback new Error "#{node_name} is already stopped" if state == 'stopped' return callback null, instance_id # # Next we terminate the instance. # terminate_instance = (instance_id, callback) => options = InstanceIds: [instance_id] logsmith.debug 'terminate instances with options', options client.terminateInstances options, (err, result) => return callback @create_error err, node_name if err return callback null, instance_id # # Finally we unmap any tags on the instance. # unmap_tags = (instance_id, callback) => options = Resources: [instance_id] Tags: [ {Key: 'vortex-node-name', Value: node_name} {Key: 'vortex-node-namespace', Value: @extract_namespace node_name} ] logsmith.debug 'delete tags with options', options client.deleteTags options, (err, result) => return callback @create_error err, node_name if err return callback null, instance_id # # Action on the tasks. # async.waterfall [verify_status, terminate_instance, unmap_tags], (err) => return callback err if err return @status node_name, callback pause: (node_name, callback) -> ### Provider-specific method for pausing a machine. ### return callback new Error "cannot pause node #{node_name} due to pause not implemented" resume: (node_name, callback) -> ### Provider-specific method for resuming a machine. ### return callback new Error "cannot resume node #{node_name} due to resume not implemented" shell_spec: (node_name, callback) -> ### Provider-specific method for obtaining a shell spec from a node. ### password = @extract_password node_name private_key = @extract_private_key node_name return callback new Error "no password or privateKey provided for node #{node_name}" if not password and not private_key ssh_port = @extract_ssh_port node_name if ssh_port ssh_port = parseInt ssh_port, 10 return callback new Error "ssh port for node #{node_name} is incorrect" if isNaN ssh_port or ssh_port < 1 else ssh_port = 22 username = @extract_username node_name if not username username = 'vortex' passphrase = @extract_passphrase node_name # # First we obtain the node status by looking for the address and to check if the state is correct. # obtain_status = (callback) => @status node_name, (err, state, address) -> return callback err if err return callback new Error "node #{node_name} is halting" if state == 'halting' return callback new Error "node #{node_name} is stopped" if state == 'stopped' return callback new Error "cannot find network address for node #{node_name}" if not address return callback null, address # # Next we continiusly check if the ssh port is open. # ensure_port = (address, callback) -> portchecker.isOpen ssh_port, address, (is_open) -> return callback null, address if is_open callee = arguments.callee milliseconds = 10000 timeout = () -> portchecker.isOpen ssh_port, address, callee logsmith.debug "repeat check for ssh port open for node #{node_name} in #{milliseconds} milliseconds" setTimeout timeout, milliseconds # # Finally we build the spec and send it off. # build_spec = (address, callback) -> parts = [] parts.push 'ssh://' parts.push encodeURIComponent username parts.push ':' + encodeURIComponent password if password parts.push '@' parts.push address parts.push ':' + ssh_port parts.push ';privateKey=' + encodeURIComponent private_key if private_key parts.push ';passphrase=' + encodeURIComponent passphrase if passphrase spec = parts.join '' spec_options = username: username password: PI:PASSWORD:<PASSWORD>END_PI host: address port: ssh_port privateKey: private_key passphrase: PI:PASSWORD:<PASSWORD>END_PI return callback null, spec, spec_options # # Action on the tasks. # async.waterfall [obtain_status, ensure_port, build_spec], callback
[ { "context": "l: index: true\n Users.create \n username: 'my_username',\n email: 'my@email.com',\n password: 'm", "end": 584, "score": 0.9996042847633362, "start": 573, "tag": "USERNAME", "value": "my_username" }, { "context": "ate \n username: 'my_username',\n...
test/type.coffee
wdavidw/node-ron
14
should = require 'should' try config = require '../conf/test' catch e ron = require '../lib' client = Users = null before (next) -> client = ron config next() afterEach (next) -> client.redis.keys '*', (err, keys) -> should.not.exists err keys.should.eql [] next() after (next) -> client.quit next describe 'type', -> it 'should filter properties', (next) -> Users = client.get 'users', temporal: true, properties: user_id: identifier: true username: unique: true email: index: true Users.create username: 'my_username', email: 'my@email.com', password: 'my_password' , (err, user) -> should.not.exist err properties = ['email', 'user_id'] Users.unserialize user, properties: properties Object.keys(user).should.eql properties Users.clear next
7343
should = require 'should' try config = require '../conf/test' catch e ron = require '../lib' client = Users = null before (next) -> client = ron config next() afterEach (next) -> client.redis.keys '*', (err, keys) -> should.not.exists err keys.should.eql [] next() after (next) -> client.quit next describe 'type', -> it 'should filter properties', (next) -> Users = client.get 'users', temporal: true, properties: user_id: identifier: true username: unique: true email: index: true Users.create username: 'my_username', email: '<EMAIL>', password: '<PASSWORD>' , (err, user) -> should.not.exist err properties = ['email', 'user_id'] Users.unserialize user, properties: properties Object.keys(user).should.eql properties Users.clear next
true
should = require 'should' try config = require '../conf/test' catch e ron = require '../lib' client = Users = null before (next) -> client = ron config next() afterEach (next) -> client.redis.keys '*', (err, keys) -> should.not.exists err keys.should.eql [] next() after (next) -> client.quit next describe 'type', -> it 'should filter properties', (next) -> Users = client.get 'users', temporal: true, properties: user_id: identifier: true username: unique: true email: index: true Users.create username: 'my_username', email: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' , (err, user) -> should.not.exist err properties = ['email', 'user_id'] Users.unserialize user, properties: properties Object.keys(user).should.eql properties Users.clear next
[ { "context": "ffee\n# Copyright 2016 9165584 Canada Corporation <legal@fuzzy.ai>\n\nexpress = require 'express'\npath = require 'pat", "end": 83, "score": 0.9999059438705444, "start": 69, "tag": "EMAIL", "value": "legal@fuzzy.ai" } ]
src/lemonade-stand.coffee
enterstudio/lemonade-stand
2
# lemonade-stand.coffee # Copyright 2016 9165584 Canada Corporation <legal@fuzzy.ai> express = require 'express' path = require 'path' _ = require 'lodash' { Databank } = require 'databank' session = require 'express-session' DatabankStore = require('connect-databank')(session) Microservice = require 'fuzzy.ai-microservice' APIClient = require 'fuzzy.ai' version = require './version' { seller, buyer } = require './agents' class LemonadeStand extends Microservice getName: -> "lemonade-stand" environmentToConfig: (env) -> config = super env _.extend config, apiServer: env['API_SERVER'] || 'https://api.fuzzy.ai' apiKey: env['API_KEY'] buyerID: env['BUYER_AGENT_ID'] config setupMiddleware: (exp) -> exp.apiClient = new APIClient root: @config.apiServer key: @config.apiKey # set up redis session @db = Databank.get @config.driver, @config.params @db.connect @config.params, (err) -> if err console.error "connection error" store = new DatabankStore @db, exp.log exp.use session secret: 's3kr3t' store: store resave: true saveUninitialized: true # Develpment mode tweaks if process.env.NODE_ENV == 'development' webpack = require('webpack') webpackConfig = require '../webpack.config' webpackConfig.entry.unshift('webpack-hot-middleware/client?reload=true') webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin()) compiler = webpack(webpackConfig) exp.use require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath }) exp.use(require('webpack-hot-middleware')(compiler)) exp.use express.static path.join(__dirname, '..', 'public') setupRoutes: (exp) -> exp.post '/data/seller', @_newSeller exp.post '/data/seller/evaluate', @_evaluateSeller exp.post '/data/seller/feedback', @_feedbackSeller exp.post '/data/buyer/evaluate', @_evaluateBuyer exp.get '/version', (req, res, next) -> res.json {name: 'lemonade-stand', version: version} startDatabase: (callback) -> callback null stopDatabase: (callback) -> callback null startCustom: (callback) -> client = @express.apiClient # Make sure we have the proper buyer agent. if @config.buyerID client.putAgent @config.buyerID, buyer, (err, agent) -> if err callback err else callback null else callback null _newSeller: (req, res, next) -> console.error req.session if req.session.sellerID res.json status: 'OK' else client = req.app.apiClient agent = seller agent.name = req.session.sid client.newAgent agent, (err, agent) -> if err next err else req.session.sellerID = agent.id res.json status: 'OK' _evaluateSeller: (req, res, next) -> client = req.app.apiClient client.evaluate req.session.sellerID, req.body, true, (err, evaluation) -> if err next err else req.session.lastEvalID = evaluation.meta.reqID res.json status: 'OK' evaluation: evaluation _feedbackSeller: (req, res, next) -> client = req.app.apiClient if not req.session.lastEvalID res.json status: 'OK' else evalID = req.session.lastEvalID client.feedback evalID, req.body, (err, feedback) -> if err next err res.json status: 'OK' feedback: feedback _evaluateBuyer: (req, res, next) -> client = req.app.apiClient config = req.app.config client.evaluate config.buyerID, req.body, (err, evaluation) -> if err next err else res.json status: 'OK' evaluation: evaluation module.exports = LemonadeStand
58568
# lemonade-stand.coffee # Copyright 2016 9165584 Canada Corporation <<EMAIL>> express = require 'express' path = require 'path' _ = require 'lodash' { Databank } = require 'databank' session = require 'express-session' DatabankStore = require('connect-databank')(session) Microservice = require 'fuzzy.ai-microservice' APIClient = require 'fuzzy.ai' version = require './version' { seller, buyer } = require './agents' class LemonadeStand extends Microservice getName: -> "lemonade-stand" environmentToConfig: (env) -> config = super env _.extend config, apiServer: env['API_SERVER'] || 'https://api.fuzzy.ai' apiKey: env['API_KEY'] buyerID: env['BUYER_AGENT_ID'] config setupMiddleware: (exp) -> exp.apiClient = new APIClient root: @config.apiServer key: @config.apiKey # set up redis session @db = Databank.get @config.driver, @config.params @db.connect @config.params, (err) -> if err console.error "connection error" store = new DatabankStore @db, exp.log exp.use session secret: 's3kr3t' store: store resave: true saveUninitialized: true # Develpment mode tweaks if process.env.NODE_ENV == 'development' webpack = require('webpack') webpackConfig = require '../webpack.config' webpackConfig.entry.unshift('webpack-hot-middleware/client?reload=true') webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin()) compiler = webpack(webpackConfig) exp.use require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath }) exp.use(require('webpack-hot-middleware')(compiler)) exp.use express.static path.join(__dirname, '..', 'public') setupRoutes: (exp) -> exp.post '/data/seller', @_newSeller exp.post '/data/seller/evaluate', @_evaluateSeller exp.post '/data/seller/feedback', @_feedbackSeller exp.post '/data/buyer/evaluate', @_evaluateBuyer exp.get '/version', (req, res, next) -> res.json {name: 'lemonade-stand', version: version} startDatabase: (callback) -> callback null stopDatabase: (callback) -> callback null startCustom: (callback) -> client = @express.apiClient # Make sure we have the proper buyer agent. if @config.buyerID client.putAgent @config.buyerID, buyer, (err, agent) -> if err callback err else callback null else callback null _newSeller: (req, res, next) -> console.error req.session if req.session.sellerID res.json status: 'OK' else client = req.app.apiClient agent = seller agent.name = req.session.sid client.newAgent agent, (err, agent) -> if err next err else req.session.sellerID = agent.id res.json status: 'OK' _evaluateSeller: (req, res, next) -> client = req.app.apiClient client.evaluate req.session.sellerID, req.body, true, (err, evaluation) -> if err next err else req.session.lastEvalID = evaluation.meta.reqID res.json status: 'OK' evaluation: evaluation _feedbackSeller: (req, res, next) -> client = req.app.apiClient if not req.session.lastEvalID res.json status: 'OK' else evalID = req.session.lastEvalID client.feedback evalID, req.body, (err, feedback) -> if err next err res.json status: 'OK' feedback: feedback _evaluateBuyer: (req, res, next) -> client = req.app.apiClient config = req.app.config client.evaluate config.buyerID, req.body, (err, evaluation) -> if err next err else res.json status: 'OK' evaluation: evaluation module.exports = LemonadeStand
true
# lemonade-stand.coffee # Copyright 2016 9165584 Canada Corporation <PI:EMAIL:<EMAIL>END_PI> express = require 'express' path = require 'path' _ = require 'lodash' { Databank } = require 'databank' session = require 'express-session' DatabankStore = require('connect-databank')(session) Microservice = require 'fuzzy.ai-microservice' APIClient = require 'fuzzy.ai' version = require './version' { seller, buyer } = require './agents' class LemonadeStand extends Microservice getName: -> "lemonade-stand" environmentToConfig: (env) -> config = super env _.extend config, apiServer: env['API_SERVER'] || 'https://api.fuzzy.ai' apiKey: env['API_KEY'] buyerID: env['BUYER_AGENT_ID'] config setupMiddleware: (exp) -> exp.apiClient = new APIClient root: @config.apiServer key: @config.apiKey # set up redis session @db = Databank.get @config.driver, @config.params @db.connect @config.params, (err) -> if err console.error "connection error" store = new DatabankStore @db, exp.log exp.use session secret: 's3kr3t' store: store resave: true saveUninitialized: true # Develpment mode tweaks if process.env.NODE_ENV == 'development' webpack = require('webpack') webpackConfig = require '../webpack.config' webpackConfig.entry.unshift('webpack-hot-middleware/client?reload=true') webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin()) compiler = webpack(webpackConfig) exp.use require('webpack-dev-middleware')(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath }) exp.use(require('webpack-hot-middleware')(compiler)) exp.use express.static path.join(__dirname, '..', 'public') setupRoutes: (exp) -> exp.post '/data/seller', @_newSeller exp.post '/data/seller/evaluate', @_evaluateSeller exp.post '/data/seller/feedback', @_feedbackSeller exp.post '/data/buyer/evaluate', @_evaluateBuyer exp.get '/version', (req, res, next) -> res.json {name: 'lemonade-stand', version: version} startDatabase: (callback) -> callback null stopDatabase: (callback) -> callback null startCustom: (callback) -> client = @express.apiClient # Make sure we have the proper buyer agent. if @config.buyerID client.putAgent @config.buyerID, buyer, (err, agent) -> if err callback err else callback null else callback null _newSeller: (req, res, next) -> console.error req.session if req.session.sellerID res.json status: 'OK' else client = req.app.apiClient agent = seller agent.name = req.session.sid client.newAgent agent, (err, agent) -> if err next err else req.session.sellerID = agent.id res.json status: 'OK' _evaluateSeller: (req, res, next) -> client = req.app.apiClient client.evaluate req.session.sellerID, req.body, true, (err, evaluation) -> if err next err else req.session.lastEvalID = evaluation.meta.reqID res.json status: 'OK' evaluation: evaluation _feedbackSeller: (req, res, next) -> client = req.app.apiClient if not req.session.lastEvalID res.json status: 'OK' else evalID = req.session.lastEvalID client.feedback evalID, req.body, (err, feedback) -> if err next err res.json status: 'OK' feedback: feedback _evaluateBuyer: (req, res, next) -> client = req.app.apiClient config = req.app.config client.evaluate config.buyerID, req.body, (err, evaluation) -> if err next err else res.json status: 'OK' evaluation: evaluation module.exports = LemonadeStand
[ { "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.9998838901519775, "start": 61, "tag": "NAME", "value": "Jessym Reziga" }, { "context": "f the Konsserto package.\n *\n * (c) Je...
node_modules/konsserto/lib/src/Konsserto/Component/Form/FormField.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. ### forms = use('ks-forms') formWidgets = forms.widgets # # FormField # # @author Jessym Reziga <jessym@konsserto.com> # class FormField constructor: (@name,@formName,@type,@options,predata = {}) -> @submit = false @csrf = false @options['value'] = predata[@name] if predata[@name]? @setSubmit() if type == 'submit' @setCsrf() if @name == '_csrf' @setHTMLfields() setSubmit:() -> @submit = true @options['widget'] = formWidgets.submit(@options) @options['value'] = @name setCsrf:() -> @csrf = true @getFullname = () -> return @name handleSubmit:() -> if @isSubmit() value = @getCompiled()['value'] if value != '' && value != undefined && value != null @isClicked = ()=> return true else @isClicked = ()=> return false @getCompiled()['value'] = @name isSubmit:() -> return @submit isCsrf:() -> return @csrf getId:() -> return @formName+'_'+@name getFullname:() -> return @formName+'['+@name+']' getShortname:() -> m = @name.match('\\[(.+)\\]') if m? && m.length >=2 return m[1] return '' setHTMLfields:() -> @addDefault(@options,'id',@getId()) @addDefault(@options,'fullname',@getFullname()) @addDefault(@options,'shortname',@name) addDefault:(object,field,value) => object[field] ?= value getName:() -> return @name getType:() -> return @type getOptions:() -> return @options setCompiled:(@compiled) -> return this getCompiled:() -> return @compiled isClicked: () -> if !@isSubmit() throw new Error('You can\'t call isClicked on a non submit field') getData:() -> return @compiled.data module.exports = FormField
142666
### * 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. ### forms = use('ks-forms') formWidgets = forms.widgets # # FormField # # @author <NAME> <<EMAIL>> # class FormField constructor: (@name,@formName,@type,@options,predata = {}) -> @submit = false @csrf = false @options['value'] = predata[@name] if predata[@name]? @setSubmit() if type == 'submit' @setCsrf() if @name == '_csrf' @setHTMLfields() setSubmit:() -> @submit = true @options['widget'] = formWidgets.submit(@options) @options['value'] = @name setCsrf:() -> @csrf = true @getFullname = () -> return @name handleSubmit:() -> if @isSubmit() value = @getCompiled()['value'] if value != '' && value != undefined && value != null @isClicked = ()=> return true else @isClicked = ()=> return false @getCompiled()['value'] = @name isSubmit:() -> return @submit isCsrf:() -> return @csrf getId:() -> return @formName+'_'+@name getFullname:() -> return @formName+'['+@name+']' getShortname:() -> m = @name.match('\\[(.+)\\]') if m? && m.length >=2 return m[1] return '' setHTMLfields:() -> @addDefault(@options,'id',@getId()) @addDefault(@options,'fullname',@getFullname()) @addDefault(@options,'shortname',@name) addDefault:(object,field,value) => object[field] ?= value getName:() -> return @name getType:() -> return @type getOptions:() -> return @options setCompiled:(@compiled) -> return this getCompiled:() -> return @compiled isClicked: () -> if !@isSubmit() throw new Error('You can\'t call isClicked on a non submit field') getData:() -> return @compiled.data module.exports = FormField
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. ### forms = use('ks-forms') formWidgets = forms.widgets # # FormField # # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # class FormField constructor: (@name,@formName,@type,@options,predata = {}) -> @submit = false @csrf = false @options['value'] = predata[@name] if predata[@name]? @setSubmit() if type == 'submit' @setCsrf() if @name == '_csrf' @setHTMLfields() setSubmit:() -> @submit = true @options['widget'] = formWidgets.submit(@options) @options['value'] = @name setCsrf:() -> @csrf = true @getFullname = () -> return @name handleSubmit:() -> if @isSubmit() value = @getCompiled()['value'] if value != '' && value != undefined && value != null @isClicked = ()=> return true else @isClicked = ()=> return false @getCompiled()['value'] = @name isSubmit:() -> return @submit isCsrf:() -> return @csrf getId:() -> return @formName+'_'+@name getFullname:() -> return @formName+'['+@name+']' getShortname:() -> m = @name.match('\\[(.+)\\]') if m? && m.length >=2 return m[1] return '' setHTMLfields:() -> @addDefault(@options,'id',@getId()) @addDefault(@options,'fullname',@getFullname()) @addDefault(@options,'shortname',@name) addDefault:(object,field,value) => object[field] ?= value getName:() -> return @name getType:() -> return @type getOptions:() -> return @options setCompiled:(@compiled) -> return this getCompiled:() -> return @compiled isClicked: () -> if !@isSubmit() throw new Error('You can\'t call isClicked on a non submit field') getData:() -> return @compiled.data module.exports = FormField
[ { "context": "###\n# controllers/basic.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# This module de", "end": 53, "score": 0.9995443820953369, "start": 42, "tag": "NAME", "value": "Dan Nichols" } ]
lib/controllers/basic.coffee
dlnichols/h_media
0
### # controllers/basic.coffee # # © 2014 Dan Nichols # See LICENSE for more details # # This module defines the controllers that handle partials (in development) and # the main application. ### 'use strict' # External libs path = require 'path' debug = require('debug') 'hMedia:controllers:basic' # Internal libs env = require '../config/environment' ### # Basic controllers # # These are basic GET actions on /partials/* or /* ### debug 'Configuring basic controllers...' module.exports = exports = ### # Partials # # This controller handles the /partials ### partials: (req, res, next) -> throw new Error('Static content should not be handled by Node in production') if env.isProduction() stripped = req.url.split('.')[0] requestedView = path.join('./', stripped) res.render requestedView, (err, html) -> if err debug "Error rendering partial '" + requestedView + "'\n", err res.send 404 else res.send html ### # Index # # This controller handles the single page app, but should only render if the # request was not XHR ### index: (req, res, next) -> if not req.xhr and req.accepts('html') is 'html' res.cookie 'user', JSON.stringify(req.user.userInfo) if req.user res.render 'index' else next() ### # Not Found # # This controller handles routes that are not found ### notFound: (req, res, next) -> res.send 404
5842
### # controllers/basic.coffee # # © 2014 <NAME> # See LICENSE for more details # # This module defines the controllers that handle partials (in development) and # the main application. ### 'use strict' # External libs path = require 'path' debug = require('debug') 'hMedia:controllers:basic' # Internal libs env = require '../config/environment' ### # Basic controllers # # These are basic GET actions on /partials/* or /* ### debug 'Configuring basic controllers...' module.exports = exports = ### # Partials # # This controller handles the /partials ### partials: (req, res, next) -> throw new Error('Static content should not be handled by Node in production') if env.isProduction() stripped = req.url.split('.')[0] requestedView = path.join('./', stripped) res.render requestedView, (err, html) -> if err debug "Error rendering partial '" + requestedView + "'\n", err res.send 404 else res.send html ### # Index # # This controller handles the single page app, but should only render if the # request was not XHR ### index: (req, res, next) -> if not req.xhr and req.accepts('html') is 'html' res.cookie 'user', JSON.stringify(req.user.userInfo) if req.user res.render 'index' else next() ### # Not Found # # This controller handles routes that are not found ### notFound: (req, res, next) -> res.send 404
true
### # controllers/basic.coffee # # © 2014 PI:NAME:<NAME>END_PI # See LICENSE for more details # # This module defines the controllers that handle partials (in development) and # the main application. ### 'use strict' # External libs path = require 'path' debug = require('debug') 'hMedia:controllers:basic' # Internal libs env = require '../config/environment' ### # Basic controllers # # These are basic GET actions on /partials/* or /* ### debug 'Configuring basic controllers...' module.exports = exports = ### # Partials # # This controller handles the /partials ### partials: (req, res, next) -> throw new Error('Static content should not be handled by Node in production') if env.isProduction() stripped = req.url.split('.')[0] requestedView = path.join('./', stripped) res.render requestedView, (err, html) -> if err debug "Error rendering partial '" + requestedView + "'\n", err res.send 404 else res.send html ### # Index # # This controller handles the single page app, but should only render if the # request was not XHR ### index: (req, res, next) -> if not req.xhr and req.accepts('html') is 'html' res.cookie 'user', JSON.stringify(req.user.userInfo) if req.user res.render 'index' else next() ### # Not Found # # This controller handles routes that are not found ### notFound: (req, res, next) -> res.send 404
[ { "context": " exec \"\"\"\n fqdn='#{params.fqdn}'\n shortname='#{shortname}'\n if [ ! -f #{cacert_path} ]; then echo 'Ru", "end": 653, "score": 0.7068151831626892, "start": 648, "tag": "NAME", "value": "short" } ]
lib/commands/pki/cert.coffee
WIN32GG/node-masson
0
path = require 'path' {exec} = require 'child_process' # `./bin/ryba pki --dir ./conf/certs cert {fqdn}` module.exports = ({params}, config, callback) -> cakey_path = path.resolve params.dir, 'ca.key.pem' cacert_path = path.resolve params.dir, 'ca.cert.pem' caserial_path = path.resolve params.dir, 'ca.seq' shortname = params.fqdn.split('.')[0] csr_path = path.resolve params.dir, "#{shortname}.cert.csr" key_path = path.resolve params.dir, "#{shortname}.key.pem" cert_path = path.resolve params.dir, "#{shortname}.cert.pem" subject = "/C=FR/O=Adaltas/L=Paris/CN=#{params.fqdn}" exec """ fqdn='#{params.fqdn}' shortname='#{shortname}' if [ ! -f #{cacert_path} ]; then echo 'Run `./generate.sh cacert` first.'; exit 1; fi # Certificate signing request (CSR) and private key (create "{hostname}.cert.csr" and "{hostname}.key.pem") openssl req -newkey rsa:2048 -sha256 -nodes -out #{csr_path} -keyout #{key_path} -subj '#{subject}' # to view the CSR: `openssl req -in {hostname}.cert.csr -noout -text` # Sign the CSR (create "hadoop.cert.pem") openssl x509 -req -sha256 -days 7300 -in #{csr_path} -CA #{cacert_path} -CAkey #{cakey_path} -out #{cert_path} -CAcreateserial -CAserial #{caserial_path} # Clean up rm -rf '#{csr_path}' """ , (err, stdout, stderr) -> if err process.stderr.write '\n' + stderr + '\n\n' process.exit 1
8687
path = require 'path' {exec} = require 'child_process' # `./bin/ryba pki --dir ./conf/certs cert {fqdn}` module.exports = ({params}, config, callback) -> cakey_path = path.resolve params.dir, 'ca.key.pem' cacert_path = path.resolve params.dir, 'ca.cert.pem' caserial_path = path.resolve params.dir, 'ca.seq' shortname = params.fqdn.split('.')[0] csr_path = path.resolve params.dir, "#{shortname}.cert.csr" key_path = path.resolve params.dir, "#{shortname}.key.pem" cert_path = path.resolve params.dir, "#{shortname}.cert.pem" subject = "/C=FR/O=Adaltas/L=Paris/CN=#{params.fqdn}" exec """ fqdn='#{params.fqdn}' shortname='#{<NAME>name}' if [ ! -f #{cacert_path} ]; then echo 'Run `./generate.sh cacert` first.'; exit 1; fi # Certificate signing request (CSR) and private key (create "{hostname}.cert.csr" and "{hostname}.key.pem") openssl req -newkey rsa:2048 -sha256 -nodes -out #{csr_path} -keyout #{key_path} -subj '#{subject}' # to view the CSR: `openssl req -in {hostname}.cert.csr -noout -text` # Sign the CSR (create "hadoop.cert.pem") openssl x509 -req -sha256 -days 7300 -in #{csr_path} -CA #{cacert_path} -CAkey #{cakey_path} -out #{cert_path} -CAcreateserial -CAserial #{caserial_path} # Clean up rm -rf '#{csr_path}' """ , (err, stdout, stderr) -> if err process.stderr.write '\n' + stderr + '\n\n' process.exit 1
true
path = require 'path' {exec} = require 'child_process' # `./bin/ryba pki --dir ./conf/certs cert {fqdn}` module.exports = ({params}, config, callback) -> cakey_path = path.resolve params.dir, 'ca.key.pem' cacert_path = path.resolve params.dir, 'ca.cert.pem' caserial_path = path.resolve params.dir, 'ca.seq' shortname = params.fqdn.split('.')[0] csr_path = path.resolve params.dir, "#{shortname}.cert.csr" key_path = path.resolve params.dir, "#{shortname}.key.pem" cert_path = path.resolve params.dir, "#{shortname}.cert.pem" subject = "/C=FR/O=Adaltas/L=Paris/CN=#{params.fqdn}" exec """ fqdn='#{params.fqdn}' shortname='#{PI:NAME:<NAME>END_PIname}' if [ ! -f #{cacert_path} ]; then echo 'Run `./generate.sh cacert` first.'; exit 1; fi # Certificate signing request (CSR) and private key (create "{hostname}.cert.csr" and "{hostname}.key.pem") openssl req -newkey rsa:2048 -sha256 -nodes -out #{csr_path} -keyout #{key_path} -subj '#{subject}' # to view the CSR: `openssl req -in {hostname}.cert.csr -noout -text` # Sign the CSR (create "hadoop.cert.pem") openssl x509 -req -sha256 -days 7300 -in #{csr_path} -CA #{cacert_path} -CAkey #{cakey_path} -out #{cert_path} -CAcreateserial -CAserial #{caserial_path} # Clean up rm -rf '#{csr_path}' """ , (err, stdout, stderr) -> if err process.stderr.write '\n' + stderr + '\n\n' process.exit 1
[ { "context": ".returns Promise.resolve fabricate 'artist', id: 'charles-broskoski'\n .onCall(1)\n .returns Promis", "end": 607, "score": 0.9525127410888672, "start": 600, "tag": "NAME", "value": "charles" }, { "context": " Promise.resolve fabricate 'artist', id: 'charles-br...
src/desktop/apps/home/components/followed_artists/test/view.coffee
zephraph/force
1
benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' { resolve } = require 'path' { fabricate } = require '@artsy/antigravity' Items = require '../../../../../collections/items.coffee' FollowedArtistsRailView = benv.requireWithJadeify require.resolve('../view.coffee'), ['template'] describe 'FollowedArtistsRailView', -> before (done) -> benv.setup -> benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') Backbone.$ = $ done() sinon.stub Backbone, 'sync' .onCall(0) .returns Promise.resolve fabricate 'artist', id: 'charles-broskoski' .onCall(1) .returns Promise.resolve fabricate 'artist', id: 'damon-zucconi' @featuredArtists = new Items [ fabricate 'featured_link' # href: /cat/bitty fabricate 'featured_link', href: 'https://www.artsy.net/artist/damon-zucconi' fabricate 'featured_link', href: 'https://www.artsy.net/artwork/damon-zucconi' fabricate 'featured_link', href: 'https://www.artsy.net/artist/charles-broskoski?fake=true' ] after -> benv.teardown() Backbone.sync.restore() beforeEach -> @view = new FollowedArtistsRailView el: $('body') describe '#_parseAndFetchArtists', -> it 'filters out weird urls', -> @view._parseAndFetchArtists(@featuredArtists) .then (artists) -> artists.length.should.equal 2 artists[0].id.should.equal 'charles-broskoski' artists[1].id.should.equal 'damon-zucconi'
26288
benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' { resolve } = require 'path' { fabricate } = require '@artsy/antigravity' Items = require '../../../../../collections/items.coffee' FollowedArtistsRailView = benv.requireWithJadeify require.resolve('../view.coffee'), ['template'] describe 'FollowedArtistsRailView', -> before (done) -> benv.setup -> benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') Backbone.$ = $ done() sinon.stub Backbone, 'sync' .onCall(0) .returns Promise.resolve fabricate 'artist', id: '<NAME>-<NAME>' .onCall(1) .returns Promise.resolve fabricate 'artist', id: '<NAME>' @featuredArtists = new Items [ fabricate 'featured_link' # href: /cat/bitty fabricate 'featured_link', href: 'https://www.artsy.net/artist/damon-zucconi' fabricate 'featured_link', href: 'https://www.artsy.net/artwork/damon-zucconi' fabricate 'featured_link', href: 'https://www.artsy.net/artist/<NAME>les-broskoski?fake=true' ] after -> benv.teardown() Backbone.sync.restore() beforeEach -> @view = new FollowedArtistsRailView el: $('body') describe '#_parseAndFetchArtists', -> it 'filters out weird urls', -> @view._parseAndFetchArtists(@featuredArtists) .then (artists) -> artists.length.should.equal 2 artists[0].id.should.equal '<NAME>-<NAME>' artists[1].id.should.equal '<NAME>'
true
benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' { resolve } = require 'path' { fabricate } = require '@artsy/antigravity' Items = require '../../../../../collections/items.coffee' FollowedArtistsRailView = benv.requireWithJadeify require.resolve('../view.coffee'), ['template'] describe 'FollowedArtistsRailView', -> before (done) -> benv.setup -> benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') Backbone.$ = $ done() sinon.stub Backbone, 'sync' .onCall(0) .returns Promise.resolve fabricate 'artist', id: 'PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI' .onCall(1) .returns Promise.resolve fabricate 'artist', id: 'PI:NAME:<NAME>END_PI' @featuredArtists = new Items [ fabricate 'featured_link' # href: /cat/bitty fabricate 'featured_link', href: 'https://www.artsy.net/artist/damon-zucconi' fabricate 'featured_link', href: 'https://www.artsy.net/artwork/damon-zucconi' fabricate 'featured_link', href: 'https://www.artsy.net/artist/PI:NAME:<NAME>END_PIles-broskoski?fake=true' ] after -> benv.teardown() Backbone.sync.restore() beforeEach -> @view = new FollowedArtistsRailView el: $('body') describe '#_parseAndFetchArtists', -> it 'filters out weird urls', -> @view._parseAndFetchArtists(@featuredArtists) .then (artists) -> artists.length.should.equal 2 artists[0].id.should.equal 'PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI' artists[1].id.should.equal 'PI:NAME:<NAME>END_PI'
[ { "context": "ew @GradientPreset, @presetDefaults,\n id: 'Copper'\n name: 'Copper'\n ColorHandles: [\n ", "end": 9562, "score": 0.9722960591316223, "start": 9556, "tag": "USERNAME", "value": "Copper" }, { "context": "esetDefaults,\n id: 'Copper'\n n...
js/src/controller/MainCtrl.coffee
evictor/html5-canvas-gradient-creator
10
class window.MainCtrl addHandleDefaultColor: 'rgba(0, 0, 0, 1)' presetDefaults: gradientType: 'linear' width: 300 height: 300 rotate: 0 innerCircleX: 50 innerCircleY: 50 outerCircleX: 50 outerCircleY: 50 constructor: (@$scope, @$document, @ColorHandle, @$filter, @localStorageService, @GradientPreset) -> @$scope.localStorageSupported = @localStorageService.isSupported() @$scope.gradientType = @presetDefaults.gradientType @$scope.bigCanvasWidth = @presetDefaults.width @$scope.bigCanvasHeight = @presetDefaults.height @$scope.rotateDegrees = @presetDefaults.rotate @$scope.innerCircleX = @presetDefaults.innerCircleX @$scope.innerCircleY = @presetDefaults.innerCircleY @$scope.outerCircleX = @presetDefaults.outerCircleX @$scope.outerCircleY = @presetDefaults.outerCircleY @$scope.LoadedPreset = {} @$scope.loading = true $.fn.qtip.defaults.position.my = 'bottom left' $.fn.qtip.defaults.position.at = 'top center' $.fn.qtip.defaults.position.viewport = true $.fn.qtip.defaults.position.adjust.method = 'shift none' $.fn.qtip.defaults.position.adjust.y = -3 $.fn.qtip.defaults.style.classes = 'qtip-jtools' @$scope.presetTooltipOpts = position: my: 'bottom center' # Get saved presets from local storage @$scope.SavedPresets = @GradientPreset.query() # Scope proxy methods @$scope.addColorHandle = => @addColorHandle.apply @, arguments @$scope.deleteColorHandle = => @deleteColorHandle.apply @, arguments @$scope.setActiveColorHandle = => @setActiveColorHandle.apply @, arguments @$scope.getMouseIsDown = => @getMouseIsDown.apply @, arguments @$scope.applyPreset = => @applyPreset.apply @, arguments @$scope.saveLoadedPreset = => @saveLoadedPreset.apply @, arguments @$scope.deleteLoadedPreset = => @deleteLoadedPreset.apply @, arguments @initColorHandles() @trackMouseIsDown() @setUpActiveColorHandleStopManualInput() @compileGradientHtmlPageCode() @initPresets() @manageLoadedPresetDirty() # Auto-show/hide instructions based on color active handle @$scope.$watch 'ActiveColorHandle', (ActiveColorHandle) => @$scope.showInstructions = !ActiveColorHandle? initColorHandles: -> @$scope.ColorHandles = [ new @ColorHandle('rgba(0, 0, 0, 1)', 0) new @ColorHandle('rgba(255, 255, 255, 1)', 1) ] @setActiveColorHandle null # ColorHandles stop change @$scope.$watch (=> (CH.stop for CH in @$scope.ColorHandles)), => # Resort by stop @sortColorHandlesByStop() , true ### Adds a new color handle. @param {Number} stop New color handle's desired stop. ### addColorHandle: (stop) -> NewHandle = new @ColorHandle @addHandleDefaultColor, stop NewHandle.forceDrag = true @$scope.ColorHandles.push NewHandle # Sort by stop @sortColorHandlesByStop() ### @param {Object} DeleteColorHandle Handle to delete. @return {Boolean} TRUE if the handle was deleted (last handle is never deleted; will return FALSE). ### deleteColorHandle: (DeleteColorHandle) -> # OK to delete (not last handle) deleted = @$scope.ColorHandles.length > 1 if deleted # Sort handles by stop @sortColorHandlesByStop() # Handle to delete is active handle if DeleteColorHandle == @$scope.ActiveColorHandle # Set active handle to next handle, or previous handle if next handle was last handle for ColorHandle, i in @$scope.ColorHandles if ColorHandle == DeleteColorHandle @$scope.setActiveColorHandle @$scope.ColorHandles[i + 1] ? @$scope.ColorHandles[i - 1] break # Delete handle @$scope.ColorHandles = (ColorHandle for ColorHandle in @$scope.ColorHandles when ColorHandle isnt DeleteColorHandle) deleted ### The "active" color handle is the one whose color is loaded into the color picker. @param {Object} ColorHandle Handle to set as active. ### setActiveColorHandle: (ColorHandle) -> @$scope.ActiveColorHandle = ColorHandle ### Keeps @$scope.mouseIsDown up to date. @see getMouseIsDown() ### trackMouseIsDown: -> @$scope.mouseIsDown = false @$document.mousedown => @$scope.mouseIsDown = true @$document.mouseup => @$scope.mouseIsDown = false ### @return {Boolean} TRUE if mouse is currently down, FALSE if it is up. ### getMouseIsDown: -> @$scope.mouseIsDown ### Keeps active color handle stop and manual input in sync. ### setUpActiveColorHandleStopManualInput: -> numberFilter = @$filter 'number' # Keep input up to date with handle @$scope.$watch 'ActiveColorHandle.stop', (stop) => if stop? then @$scope.activeColorHandleStopPercent = parseFloat(numberFilter(stop * 100, 1).replace(/,/g, '')) # Keep handle up to date with input @$scope.$watch 'activeColorHandleStopPercent', (percent) => if percent? then @$scope.ActiveColorHandle.stop = percent / 100 ### Watches HTML and JS code bits from previewCanvas directive and compiles final full page code. ### compileGradientHtmlPageCode: -> # Watch gradient code parts @$scope.$watch => html: @$scope.gradientHtmlCode ? '' js: @$scope.gradientJsCode ? '' dirty: @$scope.LoadedPreset?.dirty , (codeParts) => # Get HTML escaped gradient preset name (or default name) gradientNameHtml = if @$scope.LoadedPreset.name? jQuery('<p />').text(@$scope.LoadedPreset.name).html() + if @$scope.LoadedPreset.dirty then ' (modified)' else '' else 'Ermahgerd, a gradient' @$scope.gradientHtmlPageCode = """ <!doctype html> <html> <head> <meta charset="UTF-8"> <title>#{gradientNameHtml}</title> </head> <body> #{codeParts.html} <script type="text/javascript"> #{codeParts.js.replace /\n/g, '\n '} </script> </body> </html> """ , true ### Init gradient presets. ### initPresets: -> @$scope.Presets = [ angular.extend new @GradientPreset, @presetDefaults, id: 'Black → transparent' name: 'Black → transparent' ColorHandles: [ new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.00 new @ColorHandle 'rgba(0, 0, 0, 0.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'White → transparent' name: 'White → transparent' ColorHandles: [ new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.00 new @ColorHandle 'rgba(255, 255, 255, 0.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Red → green' name: 'Red → green' ColorHandles: [ new @ColorHandle 'rgba(225, 0, 25, 1.00)', 0.00 new @ColorHandle 'rgba(0, 96, 27, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Violet → orange' name: 'Violet → orange' ColorHandles: [ new @ColorHandle 'rgba(41, 10, 89, 1.00)', 0.00 new @ColorHandle 'rgba(255, 124, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Blue → red → yellow' name: 'Blue → red → yellow' ColorHandles: [ new @ColorHandle 'rgba(10, 0, 178, 1.00)', 0.00 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.50 new @ColorHandle 'rgba(255, 252, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Blue → yellow → blue' name: 'Blue → yellow → blue' ColorHandles: [ new @ColorHandle 'rgba(11, 1, 184, 1.00)', 0.10 new @ColorHandle 'rgba(253, 250, 3, 1.00)', 0.50 new @ColorHandle 'rgba(11, 2, 170, 1.00)', 0.90 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Orange → yellow → orange' name: 'Orange → yellow → orange' ColorHandles: [ new @ColorHandle 'rgba(255, 110, 2, 1.00)', 0.00 new @ColorHandle 'rgba(255, 255, 0, 1.00)', 0.50 new @ColorHandle 'rgba(255, 109, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Violet → green → orange' name: 'Violet → green → orange' ColorHandles: [ new @ColorHandle 'rgba(111, 21, 108, 1.00)', 0.00 new @ColorHandle 'rgba(0, 96, 27, 1.00)', 0.50 new @ColorHandle 'rgba(253, 124, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Yellow → violet → orange → blue' name: 'Yellow → violet → orange → blue' ColorHandles: [ new @ColorHandle 'rgba(249, 230, 0, 1.00)', 0.05 new @ColorHandle 'rgba(111, 21, 108, 1.00)', 0.35 new @ColorHandle 'rgba(253, 124, 0, 1.00)', 0.65 new @ColorHandle 'rgba(0, 40, 116, 1.00)', 0.95 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Copper' name: 'Copper' ColorHandles: [ new @ColorHandle 'rgba(151, 70, 26, 1.00)', 0.00 new @ColorHandle 'rgba(251, 216, 197, 1.00)', 0.30 new @ColorHandle 'rgba(108, 46, 22, 1.00)', 0.83 new @ColorHandle 'rgba(239, 219, 205, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Chrome' name: 'Chrome' ColorHandles: [ new @ColorHandle 'rgba(41, 137, 204, 1.00)', 0.00 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.50 new @ColorHandle 'rgba(144, 106, 0, 1.00)', 0.52 new @ColorHandle 'rgba(217, 159, 0, 1.00)', 0.64 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Spectrum' name: 'Spectrum' ColorHandles: [ new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.00 new @ColorHandle 'rgba(255, 0, 255, 1.00)', 0.15 new @ColorHandle 'rgba(0, 0, 255, 1.00)', 0.33 new @ColorHandle 'rgba(0, 255, 255, 1.00)', 0.49 new @ColorHandle 'rgba(0, 255, 0, 1.00)', 0.67 new @ColorHandle 'rgba(255, 255, 0, 1.00)', 0.84 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Rainbow' name: 'Rainbow' ColorHandles: [ new @ColorHandle 'rgba(255, 0, 0, 0.00)', 0.15 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.20 new @ColorHandle 'rgba(255, 252, 0, 1.00)', 0.32 new @ColorHandle 'rgba(1, 180, 57, 1.00)', 0.44 new @ColorHandle 'rgba(0, 234, 255, 1.00)', 0.56 new @ColorHandle 'rgba(0, 3, 144, 1.00)', 0.68 new @ColorHandle 'rgba(255, 0, 198, 1.00)', 0.80 new @ColorHandle 'rgba(255, 0, 198, 0.00)', 0.85 ] ] @$scope.FunPresets = [ angular.extend new @GradientPreset, @presetDefaults, id: 'Solar eclipse' name: 'Solar eclipse' gradientType: 'radial' innerCircleX: 45 innerCircleY: 45 outerCircleX: 45 outerCircleY: 45 ColorHandles: [ new @ColorHandle 'rgba(34, 10, 10, 1.00)', 0.00 new @ColorHandle 'rgba(34, 10, 10, 1.00)', 0.33 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.34 new @ColorHandle 'rgba(234, 189, 12, 1.00)', 0.60 new @ColorHandle 'rgba(35, 1, 4, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Eyeball' name: 'Eyeball' gradientType: 'radial' innerCircleX: 51 innerCircleY: 63.3 outerCircleY: 49 ColorHandles: [ new @ColorHandle 'rgba(14, 14, 16, 1.00)', 0.00 new @ColorHandle 'rgba(14, 14, 16, 1.00)', 0.17 new @ColorHandle 'rgba(75, 93, 103, 1.00)', 0.61 new @ColorHandle 'rgba(96, 109, 91, 1.00)', 0.27 new @ColorHandle 'rgba(75, 93, 103, 1.00)', 0.62 new @ColorHandle 'rgba(255, 250, 250, 1.00)', 0.69 new @ColorHandle 'rgba(255, 250, 250, 1.00)', 0.92 new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.93 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.94 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Bullseye' name: 'Bullseye' gradientType: 'radial' ColorHandles: [ new @ColorHandle 'rgba(255, 238, 40, 1.00)', 0.00 new @ColorHandle 'rgba(255, 238, 40, 1.00)', 0.20 new @ColorHandle 'rgba(194, 66, 57, 1.00)', 0.21 new @ColorHandle 'rgba(194, 66, 57, 1.00)', 0.40 new @ColorHandle 'rgba(130, 194, 238, 1.00)', 0.41 new @ColorHandle 'rgba(130, 194, 238, 1.00)', 0.60 new @ColorHandle 'rgba(254, 254, 254, 1.00)', 0.61 new @ColorHandle 'rgba(254, 254, 254, 1.00)', 0.78 new @ColorHandle 'rgba(52, 50, 51, 1.00)', 0.79 new @ColorHandle 'rgba(52, 50, 51, 1.00)', 0.99 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Breakfast' name: 'Breakfast' gradientType: 'radial' width: 320 height: 404 innerCircleY: 89.1 outerCircleY: 47.5 ColorHandles: [ new @ColorHandle 'rgba(255, 153, 0, 1.00)', 0.00 new @ColorHandle 'rgba(255, 191, 0, 1.00)', 0.46 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.49 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.86 new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.85 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.84 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Sunset' name: 'Sunset' gradientType: 'radial' innerCircleX: 60 innerCircleY: 100 outerCircleX: 60 outerCircleY: 100 ColorHandles: [ new @ColorHandle 'rgba(255, 242, 0, 1.00)', 0.00 new @ColorHandle 'rgba(255, 157, 0, 1.00)', 0.37 new @ColorHandle 'rgba(47, 32, 163, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Oui oui' name: 'Oui oui' gradientType: 'linear' width: 300 height: 200 ColorHandles: [ new @ColorHandle 'rgba(0, 85, 164, 1.00)', 0.00 new @ColorHandle 'rgba(0, 85, 164, 1.00)', 0.33 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.331 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.66 new @ColorHandle 'rgba(250, 60, 50, 1.00)', 0.661 new @ColorHandle 'rgba(250, 60, 50, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Mamma mia' name: 'Mamma mia' gradientType: 'linear' width: 300 height: 200 ColorHandles: [ new @ColorHandle 'rgba(0, 146, 70, 1.00)', 0.00 new @ColorHandle 'rgba(0, 146, 70, 1.00)', 0.33 new @ColorHandle 'rgba(241, 242, 241, 1.00)', 0.331 new @ColorHandle 'rgba(241, 242, 241, 1.00)', 0.66 new @ColorHandle 'rgba(206, 43, 55, 1.00)', 0.661 new @ColorHandle 'rgba(206, 43, 55, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Con gusto' name: 'Con gusto' gradientType: 'linear' rotate: 90 width: 300 height: 200 ColorHandles: [ new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.00 new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.5 new @ColorHandle 'rgba(0, 56, 147, 1.00)', 0.501 new @ColorHandle 'rgba(0, 56, 147, 1.00)', 0.75 new @ColorHandle 'rgba(206, 17, 38, 1.00)', 0.751 new @ColorHandle 'rgba(206, 17, 38, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Genau' name: 'Genau' gradientType: 'linear' rotate: 90 width: 300 height: 180 ColorHandles: [ new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.00 new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.33 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.331 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.69 new @ColorHandle 'rgba(255, 204, 0, 1.00)', 0.691 new @ColorHandle 'rgba(255, 204, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Привет' name: 'Привет' gradientType: 'linear' rotate: 90 width: 300 height: 200 ColorHandles: [ new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.00 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.33 new @ColorHandle 'rgba(0, 0, 255, 1.00)', 0.331 new @ColorHandle 'rgba(0, 0, 255, 1.00)', 0.69 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.691 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Maisha mazuri' name: 'Maisha mazuri' gradientType: 'linear' rotate: 71 width: 300 height: 200 ColorHandles: [ new @ColorHandle 'rgba(30, 181, 58, 1.00)', 0.00 new @ColorHandle 'rgba(30, 181, 58, 1.00)', 0.35 new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.351 new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.4 new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.401 new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.6 new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.601 new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.65 new @ColorHandle 'rgba(0, 163, 221, 1.00)', 0.651 new @ColorHandle 'rgba(0, 163, 221, 1.00)', 1.00 ] ] ### Apply preset gradient to working area. @param {GradientPreset} Preset ### applyPreset: (Preset) -> # Deep clone so updates in the working area don't immediately affect the preset Preset = Preset.clone() @$scope.gradientType = Preset.gradientType @$scope.bigCanvasWidth = Preset.width @$scope.bigCanvasHeight = Preset.height @$scope.rotateDegrees = Preset.rotate @$scope.innerCircleX = Preset.innerCircleX @$scope.innerCircleY = Preset.innerCircleY @$scope.outerCircleX = Preset.outerCircleX @$scope.outerCircleY = Preset.outerCircleY @$scope.ColorHandles = Preset.ColorHandles @$scope.ActiveColorHandle = null @$scope.LoadedPreset = Preset @$scope.LoadedPreset.initialChange = true ### Marks loaded preset as dirty as appropriate. ### manageLoadedPresetDirty: -> # Marks loaded preset dirty under certain conditions... manageLoadedPresetDirty = => # 1. There actually is a loaded preset # 2. The data watch fired wasn't the "initial change" if @$scope.LoadedPreset? and !@$scope.LoadedPreset.initialChange @$scope.LoadedPreset.dirty = true else @$scope.LoadedPreset.initialChange = false # Watch data that should dirtify @$scope.$watch => gradientType: @$scope.gradientType width: @$scope.bigCanvasWidth height: @$scope.bigCanvasHeight rotate: @$scope.rotateDegrees innerCircleX: @$scope.innerCircleX innerCircleY: @$scope.innerCircleY outerCircleX: @$scope.outerCircleX outerCircleY: @$scope.outerCircleY ColorHandles: @$scope.ColorHandles , (newData, oldData) -> # Some data actually changed if typeof newData != typeof oldData or newData.gradientType != oldData.gradientType or newData.width != oldData.width or newData.height != oldData.height or newData.rotate != oldData.rotate or newData.innerCircleX != oldData.innerCircleX or newData.innerCircleY != oldData.innerCircleY or newData.outerCircleX != oldData.outerCircleX or newData.outerCircleY != oldData.outerCircleY or angular.toJson(newData.ColorHandles) != angular.toJson(oldData.ColorHandles) manageLoadedPresetDirty() , true ### Saves currently loaded preset to local storage. @param {Boolean} [saveAs=false] TRUE to force "save as" with a new preset name. ### saveLoadedPreset: (saveAs = false) -> SavedPresets = @$scope.SavedPresets LoadedPreset = angular.extend new @GradientPreset, @$scope.LoadedPreset # Copy data from scope to loaded preset angular.extend LoadedPreset, gradientType: @$scope.gradientType width: @$scope.bigCanvasWidth height: @$scope.bigCanvasHeight rotate: @$scope.rotateDegrees innerCircleX: @$scope.innerCircleX innerCircleY: @$scope.innerCircleY outerCircleX: @$scope.outerCircleX outerCircleY: @$scope.outerCircleY ColorHandles: (angular.extend({}, ColorHandle) for ColorHandle in @$scope.ColorHandles) # Gradient is new or force "save as" if !LoadedPreset.id? or saveAs name = prompt 'Unique name for your preset:', '' name = prompt 'Name already in use. Try another (or cancel to abort):', '' while name isnt null and ( Preset for Preset in SavedPresets when Preset.name == name ).length # Canceled if name is null then return LoadedPreset.id = LoadedPreset.name = name LoadedPreset.saveable = true LoadedPreset.deleteable = true SavedPresets.push LoadedPreset # Non-new else SavedPresets[i] = LoadedPreset for Preset, i in SavedPresets when Preset.id == LoadedPreset.id LoadedPreset.dirty = false # Save LoadedPreset.save() # "Load" back what was just saved @$scope.LoadedPreset = angular.extend new @GradientPreset, LoadedPreset ### Deletes currently loaded preset from local storage. ### deleteLoadedPreset: -> SavedPresets = @$scope.SavedPresets LoadedPreset = angular.extend new @GradientPreset, @$scope.LoadedPreset # Remove our copy for Preset, i in SavedPresets when Preset.id == LoadedPreset?.id SavedPresets.splice i, 1 break # Remove from storage LoadedPreset.delete() # Mark as dirty, saveable, undeleteable, and unsaved angular.extend LoadedPreset, dirty: true saveable: true deleteable: false id: null name: null # Load back into scope @$scope.LoadedPreset = LoadedPreset sortColorHandlesByStop: -> @$scope.ColorHandles.sort (LeftHandle, RightHandle) -> LeftHandle.stop - RightHandle.stop
216082
class window.MainCtrl addHandleDefaultColor: 'rgba(0, 0, 0, 1)' presetDefaults: gradientType: 'linear' width: 300 height: 300 rotate: 0 innerCircleX: 50 innerCircleY: 50 outerCircleX: 50 outerCircleY: 50 constructor: (@$scope, @$document, @ColorHandle, @$filter, @localStorageService, @GradientPreset) -> @$scope.localStorageSupported = @localStorageService.isSupported() @$scope.gradientType = @presetDefaults.gradientType @$scope.bigCanvasWidth = @presetDefaults.width @$scope.bigCanvasHeight = @presetDefaults.height @$scope.rotateDegrees = @presetDefaults.rotate @$scope.innerCircleX = @presetDefaults.innerCircleX @$scope.innerCircleY = @presetDefaults.innerCircleY @$scope.outerCircleX = @presetDefaults.outerCircleX @$scope.outerCircleY = @presetDefaults.outerCircleY @$scope.LoadedPreset = {} @$scope.loading = true $.fn.qtip.defaults.position.my = 'bottom left' $.fn.qtip.defaults.position.at = 'top center' $.fn.qtip.defaults.position.viewport = true $.fn.qtip.defaults.position.adjust.method = 'shift none' $.fn.qtip.defaults.position.adjust.y = -3 $.fn.qtip.defaults.style.classes = 'qtip-jtools' @$scope.presetTooltipOpts = position: my: 'bottom center' # Get saved presets from local storage @$scope.SavedPresets = @GradientPreset.query() # Scope proxy methods @$scope.addColorHandle = => @addColorHandle.apply @, arguments @$scope.deleteColorHandle = => @deleteColorHandle.apply @, arguments @$scope.setActiveColorHandle = => @setActiveColorHandle.apply @, arguments @$scope.getMouseIsDown = => @getMouseIsDown.apply @, arguments @$scope.applyPreset = => @applyPreset.apply @, arguments @$scope.saveLoadedPreset = => @saveLoadedPreset.apply @, arguments @$scope.deleteLoadedPreset = => @deleteLoadedPreset.apply @, arguments @initColorHandles() @trackMouseIsDown() @setUpActiveColorHandleStopManualInput() @compileGradientHtmlPageCode() @initPresets() @manageLoadedPresetDirty() # Auto-show/hide instructions based on color active handle @$scope.$watch 'ActiveColorHandle', (ActiveColorHandle) => @$scope.showInstructions = !ActiveColorHandle? initColorHandles: -> @$scope.ColorHandles = [ new @ColorHandle('rgba(0, 0, 0, 1)', 0) new @ColorHandle('rgba(255, 255, 255, 1)', 1) ] @setActiveColorHandle null # ColorHandles stop change @$scope.$watch (=> (CH.stop for CH in @$scope.ColorHandles)), => # Resort by stop @sortColorHandlesByStop() , true ### Adds a new color handle. @param {Number} stop New color handle's desired stop. ### addColorHandle: (stop) -> NewHandle = new @ColorHandle @addHandleDefaultColor, stop NewHandle.forceDrag = true @$scope.ColorHandles.push NewHandle # Sort by stop @sortColorHandlesByStop() ### @param {Object} DeleteColorHandle Handle to delete. @return {Boolean} TRUE if the handle was deleted (last handle is never deleted; will return FALSE). ### deleteColorHandle: (DeleteColorHandle) -> # OK to delete (not last handle) deleted = @$scope.ColorHandles.length > 1 if deleted # Sort handles by stop @sortColorHandlesByStop() # Handle to delete is active handle if DeleteColorHandle == @$scope.ActiveColorHandle # Set active handle to next handle, or previous handle if next handle was last handle for ColorHandle, i in @$scope.ColorHandles if ColorHandle == DeleteColorHandle @$scope.setActiveColorHandle @$scope.ColorHandles[i + 1] ? @$scope.ColorHandles[i - 1] break # Delete handle @$scope.ColorHandles = (ColorHandle for ColorHandle in @$scope.ColorHandles when ColorHandle isnt DeleteColorHandle) deleted ### The "active" color handle is the one whose color is loaded into the color picker. @param {Object} ColorHandle Handle to set as active. ### setActiveColorHandle: (ColorHandle) -> @$scope.ActiveColorHandle = ColorHandle ### Keeps @$scope.mouseIsDown up to date. @see getMouseIsDown() ### trackMouseIsDown: -> @$scope.mouseIsDown = false @$document.mousedown => @$scope.mouseIsDown = true @$document.mouseup => @$scope.mouseIsDown = false ### @return {Boolean} TRUE if mouse is currently down, FALSE if it is up. ### getMouseIsDown: -> @$scope.mouseIsDown ### Keeps active color handle stop and manual input in sync. ### setUpActiveColorHandleStopManualInput: -> numberFilter = @$filter 'number' # Keep input up to date with handle @$scope.$watch 'ActiveColorHandle.stop', (stop) => if stop? then @$scope.activeColorHandleStopPercent = parseFloat(numberFilter(stop * 100, 1).replace(/,/g, '')) # Keep handle up to date with input @$scope.$watch 'activeColorHandleStopPercent', (percent) => if percent? then @$scope.ActiveColorHandle.stop = percent / 100 ### Watches HTML and JS code bits from previewCanvas directive and compiles final full page code. ### compileGradientHtmlPageCode: -> # Watch gradient code parts @$scope.$watch => html: @$scope.gradientHtmlCode ? '' js: @$scope.gradientJsCode ? '' dirty: @$scope.LoadedPreset?.dirty , (codeParts) => # Get HTML escaped gradient preset name (or default name) gradientNameHtml = if @$scope.LoadedPreset.name? jQuery('<p />').text(@$scope.LoadedPreset.name).html() + if @$scope.LoadedPreset.dirty then ' (modified)' else '' else 'Ermahgerd, a gradient' @$scope.gradientHtmlPageCode = """ <!doctype html> <html> <head> <meta charset="UTF-8"> <title>#{gradientNameHtml}</title> </head> <body> #{codeParts.html} <script type="text/javascript"> #{codeParts.js.replace /\n/g, '\n '} </script> </body> </html> """ , true ### Init gradient presets. ### initPresets: -> @$scope.Presets = [ angular.extend new @GradientPreset, @presetDefaults, id: 'Black → transparent' name: 'Black → transparent' ColorHandles: [ new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.00 new @ColorHandle 'rgba(0, 0, 0, 0.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'White → transparent' name: 'White → transparent' ColorHandles: [ new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.00 new @ColorHandle 'rgba(255, 255, 255, 0.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Red → green' name: 'Red → green' ColorHandles: [ new @ColorHandle 'rgba(225, 0, 25, 1.00)', 0.00 new @ColorHandle 'rgba(0, 96, 27, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Violet → orange' name: 'Violet → orange' ColorHandles: [ new @ColorHandle 'rgba(41, 10, 89, 1.00)', 0.00 new @ColorHandle 'rgba(255, 124, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Blue → red → yellow' name: 'Blue → red → yellow' ColorHandles: [ new @ColorHandle 'rgba(10, 0, 178, 1.00)', 0.00 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.50 new @ColorHandle 'rgba(255, 252, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Blue → yellow → blue' name: 'Blue → yellow → blue' ColorHandles: [ new @ColorHandle 'rgba(11, 1, 184, 1.00)', 0.10 new @ColorHandle 'rgba(253, 250, 3, 1.00)', 0.50 new @ColorHandle 'rgba(11, 2, 170, 1.00)', 0.90 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Orange → yellow → orange' name: 'Orange → yellow → orange' ColorHandles: [ new @ColorHandle 'rgba(255, 110, 2, 1.00)', 0.00 new @ColorHandle 'rgba(255, 255, 0, 1.00)', 0.50 new @ColorHandle 'rgba(255, 109, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Violet → green → orange' name: 'Violet → green → orange' ColorHandles: [ new @ColorHandle 'rgba(111, 21, 108, 1.00)', 0.00 new @ColorHandle 'rgba(0, 96, 27, 1.00)', 0.50 new @ColorHandle 'rgba(253, 124, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Yellow → violet → orange → blue' name: 'Yellow → violet → orange → blue' ColorHandles: [ new @ColorHandle 'rgba(249, 230, 0, 1.00)', 0.05 new @ColorHandle 'rgba(111, 21, 108, 1.00)', 0.35 new @ColorHandle 'rgba(253, 124, 0, 1.00)', 0.65 new @ColorHandle 'rgba(0, 40, 116, 1.00)', 0.95 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Copper' name: '<NAME>' ColorHandles: [ new @ColorHandle 'rgba(151, 70, 26, 1.00)', 0.00 new @ColorHandle 'rgba(251, 216, 197, 1.00)', 0.30 new @ColorHandle 'rgba(108, 46, 22, 1.00)', 0.83 new @ColorHandle 'rgba(239, 219, 205, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Chrome' name: 'Chrome' ColorHandles: [ new @ColorHandle 'rgba(41, 137, 204, 1.00)', 0.00 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.50 new @ColorHandle 'rgba(144, 106, 0, 1.00)', 0.52 new @ColorHandle 'rgba(217, 159, 0, 1.00)', 0.64 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Spectrum' name: 'Spectrum' ColorHandles: [ new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.00 new @ColorHandle 'rgba(255, 0, 255, 1.00)', 0.15 new @ColorHandle 'rgba(0, 0, 255, 1.00)', 0.33 new @ColorHandle 'rgba(0, 255, 255, 1.00)', 0.49 new @ColorHandle 'rgba(0, 255, 0, 1.00)', 0.67 new @ColorHandle 'rgba(255, 255, 0, 1.00)', 0.84 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Rainbow' name: '<NAME>bow' ColorHandles: [ new @ColorHandle 'rgba(255, 0, 0, 0.00)', 0.15 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.20 new @ColorHandle 'rgba(255, 252, 0, 1.00)', 0.32 new @ColorHandle 'rgba(1, 180, 57, 1.00)', 0.44 new @ColorHandle 'rgba(0, 234, 255, 1.00)', 0.56 new @ColorHandle 'rgba(0, 3, 144, 1.00)', 0.68 new @ColorHandle 'rgba(255, 0, 198, 1.00)', 0.80 new @ColorHandle 'rgba(255, 0, 198, 0.00)', 0.85 ] ] @$scope.FunPresets = [ angular.extend new @GradientPreset, @presetDefaults, id: 'Solar eclipse' name: 'Solar eclipse' gradientType: 'radial' innerCircleX: 45 innerCircleY: 45 outerCircleX: 45 outerCircleY: 45 ColorHandles: [ new @ColorHandle 'rgba(34, 10, 10, 1.00)', 0.00 new @ColorHandle 'rgba(34, 10, 10, 1.00)', 0.33 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.34 new @ColorHandle 'rgba(234, 189, 12, 1.00)', 0.60 new @ColorHandle 'rgba(35, 1, 4, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Eyeball' name: '<NAME>eball' gradientType: 'radial' innerCircleX: 51 innerCircleY: 63.3 outerCircleY: 49 ColorHandles: [ new @ColorHandle 'rgba(14, 14, 16, 1.00)', 0.00 new @ColorHandle 'rgba(14, 14, 16, 1.00)', 0.17 new @ColorHandle 'rgba(75, 93, 103, 1.00)', 0.61 new @ColorHandle 'rgba(96, 109, 91, 1.00)', 0.27 new @ColorHandle 'rgba(75, 93, 103, 1.00)', 0.62 new @ColorHandle 'rgba(255, 250, 250, 1.00)', 0.69 new @ColorHandle 'rgba(255, 250, 250, 1.00)', 0.92 new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.93 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.94 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Bullseye' name: '<NAME>' gradientType: 'radial' ColorHandles: [ new @ColorHandle 'rgba(255, 238, 40, 1.00)', 0.00 new @ColorHandle 'rgba(255, 238, 40, 1.00)', 0.20 new @ColorHandle 'rgba(194, 66, 57, 1.00)', 0.21 new @ColorHandle 'rgba(194, 66, 57, 1.00)', 0.40 new @ColorHandle 'rgba(130, 194, 238, 1.00)', 0.41 new @ColorHandle 'rgba(130, 194, 238, 1.00)', 0.60 new @ColorHandle 'rgba(254, 254, 254, 1.00)', 0.61 new @ColorHandle 'rgba(254, 254, 254, 1.00)', 0.78 new @ColorHandle 'rgba(52, 50, 51, 1.00)', 0.79 new @ColorHandle 'rgba(52, 50, 51, 1.00)', 0.99 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Breakfast' name: '<NAME>' gradientType: 'radial' width: 320 height: 404 innerCircleY: 89.1 outerCircleY: 47.5 ColorHandles: [ new @ColorHandle 'rgba(255, 153, 0, 1.00)', 0.00 new @ColorHandle 'rgba(255, 191, 0, 1.00)', 0.46 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.49 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.86 new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.85 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.84 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Sunset' name: 'Sunset' gradientType: 'radial' innerCircleX: 60 innerCircleY: 100 outerCircleX: 60 outerCircleY: 100 ColorHandles: [ new @ColorHandle 'rgba(255, 242, 0, 1.00)', 0.00 new @ColorHandle 'rgba(255, 157, 0, 1.00)', 0.37 new @ColorHandle 'rgba(47, 32, 163, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Oui oui' name: 'Oui oui' gradientType: 'linear' width: 300 height: 200 ColorHandles: [ new @ColorHandle 'rgba(0, 85, 164, 1.00)', 0.00 new @ColorHandle 'rgba(0, 85, 164, 1.00)', 0.33 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.331 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.66 new @ColorHandle 'rgba(250, 60, 50, 1.00)', 0.661 new @ColorHandle 'rgba(250, 60, 50, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: '<NAME>' name: '<NAME>' gradientType: 'linear' width: 300 height: 200 ColorHandles: [ new @ColorHandle 'rgba(0, 146, 70, 1.00)', 0.00 new @ColorHandle 'rgba(0, 146, 70, 1.00)', 0.33 new @ColorHandle 'rgba(241, 242, 241, 1.00)', 0.331 new @ColorHandle 'rgba(241, 242, 241, 1.00)', 0.66 new @ColorHandle 'rgba(206, 43, 55, 1.00)', 0.661 new @ColorHandle 'rgba(206, 43, 55, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: '<NAME>' name: '<NAME>' gradientType: 'linear' rotate: 90 width: 300 height: 200 ColorHandles: [ new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.00 new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.5 new @ColorHandle 'rgba(0, 56, 147, 1.00)', 0.501 new @ColorHandle 'rgba(0, 56, 147, 1.00)', 0.75 new @ColorHandle 'rgba(206, 17, 38, 1.00)', 0.751 new @ColorHandle 'rgba(206, 17, 38, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Genau' name: '<NAME>' gradientType: 'linear' rotate: 90 width: 300 height: 180 ColorHandles: [ new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.00 new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.33 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.331 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.69 new @ColorHandle 'rgba(255, 204, 0, 1.00)', 0.691 new @ColorHandle 'rgba(255, 204, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: '<NAME>ивет' name: '<NAME>' gradientType: 'linear' rotate: 90 width: 300 height: 200 ColorHandles: [ new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.00 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.33 new @ColorHandle 'rgba(0, 0, 255, 1.00)', 0.331 new @ColorHandle 'rgba(0, 0, 255, 1.00)', 0.69 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.691 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: '<NAME>' name: '<NAME>' gradientType: 'linear' rotate: 71 width: 300 height: 200 ColorHandles: [ new @ColorHandle 'rgba(30, 181, 58, 1.00)', 0.00 new @ColorHandle 'rgba(30, 181, 58, 1.00)', 0.35 new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.351 new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.4 new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.401 new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.6 new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.601 new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.65 new @ColorHandle 'rgba(0, 163, 221, 1.00)', 0.651 new @ColorHandle 'rgba(0, 163, 221, 1.00)', 1.00 ] ] ### Apply preset gradient to working area. @param {GradientPreset} Preset ### applyPreset: (Preset) -> # Deep clone so updates in the working area don't immediately affect the preset Preset = Preset.clone() @$scope.gradientType = Preset.gradientType @$scope.bigCanvasWidth = Preset.width @$scope.bigCanvasHeight = Preset.height @$scope.rotateDegrees = Preset.rotate @$scope.innerCircleX = Preset.innerCircleX @$scope.innerCircleY = Preset.innerCircleY @$scope.outerCircleX = Preset.outerCircleX @$scope.outerCircleY = Preset.outerCircleY @$scope.ColorHandles = Preset.ColorHandles @$scope.ActiveColorHandle = null @$scope.LoadedPreset = Preset @$scope.LoadedPreset.initialChange = true ### Marks loaded preset as dirty as appropriate. ### manageLoadedPresetDirty: -> # Marks loaded preset dirty under certain conditions... manageLoadedPresetDirty = => # 1. There actually is a loaded preset # 2. The data watch fired wasn't the "initial change" if @$scope.LoadedPreset? and !@$scope.LoadedPreset.initialChange @$scope.LoadedPreset.dirty = true else @$scope.LoadedPreset.initialChange = false # Watch data that should dirtify @$scope.$watch => gradientType: @$scope.gradientType width: @$scope.bigCanvasWidth height: @$scope.bigCanvasHeight rotate: @$scope.rotateDegrees innerCircleX: @$scope.innerCircleX innerCircleY: @$scope.innerCircleY outerCircleX: @$scope.outerCircleX outerCircleY: @$scope.outerCircleY ColorHandles: @$scope.ColorHandles , (newData, oldData) -> # Some data actually changed if typeof newData != typeof oldData or newData.gradientType != oldData.gradientType or newData.width != oldData.width or newData.height != oldData.height or newData.rotate != oldData.rotate or newData.innerCircleX != oldData.innerCircleX or newData.innerCircleY != oldData.innerCircleY or newData.outerCircleX != oldData.outerCircleX or newData.outerCircleY != oldData.outerCircleY or angular.toJson(newData.ColorHandles) != angular.toJson(oldData.ColorHandles) manageLoadedPresetDirty() , true ### Saves currently loaded preset to local storage. @param {Boolean} [saveAs=false] TRUE to force "save as" with a new preset name. ### saveLoadedPreset: (saveAs = false) -> SavedPresets = @$scope.SavedPresets LoadedPreset = angular.extend new @GradientPreset, @$scope.LoadedPreset # Copy data from scope to loaded preset angular.extend LoadedPreset, gradientType: @$scope.gradientType width: @$scope.bigCanvasWidth height: @$scope.bigCanvasHeight rotate: @$scope.rotateDegrees innerCircleX: @$scope.innerCircleX innerCircleY: @$scope.innerCircleY outerCircleX: @$scope.outerCircleX outerCircleY: @$scope.outerCircleY ColorHandles: (angular.extend({}, ColorHandle) for ColorHandle in @$scope.ColorHandles) # Gradient is new or force "save as" if !LoadedPreset.id? or saveAs name = prompt 'Unique name for your preset:', '' name = prompt 'Name already in use. Try another (or cancel to abort):', '' while name isnt null and ( Preset for Preset in SavedPresets when Preset.name == name ).length # Canceled if name is null then return LoadedPreset.id = LoadedPreset.name = name LoadedPreset.saveable = true LoadedPreset.deleteable = true SavedPresets.push LoadedPreset # Non-new else SavedPresets[i] = LoadedPreset for Preset, i in SavedPresets when Preset.id == LoadedPreset.id LoadedPreset.dirty = false # Save LoadedPreset.save() # "Load" back what was just saved @$scope.LoadedPreset = angular.extend new @GradientPreset, LoadedPreset ### Deletes currently loaded preset from local storage. ### deleteLoadedPreset: -> SavedPresets = @$scope.SavedPresets LoadedPreset = angular.extend new @GradientPreset, @$scope.LoadedPreset # Remove our copy for Preset, i in SavedPresets when Preset.id == LoadedPreset?.id SavedPresets.splice i, 1 break # Remove from storage LoadedPreset.delete() # Mark as dirty, saveable, undeleteable, and unsaved angular.extend LoadedPreset, dirty: true saveable: true deleteable: false id: null name: null # Load back into scope @$scope.LoadedPreset = LoadedPreset sortColorHandlesByStop: -> @$scope.ColorHandles.sort (LeftHandle, RightHandle) -> LeftHandle.stop - RightHandle.stop
true
class window.MainCtrl addHandleDefaultColor: 'rgba(0, 0, 0, 1)' presetDefaults: gradientType: 'linear' width: 300 height: 300 rotate: 0 innerCircleX: 50 innerCircleY: 50 outerCircleX: 50 outerCircleY: 50 constructor: (@$scope, @$document, @ColorHandle, @$filter, @localStorageService, @GradientPreset) -> @$scope.localStorageSupported = @localStorageService.isSupported() @$scope.gradientType = @presetDefaults.gradientType @$scope.bigCanvasWidth = @presetDefaults.width @$scope.bigCanvasHeight = @presetDefaults.height @$scope.rotateDegrees = @presetDefaults.rotate @$scope.innerCircleX = @presetDefaults.innerCircleX @$scope.innerCircleY = @presetDefaults.innerCircleY @$scope.outerCircleX = @presetDefaults.outerCircleX @$scope.outerCircleY = @presetDefaults.outerCircleY @$scope.LoadedPreset = {} @$scope.loading = true $.fn.qtip.defaults.position.my = 'bottom left' $.fn.qtip.defaults.position.at = 'top center' $.fn.qtip.defaults.position.viewport = true $.fn.qtip.defaults.position.adjust.method = 'shift none' $.fn.qtip.defaults.position.adjust.y = -3 $.fn.qtip.defaults.style.classes = 'qtip-jtools' @$scope.presetTooltipOpts = position: my: 'bottom center' # Get saved presets from local storage @$scope.SavedPresets = @GradientPreset.query() # Scope proxy methods @$scope.addColorHandle = => @addColorHandle.apply @, arguments @$scope.deleteColorHandle = => @deleteColorHandle.apply @, arguments @$scope.setActiveColorHandle = => @setActiveColorHandle.apply @, arguments @$scope.getMouseIsDown = => @getMouseIsDown.apply @, arguments @$scope.applyPreset = => @applyPreset.apply @, arguments @$scope.saveLoadedPreset = => @saveLoadedPreset.apply @, arguments @$scope.deleteLoadedPreset = => @deleteLoadedPreset.apply @, arguments @initColorHandles() @trackMouseIsDown() @setUpActiveColorHandleStopManualInput() @compileGradientHtmlPageCode() @initPresets() @manageLoadedPresetDirty() # Auto-show/hide instructions based on color active handle @$scope.$watch 'ActiveColorHandle', (ActiveColorHandle) => @$scope.showInstructions = !ActiveColorHandle? initColorHandles: -> @$scope.ColorHandles = [ new @ColorHandle('rgba(0, 0, 0, 1)', 0) new @ColorHandle('rgba(255, 255, 255, 1)', 1) ] @setActiveColorHandle null # ColorHandles stop change @$scope.$watch (=> (CH.stop for CH in @$scope.ColorHandles)), => # Resort by stop @sortColorHandlesByStop() , true ### Adds a new color handle. @param {Number} stop New color handle's desired stop. ### addColorHandle: (stop) -> NewHandle = new @ColorHandle @addHandleDefaultColor, stop NewHandle.forceDrag = true @$scope.ColorHandles.push NewHandle # Sort by stop @sortColorHandlesByStop() ### @param {Object} DeleteColorHandle Handle to delete. @return {Boolean} TRUE if the handle was deleted (last handle is never deleted; will return FALSE). ### deleteColorHandle: (DeleteColorHandle) -> # OK to delete (not last handle) deleted = @$scope.ColorHandles.length > 1 if deleted # Sort handles by stop @sortColorHandlesByStop() # Handle to delete is active handle if DeleteColorHandle == @$scope.ActiveColorHandle # Set active handle to next handle, or previous handle if next handle was last handle for ColorHandle, i in @$scope.ColorHandles if ColorHandle == DeleteColorHandle @$scope.setActiveColorHandle @$scope.ColorHandles[i + 1] ? @$scope.ColorHandles[i - 1] break # Delete handle @$scope.ColorHandles = (ColorHandle for ColorHandle in @$scope.ColorHandles when ColorHandle isnt DeleteColorHandle) deleted ### The "active" color handle is the one whose color is loaded into the color picker. @param {Object} ColorHandle Handle to set as active. ### setActiveColorHandle: (ColorHandle) -> @$scope.ActiveColorHandle = ColorHandle ### Keeps @$scope.mouseIsDown up to date. @see getMouseIsDown() ### trackMouseIsDown: -> @$scope.mouseIsDown = false @$document.mousedown => @$scope.mouseIsDown = true @$document.mouseup => @$scope.mouseIsDown = false ### @return {Boolean} TRUE if mouse is currently down, FALSE if it is up. ### getMouseIsDown: -> @$scope.mouseIsDown ### Keeps active color handle stop and manual input in sync. ### setUpActiveColorHandleStopManualInput: -> numberFilter = @$filter 'number' # Keep input up to date with handle @$scope.$watch 'ActiveColorHandle.stop', (stop) => if stop? then @$scope.activeColorHandleStopPercent = parseFloat(numberFilter(stop * 100, 1).replace(/,/g, '')) # Keep handle up to date with input @$scope.$watch 'activeColorHandleStopPercent', (percent) => if percent? then @$scope.ActiveColorHandle.stop = percent / 100 ### Watches HTML and JS code bits from previewCanvas directive and compiles final full page code. ### compileGradientHtmlPageCode: -> # Watch gradient code parts @$scope.$watch => html: @$scope.gradientHtmlCode ? '' js: @$scope.gradientJsCode ? '' dirty: @$scope.LoadedPreset?.dirty , (codeParts) => # Get HTML escaped gradient preset name (or default name) gradientNameHtml = if @$scope.LoadedPreset.name? jQuery('<p />').text(@$scope.LoadedPreset.name).html() + if @$scope.LoadedPreset.dirty then ' (modified)' else '' else 'Ermahgerd, a gradient' @$scope.gradientHtmlPageCode = """ <!doctype html> <html> <head> <meta charset="UTF-8"> <title>#{gradientNameHtml}</title> </head> <body> #{codeParts.html} <script type="text/javascript"> #{codeParts.js.replace /\n/g, '\n '} </script> </body> </html> """ , true ### Init gradient presets. ### initPresets: -> @$scope.Presets = [ angular.extend new @GradientPreset, @presetDefaults, id: 'Black → transparent' name: 'Black → transparent' ColorHandles: [ new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.00 new @ColorHandle 'rgba(0, 0, 0, 0.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'White → transparent' name: 'White → transparent' ColorHandles: [ new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.00 new @ColorHandle 'rgba(255, 255, 255, 0.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Red → green' name: 'Red → green' ColorHandles: [ new @ColorHandle 'rgba(225, 0, 25, 1.00)', 0.00 new @ColorHandle 'rgba(0, 96, 27, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Violet → orange' name: 'Violet → orange' ColorHandles: [ new @ColorHandle 'rgba(41, 10, 89, 1.00)', 0.00 new @ColorHandle 'rgba(255, 124, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Blue → red → yellow' name: 'Blue → red → yellow' ColorHandles: [ new @ColorHandle 'rgba(10, 0, 178, 1.00)', 0.00 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.50 new @ColorHandle 'rgba(255, 252, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Blue → yellow → blue' name: 'Blue → yellow → blue' ColorHandles: [ new @ColorHandle 'rgba(11, 1, 184, 1.00)', 0.10 new @ColorHandle 'rgba(253, 250, 3, 1.00)', 0.50 new @ColorHandle 'rgba(11, 2, 170, 1.00)', 0.90 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Orange → yellow → orange' name: 'Orange → yellow → orange' ColorHandles: [ new @ColorHandle 'rgba(255, 110, 2, 1.00)', 0.00 new @ColorHandle 'rgba(255, 255, 0, 1.00)', 0.50 new @ColorHandle 'rgba(255, 109, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Violet → green → orange' name: 'Violet → green → orange' ColorHandles: [ new @ColorHandle 'rgba(111, 21, 108, 1.00)', 0.00 new @ColorHandle 'rgba(0, 96, 27, 1.00)', 0.50 new @ColorHandle 'rgba(253, 124, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Yellow → violet → orange → blue' name: 'Yellow → violet → orange → blue' ColorHandles: [ new @ColorHandle 'rgba(249, 230, 0, 1.00)', 0.05 new @ColorHandle 'rgba(111, 21, 108, 1.00)', 0.35 new @ColorHandle 'rgba(253, 124, 0, 1.00)', 0.65 new @ColorHandle 'rgba(0, 40, 116, 1.00)', 0.95 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Copper' name: 'PI:NAME:<NAME>END_PI' ColorHandles: [ new @ColorHandle 'rgba(151, 70, 26, 1.00)', 0.00 new @ColorHandle 'rgba(251, 216, 197, 1.00)', 0.30 new @ColorHandle 'rgba(108, 46, 22, 1.00)', 0.83 new @ColorHandle 'rgba(239, 219, 205, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Chrome' name: 'Chrome' ColorHandles: [ new @ColorHandle 'rgba(41, 137, 204, 1.00)', 0.00 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.50 new @ColorHandle 'rgba(144, 106, 0, 1.00)', 0.52 new @ColorHandle 'rgba(217, 159, 0, 1.00)', 0.64 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Spectrum' name: 'Spectrum' ColorHandles: [ new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.00 new @ColorHandle 'rgba(255, 0, 255, 1.00)', 0.15 new @ColorHandle 'rgba(0, 0, 255, 1.00)', 0.33 new @ColorHandle 'rgba(0, 255, 255, 1.00)', 0.49 new @ColorHandle 'rgba(0, 255, 0, 1.00)', 0.67 new @ColorHandle 'rgba(255, 255, 0, 1.00)', 0.84 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Rainbow' name: 'PI:NAME:<NAME>END_PIbow' ColorHandles: [ new @ColorHandle 'rgba(255, 0, 0, 0.00)', 0.15 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.20 new @ColorHandle 'rgba(255, 252, 0, 1.00)', 0.32 new @ColorHandle 'rgba(1, 180, 57, 1.00)', 0.44 new @ColorHandle 'rgba(0, 234, 255, 1.00)', 0.56 new @ColorHandle 'rgba(0, 3, 144, 1.00)', 0.68 new @ColorHandle 'rgba(255, 0, 198, 1.00)', 0.80 new @ColorHandle 'rgba(255, 0, 198, 0.00)', 0.85 ] ] @$scope.FunPresets = [ angular.extend new @GradientPreset, @presetDefaults, id: 'Solar eclipse' name: 'Solar eclipse' gradientType: 'radial' innerCircleX: 45 innerCircleY: 45 outerCircleX: 45 outerCircleY: 45 ColorHandles: [ new @ColorHandle 'rgba(34, 10, 10, 1.00)', 0.00 new @ColorHandle 'rgba(34, 10, 10, 1.00)', 0.33 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.34 new @ColorHandle 'rgba(234, 189, 12, 1.00)', 0.60 new @ColorHandle 'rgba(35, 1, 4, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Eyeball' name: 'PI:NAME:<NAME>END_PIeball' gradientType: 'radial' innerCircleX: 51 innerCircleY: 63.3 outerCircleY: 49 ColorHandles: [ new @ColorHandle 'rgba(14, 14, 16, 1.00)', 0.00 new @ColorHandle 'rgba(14, 14, 16, 1.00)', 0.17 new @ColorHandle 'rgba(75, 93, 103, 1.00)', 0.61 new @ColorHandle 'rgba(96, 109, 91, 1.00)', 0.27 new @ColorHandle 'rgba(75, 93, 103, 1.00)', 0.62 new @ColorHandle 'rgba(255, 250, 250, 1.00)', 0.69 new @ColorHandle 'rgba(255, 250, 250, 1.00)', 0.92 new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.93 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.94 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Bullseye' name: 'PI:NAME:<NAME>END_PI' gradientType: 'radial' ColorHandles: [ new @ColorHandle 'rgba(255, 238, 40, 1.00)', 0.00 new @ColorHandle 'rgba(255, 238, 40, 1.00)', 0.20 new @ColorHandle 'rgba(194, 66, 57, 1.00)', 0.21 new @ColorHandle 'rgba(194, 66, 57, 1.00)', 0.40 new @ColorHandle 'rgba(130, 194, 238, 1.00)', 0.41 new @ColorHandle 'rgba(130, 194, 238, 1.00)', 0.60 new @ColorHandle 'rgba(254, 254, 254, 1.00)', 0.61 new @ColorHandle 'rgba(254, 254, 254, 1.00)', 0.78 new @ColorHandle 'rgba(52, 50, 51, 1.00)', 0.79 new @ColorHandle 'rgba(52, 50, 51, 1.00)', 0.99 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Breakfast' name: 'PI:NAME:<NAME>END_PI' gradientType: 'radial' width: 320 height: 404 innerCircleY: 89.1 outerCircleY: 47.5 ColorHandles: [ new @ColorHandle 'rgba(255, 153, 0, 1.00)', 0.00 new @ColorHandle 'rgba(255, 191, 0, 1.00)', 0.46 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.49 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.86 new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.85 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.84 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Sunset' name: 'Sunset' gradientType: 'radial' innerCircleX: 60 innerCircleY: 100 outerCircleX: 60 outerCircleY: 100 ColorHandles: [ new @ColorHandle 'rgba(255, 242, 0, 1.00)', 0.00 new @ColorHandle 'rgba(255, 157, 0, 1.00)', 0.37 new @ColorHandle 'rgba(47, 32, 163, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Oui oui' name: 'Oui oui' gradientType: 'linear' width: 300 height: 200 ColorHandles: [ new @ColorHandle 'rgba(0, 85, 164, 1.00)', 0.00 new @ColorHandle 'rgba(0, 85, 164, 1.00)', 0.33 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.331 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.66 new @ColorHandle 'rgba(250, 60, 50, 1.00)', 0.661 new @ColorHandle 'rgba(250, 60, 50, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'PI:NAME:<NAME>END_PI' name: 'PI:NAME:<NAME>END_PI' gradientType: 'linear' width: 300 height: 200 ColorHandles: [ new @ColorHandle 'rgba(0, 146, 70, 1.00)', 0.00 new @ColorHandle 'rgba(0, 146, 70, 1.00)', 0.33 new @ColorHandle 'rgba(241, 242, 241, 1.00)', 0.331 new @ColorHandle 'rgba(241, 242, 241, 1.00)', 0.66 new @ColorHandle 'rgba(206, 43, 55, 1.00)', 0.661 new @ColorHandle 'rgba(206, 43, 55, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'PI:NAME:<NAME>END_PI' name: 'PI:NAME:<NAME>END_PI' gradientType: 'linear' rotate: 90 width: 300 height: 200 ColorHandles: [ new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.00 new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.5 new @ColorHandle 'rgba(0, 56, 147, 1.00)', 0.501 new @ColorHandle 'rgba(0, 56, 147, 1.00)', 0.75 new @ColorHandle 'rgba(206, 17, 38, 1.00)', 0.751 new @ColorHandle 'rgba(206, 17, 38, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'Genau' name: 'PI:NAME:<NAME>END_PI' gradientType: 'linear' rotate: 90 width: 300 height: 180 ColorHandles: [ new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.00 new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.33 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.331 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.69 new @ColorHandle 'rgba(255, 204, 0, 1.00)', 0.691 new @ColorHandle 'rgba(255, 204, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'PI:NAME:<NAME>END_PIивет' name: 'PI:NAME:<NAME>END_PI' gradientType: 'linear' rotate: 90 width: 300 height: 200 ColorHandles: [ new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.00 new @ColorHandle 'rgba(255, 255, 255, 1.00)', 0.33 new @ColorHandle 'rgba(0, 0, 255, 1.00)', 0.331 new @ColorHandle 'rgba(0, 0, 255, 1.00)', 0.69 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 0.691 new @ColorHandle 'rgba(255, 0, 0, 1.00)', 1.00 ] angular.extend new @GradientPreset, @presetDefaults, id: 'PI:NAME:<NAME>END_PI' name: 'PI:NAME:<NAME>END_PI' gradientType: 'linear' rotate: 71 width: 300 height: 200 ColorHandles: [ new @ColorHandle 'rgba(30, 181, 58, 1.00)', 0.00 new @ColorHandle 'rgba(30, 181, 58, 1.00)', 0.35 new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.351 new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.4 new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.401 new @ColorHandle 'rgba(0, 0, 0, 1.00)', 0.6 new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.601 new @ColorHandle 'rgba(252, 209, 22, 1.00)', 0.65 new @ColorHandle 'rgba(0, 163, 221, 1.00)', 0.651 new @ColorHandle 'rgba(0, 163, 221, 1.00)', 1.00 ] ] ### Apply preset gradient to working area. @param {GradientPreset} Preset ### applyPreset: (Preset) -> # Deep clone so updates in the working area don't immediately affect the preset Preset = Preset.clone() @$scope.gradientType = Preset.gradientType @$scope.bigCanvasWidth = Preset.width @$scope.bigCanvasHeight = Preset.height @$scope.rotateDegrees = Preset.rotate @$scope.innerCircleX = Preset.innerCircleX @$scope.innerCircleY = Preset.innerCircleY @$scope.outerCircleX = Preset.outerCircleX @$scope.outerCircleY = Preset.outerCircleY @$scope.ColorHandles = Preset.ColorHandles @$scope.ActiveColorHandle = null @$scope.LoadedPreset = Preset @$scope.LoadedPreset.initialChange = true ### Marks loaded preset as dirty as appropriate. ### manageLoadedPresetDirty: -> # Marks loaded preset dirty under certain conditions... manageLoadedPresetDirty = => # 1. There actually is a loaded preset # 2. The data watch fired wasn't the "initial change" if @$scope.LoadedPreset? and !@$scope.LoadedPreset.initialChange @$scope.LoadedPreset.dirty = true else @$scope.LoadedPreset.initialChange = false # Watch data that should dirtify @$scope.$watch => gradientType: @$scope.gradientType width: @$scope.bigCanvasWidth height: @$scope.bigCanvasHeight rotate: @$scope.rotateDegrees innerCircleX: @$scope.innerCircleX innerCircleY: @$scope.innerCircleY outerCircleX: @$scope.outerCircleX outerCircleY: @$scope.outerCircleY ColorHandles: @$scope.ColorHandles , (newData, oldData) -> # Some data actually changed if typeof newData != typeof oldData or newData.gradientType != oldData.gradientType or newData.width != oldData.width or newData.height != oldData.height or newData.rotate != oldData.rotate or newData.innerCircleX != oldData.innerCircleX or newData.innerCircleY != oldData.innerCircleY or newData.outerCircleX != oldData.outerCircleX or newData.outerCircleY != oldData.outerCircleY or angular.toJson(newData.ColorHandles) != angular.toJson(oldData.ColorHandles) manageLoadedPresetDirty() , true ### Saves currently loaded preset to local storage. @param {Boolean} [saveAs=false] TRUE to force "save as" with a new preset name. ### saveLoadedPreset: (saveAs = false) -> SavedPresets = @$scope.SavedPresets LoadedPreset = angular.extend new @GradientPreset, @$scope.LoadedPreset # Copy data from scope to loaded preset angular.extend LoadedPreset, gradientType: @$scope.gradientType width: @$scope.bigCanvasWidth height: @$scope.bigCanvasHeight rotate: @$scope.rotateDegrees innerCircleX: @$scope.innerCircleX innerCircleY: @$scope.innerCircleY outerCircleX: @$scope.outerCircleX outerCircleY: @$scope.outerCircleY ColorHandles: (angular.extend({}, ColorHandle) for ColorHandle in @$scope.ColorHandles) # Gradient is new or force "save as" if !LoadedPreset.id? or saveAs name = prompt 'Unique name for your preset:', '' name = prompt 'Name already in use. Try another (or cancel to abort):', '' while name isnt null and ( Preset for Preset in SavedPresets when Preset.name == name ).length # Canceled if name is null then return LoadedPreset.id = LoadedPreset.name = name LoadedPreset.saveable = true LoadedPreset.deleteable = true SavedPresets.push LoadedPreset # Non-new else SavedPresets[i] = LoadedPreset for Preset, i in SavedPresets when Preset.id == LoadedPreset.id LoadedPreset.dirty = false # Save LoadedPreset.save() # "Load" back what was just saved @$scope.LoadedPreset = angular.extend new @GradientPreset, LoadedPreset ### Deletes currently loaded preset from local storage. ### deleteLoadedPreset: -> SavedPresets = @$scope.SavedPresets LoadedPreset = angular.extend new @GradientPreset, @$scope.LoadedPreset # Remove our copy for Preset, i in SavedPresets when Preset.id == LoadedPreset?.id SavedPresets.splice i, 1 break # Remove from storage LoadedPreset.delete() # Mark as dirty, saveable, undeleteable, and unsaved angular.extend LoadedPreset, dirty: true saveable: true deleteable: false id: null name: null # Load back into scope @$scope.LoadedPreset = LoadedPreset sortColorHandlesByStop: -> @$scope.ColorHandles.sort (LeftHandle, RightHandle) -> LeftHandle.stop - RightHandle.stop
[ { "context": "revent you from fleeing from combat.\n *\n * @name Brave\n * @prerequisite Flee combat once\n * @effect -1", "end": 141, "score": 0.9895156621932983, "start": 136, "tag": "NAME", "value": "Brave" } ]
src/character/personalities/Brave.coffee
sadbear-/IdleLands
3
Personality = require "../base/Personality" `/** * This personality attempts to prevent you from fleeing from combat. * * @name Brave * @prerequisite Flee combat once * @effect -100 fleePercent * @effect +5% STR * @effect +10% XP loss at end of combat * @category Personalities * @package Player */` class Brave extends Personality constructor: -> fleePercent: -> -100 strPercent: -> 5 combatEndXpLoss: (player, baseCombatEndXpLoss) -> parseInt baseCombatEndXpLoss*0.1 @canUse = (player) -> player.statistics["combat self flee"] > 0 @desc = "Flee combat once" module.exports = exports = Brave
23698
Personality = require "../base/Personality" `/** * This personality attempts to prevent you from fleeing from combat. * * @name <NAME> * @prerequisite Flee combat once * @effect -100 fleePercent * @effect +5% STR * @effect +10% XP loss at end of combat * @category Personalities * @package Player */` class Brave extends Personality constructor: -> fleePercent: -> -100 strPercent: -> 5 combatEndXpLoss: (player, baseCombatEndXpLoss) -> parseInt baseCombatEndXpLoss*0.1 @canUse = (player) -> player.statistics["combat self flee"] > 0 @desc = "Flee combat once" module.exports = exports = Brave
true
Personality = require "../base/Personality" `/** * This personality attempts to prevent you from fleeing from combat. * * @name PI:NAME:<NAME>END_PI * @prerequisite Flee combat once * @effect -100 fleePercent * @effect +5% STR * @effect +10% XP loss at end of combat * @category Personalities * @package Player */` class Brave extends Personality constructor: -> fleePercent: -> -100 strPercent: -> 5 combatEndXpLoss: (player, baseCombatEndXpLoss) -> parseInt baseCombatEndXpLoss*0.1 @canUse = (player) -> player.statistics["combat self flee"] > 0 @desc = "Flee combat once" module.exports = exports = Brave
[ { "context": "\"../index\"\n\ndomain = \"slack-node\"\nwebhookToken = \"ROHgstANbsFAUA5dHHI5JONu\"\napiToken = \"xoxp-2307918714-2307918716-230791081", "end": 116, "score": 0.9193246364593506, "start": 92, "tag": "KEY", "value": "ROHgstANbsFAUA5dHHI5JONu" }, { "context": "ookToken = ...
src/test/main.spec.test.coffee
juanpabloaj/slack-node-sdk
0
should = require "should" Slack = require "../index" domain = "slack-node" webhookToken = "ROHgstANbsFAUA5dHHI5JONu" apiToken = "xoxp-2307918714-2307918716-2307910813-17cabf" describe 'slack webhook part', -> slack = new Slack webhookToken, domain it ',should send a correct response', (done) -> slack.should.be.an.Object done() it ',should send a correct response', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." , (err, response) -> response.should.be.ok.and.an.Object done() it ',should send a correct response', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." "icon_emoji": ":ghost:" , (err, response) -> response.should.be.ok.and.an.Object done() it ',should have status code and headers', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." "icon_emoji": ":ghost:" , (err, response) -> response.statusCode.should.be.a.Number response.headers.should.be.an.Object done() describe "slack api part", -> slack = new Slack apiToken it ',shoule be return a slack object', (done) -> slack.should.be.an.Object done() it ", run with user.list", (done) -> slack.api "users.list", (err, response) -> response.should.be.ok.and.an.Object done() describe ", emoji test", -> slack = new Slack webhookToken, domain it ', emoji give empty value', (done) -> obj = slack.detectEmoji() obj.should.be.an.Array obj["key"].should.equal("icon_emoji") obj["val"].should.equal("") done() it ', emoji using :ghost: style', (done) -> obj = slack.detectEmoji(":ghost:") obj.should.be.an.Array obj["key"].should.equal("icon_emoji") obj["val"].should.equal(":ghost:") done() it ', emoji using http image url', (done) -> obj = slack.detectEmoji("http://icons.iconarchive.com/icons/rokey/popo-emotions/128/after-boom-icon.png") obj.should.be.an.Array obj["key"].should.equal("icon_url") obj["val"].should.equal("http://icons.iconarchive.com/icons/rokey/popo-emotions/128/after-boom-icon.png") done()
104657
should = require "should" Slack = require "../index" domain = "slack-node" webhookToken = "<KEY>" apiToken = "<KEY>" describe 'slack webhook part', -> slack = new Slack webhookToken, domain it ',should send a correct response', (done) -> slack.should.be.an.Object done() it ',should send a correct response', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." , (err, response) -> response.should.be.ok.and.an.Object done() it ',should send a correct response', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." "icon_emoji": ":ghost:" , (err, response) -> response.should.be.ok.and.an.Object done() it ',should have status code and headers', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." "icon_emoji": ":ghost:" , (err, response) -> response.statusCode.should.be.a.Number response.headers.should.be.an.Object done() describe "slack api part", -> slack = new Slack apiToken it ',shoule be return a slack object', (done) -> slack.should.be.an.Object done() it ", run with user.list", (done) -> slack.api "users.list", (err, response) -> response.should.be.ok.and.an.Object done() describe ", emoji test", -> slack = new Slack webhookToken, domain it ', emoji give empty value', (done) -> obj = slack.detectEmoji() obj.should.be.an.Array obj["key"].should.equal("icon_emoji") obj["val"].should.equal("") done() it ', emoji using :ghost: style', (done) -> obj = slack.detectEmoji(":ghost:") obj.should.be.an.Array obj["key"].should.equal("icon_emoji") obj["val"].should.equal(":ghost:") done() it ', emoji using http image url', (done) -> obj = slack.detectEmoji("http://icons.iconarchive.com/icons/rokey/popo-emotions/128/after-boom-icon.png") obj.should.be.an.Array obj["key"].should.equal("icon_url") obj["val"].should.equal("http://icons.iconarchive.com/icons/rokey/popo-emotions/128/after-boom-icon.png") done()
true
should = require "should" Slack = require "../index" domain = "slack-node" webhookToken = "PI:KEY:<KEY>END_PI" apiToken = "PI:KEY:<KEY>END_PI" describe 'slack webhook part', -> slack = new Slack webhookToken, domain it ',should send a correct response', (done) -> slack.should.be.an.Object done() it ',should send a correct response', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." , (err, response) -> response.should.be.ok.and.an.Object done() it ',should send a correct response', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." "icon_emoji": ":ghost:" , (err, response) -> response.should.be.ok.and.an.Object done() it ',should have status code and headers', (done) -> slack.webhook channel: "#general" username: "webhookbot" text: "This is posted to #general and comes from a bot named webhookbot." "icon_emoji": ":ghost:" , (err, response) -> response.statusCode.should.be.a.Number response.headers.should.be.an.Object done() describe "slack api part", -> slack = new Slack apiToken it ',shoule be return a slack object', (done) -> slack.should.be.an.Object done() it ", run with user.list", (done) -> slack.api "users.list", (err, response) -> response.should.be.ok.and.an.Object done() describe ", emoji test", -> slack = new Slack webhookToken, domain it ', emoji give empty value', (done) -> obj = slack.detectEmoji() obj.should.be.an.Array obj["key"].should.equal("icon_emoji") obj["val"].should.equal("") done() it ', emoji using :ghost: style', (done) -> obj = slack.detectEmoji(":ghost:") obj.should.be.an.Array obj["key"].should.equal("icon_emoji") obj["val"].should.equal(":ghost:") done() it ', emoji using http image url', (done) -> obj = slack.detectEmoji("http://icons.iconarchive.com/icons/rokey/popo-emotions/128/after-boom-icon.png") obj.should.be.an.Array obj["key"].should.equal("icon_url") obj["val"].should.equal("http://icons.iconarchive.com/icons/rokey/popo-emotions/128/after-boom-icon.png") done()
[ { "context": "ild'\n commit: true\n push: true\n remote: 'git@github.com:drupalprojects/kalatheme.git'\n build:\n 'B", "end": 104, "score": 0.9994560480117798, "start": 90, "tag": "EMAIL", "value": "git@github.com" }, { "context": ": true\n push: true\n remote:...
grunt/buildcontrol.coffee
pirog/kalatheme-backup
1
module.exports = options: dir: 'build' commit: true push: true remote: 'git@github.com:drupalprojects/kalatheme.git' build: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%' dev: options: branch: '7.x-4.x' release: options: branch: '<%= package.drupalversion =>' tag: '<%= package.drupalversion +"-"+ package.version =>'
11853
module.exports = options: dir: 'build' commit: true push: true remote: '<EMAIL>:drupalprojects/kalatheme.git' build: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%' dev: options: branch: '7.x-4.x' release: options: branch: '<%= package.drupalversion =>' tag: '<%= package.drupalversion +"-"+ package.version =>'
true
module.exports = options: dir: 'build' commit: true push: true remote: 'PI:EMAIL:<EMAIL>END_PI:drupalprojects/kalatheme.git' build: 'Built %sourceName% from commit %sourceCommit% on branch %sourceBranch%' dev: options: branch: '7.x-4.x' release: options: branch: '<%= package.drupalversion =>' tag: '<%= package.drupalversion +"-"+ package.version =>'
[ { "context": " name: 'jack' + Date.now(),\n password: 'rose'\n co(->\n user = yield US.create(data)\n ", "end": 278, "score": 0.9991538524627686, "start": 274, "tag": "PASSWORD", "value": "rose" } ]
samples/reader/test/functional/user_test.coffee
RobinQu/katalyst
1
expect = require('chai').expect co = require('co') before((done)-> process.app.bootstrap(done) ) describe 'UserService', -> it 'should register user', (done)-> US = process.app.require('service/user') data = name: 'jack' + Date.now(), password: 'rose' co(-> user = yield US.create(data) found = yield US.findUserByLogin(data) expect(found).to.be.ok expect(found.name).to.equal(data.name) yield found.destroy() done() ).catch(done)
3599
expect = require('chai').expect co = require('co') before((done)-> process.app.bootstrap(done) ) describe 'UserService', -> it 'should register user', (done)-> US = process.app.require('service/user') data = name: 'jack' + Date.now(), password: '<PASSWORD>' co(-> user = yield US.create(data) found = yield US.findUserByLogin(data) expect(found).to.be.ok expect(found.name).to.equal(data.name) yield found.destroy() done() ).catch(done)
true
expect = require('chai').expect co = require('co') before((done)-> process.app.bootstrap(done) ) describe 'UserService', -> it 'should register user', (done)-> US = process.app.require('service/user') data = name: 'jack' + Date.now(), password: 'PI:PASSWORD:<PASSWORD>END_PI' co(-> user = yield US.create(data) found = yield US.findUserByLogin(data) expect(found).to.be.ok expect(found.name).to.equal(data.name) yield found.destroy() done() ).catch(done)
[ { "context": " url = Iron.Location.get().path\n key = \"#{Meteor.userId()}:#{url}\"\n\n # Register hook which will save state into", "end": 741, "score": 0.9838842153549194, "start": 714, "tag": "KEY", "value": "\"#{Meteor.userId()}:#{url}\"" }, { "context": " Tem...
tabmanager.coffee
nous-consulting/mateor-tabmanager
2
defaultTabUrls = ['/', '/orders', '/directory', '/suppliers'] if Meteor.isClient Template.registerHelper "isDefaultTab", (url) -> url in defaultTabUrls last_visited_tabs = ReactiveVar [] visitTab = (url) -> tabs = last_visited_tabs.get() if url in tabs tabs.remove(url) tabs.push url last_visited_tabs.set tabs class TabManager constructor: (@collection, @icons) -> @registeredTemplates = [] registerTemplate: (name) -> if name and name not in @registeredTemplates @registeredTemplates.push name collection = @collection getKey = -> if FlowRouter url = FlowRouter.current().path else url = Iron.Location.get().path key = "#{Meteor.userId()}:#{url}" # Register hook which will save state into database each time it will change. # Hook is provided by `nous:state` package. Template[name].onStateUpdated -> key = getKey() collection.update key, $set: state: @state.toJSON() # Register hook which will restore saved state from database. Template[name].onStateRequested -> key = getKey() collection.findOne(key)?.state createTab: (template_name, title) -> if FlowRouter url = FlowRouter.current().path else url = Iron.Location.get().path Session.set 'currentTab', url visitTab(url) key = "#{Meteor.userId()}:#{url}" if @collection.find(key).count() is 0 @collection.insert _id: key url: url title: title route: template_name @registerTemplate template_name removeTab: (id) -> visited_tabs = last_visited_tabs.get() tab = @collection.findOne(id) if tab @collection.remove id visited_tabs.remove tab.url last_visited_tabs.set visited_tabs lastVisitedTab: -> tabs = last_visited_tabs.get() tabs[tabs.length - 1] getIcon: (route) -> @icons[route] ? 'fa-file'
135799
defaultTabUrls = ['/', '/orders', '/directory', '/suppliers'] if Meteor.isClient Template.registerHelper "isDefaultTab", (url) -> url in defaultTabUrls last_visited_tabs = ReactiveVar [] visitTab = (url) -> tabs = last_visited_tabs.get() if url in tabs tabs.remove(url) tabs.push url last_visited_tabs.set tabs class TabManager constructor: (@collection, @icons) -> @registeredTemplates = [] registerTemplate: (name) -> if name and name not in @registeredTemplates @registeredTemplates.push name collection = @collection getKey = -> if FlowRouter url = FlowRouter.current().path else url = Iron.Location.get().path key = <KEY> # Register hook which will save state into database each time it will change. # Hook is provided by `nous:state` package. Template[name].onStateUpdated -> key = <KEY>() collection.update key, $set: state: @state.toJSON() # Register hook which will restore saved state from database. Template[name].onStateRequested -> key = getKey() collection.findOne(key)?.state createTab: (template_name, title) -> if FlowRouter url = FlowRouter.current().path else url = Iron.Location.get().path Session.set 'currentTab', url visitTab(url) key = <KEY> if @collection.find(key).count() is 0 @collection.insert _id: key url: url title: title route: template_name @registerTemplate template_name removeTab: (id) -> visited_tabs = last_visited_tabs.get() tab = @collection.findOne(id) if tab @collection.remove id visited_tabs.remove tab.url last_visited_tabs.set visited_tabs lastVisitedTab: -> tabs = last_visited_tabs.get() tabs[tabs.length - 1] getIcon: (route) -> @icons[route] ? 'fa-file'
true
defaultTabUrls = ['/', '/orders', '/directory', '/suppliers'] if Meteor.isClient Template.registerHelper "isDefaultTab", (url) -> url in defaultTabUrls last_visited_tabs = ReactiveVar [] visitTab = (url) -> tabs = last_visited_tabs.get() if url in tabs tabs.remove(url) tabs.push url last_visited_tabs.set tabs class TabManager constructor: (@collection, @icons) -> @registeredTemplates = [] registerTemplate: (name) -> if name and name not in @registeredTemplates @registeredTemplates.push name collection = @collection getKey = -> if FlowRouter url = FlowRouter.current().path else url = Iron.Location.get().path key = PI:KEY:<KEY>END_PI # Register hook which will save state into database each time it will change. # Hook is provided by `nous:state` package. Template[name].onStateUpdated -> key = PI:KEY:<KEY>END_PI() collection.update key, $set: state: @state.toJSON() # Register hook which will restore saved state from database. Template[name].onStateRequested -> key = getKey() collection.findOne(key)?.state createTab: (template_name, title) -> if FlowRouter url = FlowRouter.current().path else url = Iron.Location.get().path Session.set 'currentTab', url visitTab(url) key = PI:KEY:<KEY>END_PI if @collection.find(key).count() is 0 @collection.insert _id: key url: url title: title route: template_name @registerTemplate template_name removeTab: (id) -> visited_tabs = last_visited_tabs.get() tab = @collection.findOne(id) if tab @collection.remove id visited_tabs.remove tab.url last_visited_tabs.set visited_tabs lastVisitedTab: -> tabs = last_visited_tabs.get() tabs[tabs.length - 1] getIcon: (route) -> @icons[route] ? 'fa-file'
[ { "context": "ript\r\n * version #{pkg.version}\r\n * Copyright 2014 Robert Nix\r\n * MIT License\r\n */\r\n\r\n\"\"\"\r\n\r\ngulp.task 'build',", "end": 396, "score": 0.9997913241386414, "start": 386, "tag": "NAME", "value": "Robert Nix" } ]
gulpfile.coffee
Mischanix/cheap
3
pkg = require './package.json' gulp = require 'gulp' util = require 'gulp-util' coffee = require 'gulp-coffee' concat = require 'gulp-concat' header = require 'gulp-header' uglify = require 'gulp-uglify' mocha = require 'gulp-mocha' src = ['src/cheap.coffee'] head = """ /** * cheap.js - C-like memory layout for javascript * version #{pkg.version} * Copyright 2014 Robert Nix * MIT License */ """ gulp.task 'build', -> gulp.src(src) .pipe(concat 'cheap.js') .pipe(coffee().on 'error', util.log) .pipe(header head) .pipe(gulp.dest 'dist') .pipe(concat 'cheap.min.js') .pipe(uglify()) .pipe(header head) .pipe(gulp.dest 'dist') return gulp.task 'spec', -> gulp.src('test/run.coffee', read: false) .pipe(mocha reporter: 'list') return gulp.task 'default', ['spec', 'build']
69648
pkg = require './package.json' gulp = require 'gulp' util = require 'gulp-util' coffee = require 'gulp-coffee' concat = require 'gulp-concat' header = require 'gulp-header' uglify = require 'gulp-uglify' mocha = require 'gulp-mocha' src = ['src/cheap.coffee'] head = """ /** * cheap.js - C-like memory layout for javascript * version #{pkg.version} * Copyright 2014 <NAME> * MIT License */ """ gulp.task 'build', -> gulp.src(src) .pipe(concat 'cheap.js') .pipe(coffee().on 'error', util.log) .pipe(header head) .pipe(gulp.dest 'dist') .pipe(concat 'cheap.min.js') .pipe(uglify()) .pipe(header head) .pipe(gulp.dest 'dist') return gulp.task 'spec', -> gulp.src('test/run.coffee', read: false) .pipe(mocha reporter: 'list') return gulp.task 'default', ['spec', 'build']
true
pkg = require './package.json' gulp = require 'gulp' util = require 'gulp-util' coffee = require 'gulp-coffee' concat = require 'gulp-concat' header = require 'gulp-header' uglify = require 'gulp-uglify' mocha = require 'gulp-mocha' src = ['src/cheap.coffee'] head = """ /** * cheap.js - C-like memory layout for javascript * version #{pkg.version} * Copyright 2014 PI:NAME:<NAME>END_PI * MIT License */ """ gulp.task 'build', -> gulp.src(src) .pipe(concat 'cheap.js') .pipe(coffee().on 'error', util.log) .pipe(header head) .pipe(gulp.dest 'dist') .pipe(concat 'cheap.min.js') .pipe(uglify()) .pipe(header head) .pipe(gulp.dest 'dist') return gulp.task 'spec', -> gulp.src('test/run.coffee', read: false) .pipe(mocha reporter: 'list') return gulp.task 'default', ['spec', 'build']
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9993391036987305, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-signal-unregister.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") childKilled = false done = false spawn = require("child_process").spawn util = require("util") child = undefined join = require("path").join child = spawn(process.argv[0], [join(common.fixturesDir, "should_exit.js")]) child.on "exit", -> childKilled = true unless done return setTimeout (-> console.log "Sending SIGINT" child.kill "SIGINT" setTimeout (-> console.log "Chance has been given to die" done = true unless childKilled # Cleanup console.log "Child did not die on SIGINT, sending SIGTERM" child.kill "SIGTERM" return ), 200 return ), 200 process.on "exit", -> assert.ok childKilled return
129752
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") childKilled = false done = false spawn = require("child_process").spawn util = require("util") child = undefined join = require("path").join child = spawn(process.argv[0], [join(common.fixturesDir, "should_exit.js")]) child.on "exit", -> childKilled = true unless done return setTimeout (-> console.log "Sending SIGINT" child.kill "SIGINT" setTimeout (-> console.log "Chance has been given to die" done = true unless childKilled # Cleanup console.log "Child did not die on SIGINT, sending SIGTERM" child.kill "SIGTERM" return ), 200 return ), 200 process.on "exit", -> assert.ok childKilled return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") childKilled = false done = false spawn = require("child_process").spawn util = require("util") child = undefined join = require("path").join child = spawn(process.argv[0], [join(common.fixturesDir, "should_exit.js")]) child.on "exit", -> childKilled = true unless done return setTimeout (-> console.log "Sending SIGINT" child.kill "SIGINT" setTimeout (-> console.log "Chance has been given to die" done = true unless childKilled # Cleanup console.log "Child did not die on SIGINT, sending SIGTERM" child.kill "SIGTERM" return ), 200 return ), 200 process.on "exit", -> assert.ok childKilled return
[ { "context": "###\n backbone-orm.js 0.5.12\n Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm\n Lice", "end": 58, "score": 0.9968027472496033, "start": 50, "tag": "NAME", "value": "Vidigami" }, { "context": " Copyright (c) 2013 Vidigami - https://github.com/v...
src/cache/model_cache.coffee
michaelBenin/backbone-orm
1
### backbone-orm.js 0.5.12 Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Backbone.js, Underscore.js, and Moment.js. ### Backbone = require 'backbone' _ = require 'underscore' Queue = require '../queue' MemoryStore = require './memory_store' MEMORY_STORE_KEYS = ['max', 'max_age', 'destroy'] # @private module.exports = class ModelCache constructor: -> @enabled = false @caches = {} @options = {modelTypes: {}} @verbose = false # @verbose = true # Configure the cache singleton # # options: # max: default maximum number of items or max size of the cache # max_age/maxAge: default maximum number of items or max size of the cache # model_types/modelTypes: {'ModelName': options} # configure: (options={}) -> @enabled = options.enabled @reset(->) for key, value of options if _.isObject(value) @options[key] or= {} values = @options[key] values[value_key] = value_value for value_key, value_value of value else @options[key] = value return @ configureSync: (model_type, sync_fn) -> return sync_fn if model_type::_orm_never_cache or not (cache = @getOrCreateCache(model_type.model_name)) model_type.cache = cache return require('./sync')(model_type, sync_fn) reset: (callback) -> queue = new Queue() for key, value of @caches do (value) -> queue.defer (callback) -> value.reset(callback) queue.await callback hardReset: -> @reset(->) delete @caches[key] for key, value of @caches return @ getOrCreateCache: (model_name) -> return null unless @enabled throw new Error "Missing model name for cache" unless model_name return model_cache if model_cache = @caches[model_name] # there are options if options = @options.modelTypes[model_name] return @caches[model_name] = options.store?() or new MemoryStore(_.pick(options, MEMORY_STORE_KEYS)) # there are global options else if @options.store or @options.max or @options.max_age return @caches[model_name] = @options.store?() or new MemoryStore(_.pick(@options, MEMORY_STORE_KEYS)) return null
116464
### backbone-orm.js 0.5.12 Copyright (c) 2013 <NAME> - https://github.com/vidigami/backbone-orm License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Backbone.js, Underscore.js, and Moment.js. ### Backbone = require 'backbone' _ = require 'underscore' Queue = require '../queue' MemoryStore = require './memory_store' MEMORY_STORE_KEYS = ['max', 'max_age', 'destroy'] # @private module.exports = class ModelCache constructor: -> @enabled = false @caches = {} @options = {modelTypes: {}} @verbose = false # @verbose = true # Configure the cache singleton # # options: # max: default maximum number of items or max size of the cache # max_age/maxAge: default maximum number of items or max size of the cache # model_types/modelTypes: {'ModelName': options} # configure: (options={}) -> @enabled = options.enabled @reset(->) for key, value of options if _.isObject(value) @options[key] or= {} values = @options[key] values[value_key] = value_value for value_key, value_value of value else @options[key] = value return @ configureSync: (model_type, sync_fn) -> return sync_fn if model_type::_orm_never_cache or not (cache = @getOrCreateCache(model_type.model_name)) model_type.cache = cache return require('./sync')(model_type, sync_fn) reset: (callback) -> queue = new Queue() for key, value of @caches do (value) -> queue.defer (callback) -> value.reset(callback) queue.await callback hardReset: -> @reset(->) delete @caches[key] for key, value of @caches return @ getOrCreateCache: (model_name) -> return null unless @enabled throw new Error "Missing model name for cache" unless model_name return model_cache if model_cache = @caches[model_name] # there are options if options = @options.modelTypes[model_name] return @caches[model_name] = options.store?() or new MemoryStore(_.pick(options, MEMORY_STORE_KEYS)) # there are global options else if @options.store or @options.max or @options.max_age return @caches[model_name] = @options.store?() or new MemoryStore(_.pick(@options, MEMORY_STORE_KEYS)) return null
true
### backbone-orm.js 0.5.12 Copyright (c) 2013 PI:NAME:<NAME>END_PI - https://github.com/vidigami/backbone-orm License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Backbone.js, Underscore.js, and Moment.js. ### Backbone = require 'backbone' _ = require 'underscore' Queue = require '../queue' MemoryStore = require './memory_store' MEMORY_STORE_KEYS = ['max', 'max_age', 'destroy'] # @private module.exports = class ModelCache constructor: -> @enabled = false @caches = {} @options = {modelTypes: {}} @verbose = false # @verbose = true # Configure the cache singleton # # options: # max: default maximum number of items or max size of the cache # max_age/maxAge: default maximum number of items or max size of the cache # model_types/modelTypes: {'ModelName': options} # configure: (options={}) -> @enabled = options.enabled @reset(->) for key, value of options if _.isObject(value) @options[key] or= {} values = @options[key] values[value_key] = value_value for value_key, value_value of value else @options[key] = value return @ configureSync: (model_type, sync_fn) -> return sync_fn if model_type::_orm_never_cache or not (cache = @getOrCreateCache(model_type.model_name)) model_type.cache = cache return require('./sync')(model_type, sync_fn) reset: (callback) -> queue = new Queue() for key, value of @caches do (value) -> queue.defer (callback) -> value.reset(callback) queue.await callback hardReset: -> @reset(->) delete @caches[key] for key, value of @caches return @ getOrCreateCache: (model_name) -> return null unless @enabled throw new Error "Missing model name for cache" unless model_name return model_cache if model_cache = @caches[model_name] # there are options if options = @options.modelTypes[model_name] return @caches[model_name] = options.store?() or new MemoryStore(_.pick(options, MEMORY_STORE_KEYS)) # there are global options else if @options.store or @options.max or @options.max_age return @caches[model_name] = @options.store?() or new MemoryStore(_.pick(@options, MEMORY_STORE_KEYS)) return null
[ { "context": "# Copyright (c) 2015 - 2017 Marcel Kapfer (mmk2410) and friends\n#\n# MIT License\n#\n# Permiss", "end": 41, "score": 0.9998793601989746, "start": 28, "tag": "NAME", "value": "Marcel Kapfer" }, { "context": "# Copyright (c) 2015 - 2017 Marcel Kapfer (mmk2410) and friend...
lib/atom-oss-license.coffee
mmk2410/atom-oss-license
5
# Copyright (c) 2015 - 2017 Marcel Kapfer (mmk2410) and friends # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. {CompositeDisposable} = require 'atom' {Point} = require 'atom' {Range} = require 'atom' YearRange = require './year-range' module.exports = AtomOssLicense = subscriptions: null config: copyright: title: "Copyright Line" description: "This shows the copyright line at the beginning of the license" type: 'boolean' default: true name: title: "Your name", description: "Your name as shown in the copyright line (only if enabled)" type: 'string' default: '' xheader: title: "Custom Header" description: "Add a custom header after the license text" type: "boolean" default: false xheaderpath: title: "Custom Header Path" description: "Absolute path to the header file" type: 'string' default: '' activate: (state) -> @subscriptions = new CompositeDisposable @subscriptions.add atom.commands.add 'atom-workspace', 'License: MIT': => @mit() 'License: Apache': => @apache() 'License: Artistic': => @artistic() 'License: BSD ISC': => @bsd_isc() 'License: BSD v2': => @bsd_v2() 'License: BSD v3': => @bsd_v3() 'License: CC0': => @cc0() 'License: Eclipse': => @eclipse() 'License: GPL v2': => @gpl_v2() 'License: GPL v3': => @gpl_v3() 'License: GPL Affero v3': => @gpl_affero() 'License: LGPL v2.1': => @lgpl_v2_1() 'License: LGPL v3': => @lgpl_v3() 'License: Mozilla': => @mozilla() 'License: no license': => @no_license() 'License: The Unlicense': => @unlicense() 'License: Academic Free License': => @academic_free_license() 'License: Apple Public Source 2 License': => @apple_public_source_2() 'License: Boost Software License': => @boost_software_license() 'License: CeCILL': => @CeCILL() 'License: Common Development and Distribution License': => @common_dev_and_dist_license() 'License: Common Public License': => @common_public_license() 'License: Cryptix General License': => @cryptix_general_license() 'License: Educational Community License': => @educational_community_license() 'License: Eiffel Forum License': => @eiffel_forum_license() 'License: IBM Public License': => @IBM_public_license() 'License: Intel Open Source License': => @intel_open_source_license() 'License: LaTeX Project Public License': => @LaTeX_project_public_license() 'License: Microsoft Public License': => @microsoft_public_license() 'License: Microsoft Reciprocal License': => @microsoft_reciprocal_license() 'License: Netscape Public License': => @netscape_public_license() 'License: Open Software License': => @open_software_license() 'License: OpenSSL License': => @openssl_license() 'License: PHP License': => @php_license() 'License: Python Software Foundation License': => @python_software_foundation_license() 'License: Q Public License': => @q_public_license() 'License: SUN Industry Standards Source License': => @sun_industry_standards_source_license() 'License: SUN Public License': => @sun_public_license() 'License: W3C License': => @w3c_license() 'License: WTFPL': => @wtfpl() 'License: xFree86 License': => @xfree86_license() 'License: zlib/libpng License': => @zlib_libpng_license() 'License: Zope Public License': => @zope_public_license() 'License: Berkeley Database License': => @berkeley_database_license() 'License: Open Font License': => @ofl() 'License: Creative Commons 4.0 BY': => @cc_by() 'License: Creative Commons 4.0 BY-SA': => @cc_by_sa() 'License: Open Recipe License': => @open_recipe_license() 'License: Toogle Copyright line': => @toggle_copyright() 'License: Toggle Header': => @toggle_header() 'License: Update Year': => @updateCopyright(atom.workspace.getActiveTextEditor()) deactivate: -> @subscriptions.dispose() academic_free_license: -> @addLicense('academic_free_license') apple_public_source_2: -> @addLicense('apple_public_source_2') boost_software_license: -> @addLicense('boost_software_license') CeCILL: -> @addLicense('CeCILL') common_dev_and_dist_license: -> @addLicense('common_dev_and_dist_license') common_public_license: -> @addLicense('common_public_license') cryptix_general_license: -> @addLicense('cryptix_general_license') educational_community_license: -> @addLicense('educational_community_license') eiffel_forum_license: -> @addLicense('eiffel_forum_license') IBM_public_license: -> @addLicense('IBM_public_license') intel_open_source_license: -> @addLicense('intel_open_source_license') LaTeX_project_public_license: -> @addLicense('LaTeX_project_public_license') microsoft_public_license: -> @addLicense('microsoft_public_license') microsoft_reciprocal_license: -> @addLicense('microsoft_reciprocal_license') netscape_public_license: -> @addLicense('netscape_public_license') open_software_license: -> @addLicense('open_software_license') openssl_license: -> @addLicense('openssl_license') php_license: -> @addLicense('php_license') python_software_foundation_license: -> @addLicense('python_software_foundation_license') q_public_license: -> @addLicense('q_public_license') sun_industry_standards_source_license: -> @addLicense('sun_industry_standards_source_license') sun_public_license: -> @addLicense('sun_public_license') w3c_license: -> @addLicense('w3c_license') wtfpl: -> @addLicense('wtfpl') xfree86_license: -> @addLicense('xfree86_license') zlib_libpng_license: -> @addLicense('zlib_libpng_license') zope_public_license: -> @addLicense('zope_public_license') apache: -> @addLicense('apache') artistic: -> @addLicense('artistic') berkeley_database_license: -> @addLicense('berkeley_database_license') bsd_isc: -> @addLicense('bsd_isc') bsd_v2: -> @addLicense('bsd_v2') bsd_v3: -> @addLicense('bsd_v3') cc0: -> @addLicense('cc0') eclipse: -> @addLicense('eclipse') gpl_v2: -> @addLicense('gpl_v2') gpl_v3: -> @addLicense('gpl_v3') gpl_affero: -> @addLicense('gpl_affero') lgpl_v2_1: -> @addLicense('lgpl_v2_1') lgpl_v3: -> @addLicense('lgpl_v3') mit: -> @addLicense('mit') mozilla: -> @addLicense('mozilla') no_license: -> @addLicense('no_license') unlicense: -> @addLicense('unlicense') ofl: -> @addLicense('ofl') cc_by: -> @addLicense('cc_by') cc_by_sa: -> @addLicense('cc_by_sa') open_recipe_license: -> @addLicense('open_recipe_license') toggle_copyright: -> if atom.config.get("atom-oss-license.copyright") is true atom.config.set("atom-oss-license.copyright", false) else atom.config.set("atom-oss-license.copyright", true) toggle_header: -> if atom.config.get("atom-oss-license.xheader") is true atom.config.set("atom-oss-license.xheader", false) else atom.config.set("atom-oss-license.xheader", true) # Determines if the supplied object already contains a copyright notice. # Only checks for a copyright notice in the first ten lines of the file. # # * `obj` Buffer to check for a copyright notice, # either a {TextEditor} or {TextBuffer}. # # Returns a {Boolean} indicating whether this buffer has a copyright notice. hasCopyright: (obj) -> return @hasCopyright(obj.buffer) if obj.buffer? # earlier (until 1.1.2) @hasCopyrightInText was called with [[0,0],[10,0]] # but due to some strange change in (presumably) Atom 1.19.2 this no longer # works range = new Range(new Point(0,0), new Point(10,0)) @hasCopyrightInText(obj.getTextInRange(range)) # Determines if the supplied text has a copyright notice. # # * `text` {String} of the text within which to search for a copyright notice. # # Returns {Boolean} indicating whether this text has a copyright notice. hasCopyrightInText: (text) -> text.match(/Copyright \(c\)/m) # After `callback` is called, puts the cursor back where it was before. # # * `editor` {TextEditor} where the cursor is. # * `callback` A {Function} that manipulates the cursor position. restoreCursor: (editor, callback) -> marker = editor.markBufferPosition( editor.getCursorBufferPosition(), persistent: false) callback() editor.setCursorBufferPosition(marker.getHeadBufferPosition()) marker.destroy() # Updates copyright in the first ten lines. # # * `editor` {TextEditor} where the copyright should be updated. updateCopyright: (editor = atom.workspace.getActiveTextEditor()) -> if @hasCopyright(editor) editor.scanInBufferRange YearRange.pattern, [[0, 0], [10, 0]], ({matchText, replace}) -> yearRange = new YearRange(matchText) yearRange.addYear(new Date().getFullYear()) replace(yearRange.toString()) addLicense: (license) -> editor = atom.workspace.getActiveTextEditor() unless @hasCopyright(editor) @restoreCursor editor, -> editor.transact -> fs = require 'fs' filename = __dirname + "/license/" + license + ".txt" fs.readFile filename, 'utf8', (err, contents) -> if not err copybool = atom.config.get("atom-oss-license.copyright") headerbool = atom.config.get("atom-oss-license.xheader") if copybool year = new YearRange(new Date().getFullYear()) name = atom.config.get("atom-oss-license.name") if name is "" name = "<YOUR NAME>" copyright = "Copyright (c) #{year} #{name}" contents = "#{copyright}\n\n#{contents}" editor.setCursorBufferPosition([0, 0], autoscroll: false) editor.insertText(contents, select: true) editor.toggleLineCommentsInSelection() editor.setCursorBufferPosition( editor.getSelectedBufferRange().end) editor.insertText("\n") if headerbool headerpath = atom.config.get("atom-oss-license.xheaderpath") if headerpath? fs.readFile headerpath, 'utf8', (err, headercontents) -> if not err editor.insertText("\n\n#{headercontents}") else console.log err else console.log err
120116
# Copyright (c) 2015 - 2017 <NAME> (mmk2410) and friends # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. {CompositeDisposable} = require 'atom' {Point} = require 'atom' {Range} = require 'atom' YearRange = require './year-range' module.exports = AtomOssLicense = subscriptions: null config: copyright: title: "Copyright Line" description: "This shows the copyright line at the beginning of the license" type: 'boolean' default: true name: title: "Your name", description: "Your name as shown in the copyright line (only if enabled)" type: 'string' default: '' xheader: title: "Custom Header" description: "Add a custom header after the license text" type: "boolean" default: false xheaderpath: title: "Custom Header Path" description: "Absolute path to the header file" type: 'string' default: '' activate: (state) -> @subscriptions = new CompositeDisposable @subscriptions.add atom.commands.add 'atom-workspace', 'License: MIT': => @mit() 'License: Apache': => @apache() 'License: Artistic': => @artistic() 'License: BSD ISC': => @bsd_isc() 'License: BSD v2': => @bsd_v2() 'License: BSD v3': => @bsd_v3() 'License: CC0': => @cc0() 'License: Eclipse': => @eclipse() 'License: GPL v2': => @gpl_v2() 'License: GPL v3': => @gpl_v3() 'License: GPL Affero v3': => @gpl_affero() 'License: LGPL v2.1': => @lgpl_v2_1() 'License: LGPL v3': => @lgpl_v3() 'License: Mozilla': => @mozilla() 'License: no license': => @no_license() 'License: The Unlicense': => @unlicense() 'License: Academic Free License': => @academic_free_license() 'License: Apple Public Source 2 License': => @apple_public_source_2() 'License: Boost Software License': => @boost_software_license() 'License: CeCILL': => @CeCILL() 'License: Common Development and Distribution License': => @common_dev_and_dist_license() 'License: Common Public License': => @common_public_license() 'License: Cryptix General License': => @cryptix_general_license() 'License: Educational Community License': => @educational_community_license() 'License: Eiffel Forum License': => @eiffel_forum_license() 'License: IBM Public License': => @IBM_public_license() 'License: Intel Open Source License': => @intel_open_source_license() 'License: LaTeX Project Public License': => @LaTeX_project_public_license() 'License: Microsoft Public License': => @microsoft_public_license() 'License: Microsoft Reciprocal License': => @microsoft_reciprocal_license() 'License: Netscape Public License': => @netscape_public_license() 'License: Open Software License': => @open_software_license() 'License: OpenSSL License': => @openssl_license() 'License: PHP License': => @php_license() 'License: Python Software Foundation License': => @python_software_foundation_license() 'License: Q Public License': => @q_public_license() 'License: SUN Industry Standards Source License': => @sun_industry_standards_source_license() 'License: SUN Public License': => @sun_public_license() 'License: W3C License': => @w3c_license() 'License: WTFPL': => @wtfpl() 'License: xFree86 License': => @xfree86_license() 'License: zlib/libpng License': => @zlib_libpng_license() 'License: Zope Public License': => @zope_public_license() 'License: Berkeley Database License': => @berkeley_database_license() 'License: Open Font License': => @ofl() 'License: Creative Commons 4.0 BY': => @cc_by() 'License: Creative Commons 4.0 BY-SA': => @cc_by_sa() 'License: Open Recipe License': => @open_recipe_license() 'License: Toogle Copyright line': => @toggle_copyright() 'License: Toggle Header': => @toggle_header() 'License: Update Year': => @updateCopyright(atom.workspace.getActiveTextEditor()) deactivate: -> @subscriptions.dispose() academic_free_license: -> @addLicense('academic_free_license') apple_public_source_2: -> @addLicense('apple_public_source_2') boost_software_license: -> @addLicense('boost_software_license') CeCILL: -> @addLicense('CeCILL') common_dev_and_dist_license: -> @addLicense('common_dev_and_dist_license') common_public_license: -> @addLicense('common_public_license') cryptix_general_license: -> @addLicense('cryptix_general_license') educational_community_license: -> @addLicense('educational_community_license') eiffel_forum_license: -> @addLicense('eiffel_forum_license') IBM_public_license: -> @addLicense('IBM_public_license') intel_open_source_license: -> @addLicense('intel_open_source_license') LaTeX_project_public_license: -> @addLicense('LaTeX_project_public_license') microsoft_public_license: -> @addLicense('microsoft_public_license') microsoft_reciprocal_license: -> @addLicense('microsoft_reciprocal_license') netscape_public_license: -> @addLicense('netscape_public_license') open_software_license: -> @addLicense('open_software_license') openssl_license: -> @addLicense('openssl_license') php_license: -> @addLicense('php_license') python_software_foundation_license: -> @addLicense('python_software_foundation_license') q_public_license: -> @addLicense('q_public_license') sun_industry_standards_source_license: -> @addLicense('sun_industry_standards_source_license') sun_public_license: -> @addLicense('sun_public_license') w3c_license: -> @addLicense('w3c_license') wtfpl: -> @addLicense('wtfpl') xfree86_license: -> @addLicense('xfree86_license') zlib_libpng_license: -> @addLicense('zlib_libpng_license') zope_public_license: -> @addLicense('zope_public_license') apache: -> @addLicense('apache') artistic: -> @addLicense('artistic') berkeley_database_license: -> @addLicense('berkeley_database_license') bsd_isc: -> @addLicense('bsd_isc') bsd_v2: -> @addLicense('bsd_v2') bsd_v3: -> @addLicense('bsd_v3') cc0: -> @addLicense('cc0') eclipse: -> @addLicense('eclipse') gpl_v2: -> @addLicense('gpl_v2') gpl_v3: -> @addLicense('gpl_v3') gpl_affero: -> @addLicense('gpl_affero') lgpl_v2_1: -> @addLicense('lgpl_v2_1') lgpl_v3: -> @addLicense('lgpl_v3') mit: -> @addLicense('mit') mozilla: -> @addLicense('mozilla') no_license: -> @addLicense('no_license') unlicense: -> @addLicense('unlicense') ofl: -> @addLicense('ofl') cc_by: -> @addLicense('cc_by') cc_by_sa: -> @addLicense('cc_by_sa') open_recipe_license: -> @addLicense('open_recipe_license') toggle_copyright: -> if atom.config.get("atom-oss-license.copyright") is true atom.config.set("atom-oss-license.copyright", false) else atom.config.set("atom-oss-license.copyright", true) toggle_header: -> if atom.config.get("atom-oss-license.xheader") is true atom.config.set("atom-oss-license.xheader", false) else atom.config.set("atom-oss-license.xheader", true) # Determines if the supplied object already contains a copyright notice. # Only checks for a copyright notice in the first ten lines of the file. # # * `obj` Buffer to check for a copyright notice, # either a {TextEditor} or {TextBuffer}. # # Returns a {Boolean} indicating whether this buffer has a copyright notice. hasCopyright: (obj) -> return @hasCopyright(obj.buffer) if obj.buffer? # earlier (until 1.1.2) @hasCopyrightInText was called with [[0,0],[10,0]] # but due to some strange change in (presumably) Atom 1.19.2 this no longer # works range = new Range(new Point(0,0), new Point(10,0)) @hasCopyrightInText(obj.getTextInRange(range)) # Determines if the supplied text has a copyright notice. # # * `text` {String} of the text within which to search for a copyright notice. # # Returns {Boolean} indicating whether this text has a copyright notice. hasCopyrightInText: (text) -> text.match(/Copyright \(c\)/m) # After `callback` is called, puts the cursor back where it was before. # # * `editor` {TextEditor} where the cursor is. # * `callback` A {Function} that manipulates the cursor position. restoreCursor: (editor, callback) -> marker = editor.markBufferPosition( editor.getCursorBufferPosition(), persistent: false) callback() editor.setCursorBufferPosition(marker.getHeadBufferPosition()) marker.destroy() # Updates copyright in the first ten lines. # # * `editor` {TextEditor} where the copyright should be updated. updateCopyright: (editor = atom.workspace.getActiveTextEditor()) -> if @hasCopyright(editor) editor.scanInBufferRange YearRange.pattern, [[0, 0], [10, 0]], ({matchText, replace}) -> yearRange = new YearRange(matchText) yearRange.addYear(new Date().getFullYear()) replace(yearRange.toString()) addLicense: (license) -> editor = atom.workspace.getActiveTextEditor() unless @hasCopyright(editor) @restoreCursor editor, -> editor.transact -> fs = require 'fs' filename = __dirname + "/license/" + license + ".txt" fs.readFile filename, 'utf8', (err, contents) -> if not err copybool = atom.config.get("atom-oss-license.copyright") headerbool = atom.config.get("atom-oss-license.xheader") if copybool year = new YearRange(new Date().getFullYear()) name = atom.config.get("atom-oss-license.name") if name is "" name = "<YOUR NAME>" copyright = "Copyright (c) #{year} #{name}" contents = "#{copyright}\n\n#{contents}" editor.setCursorBufferPosition([0, 0], autoscroll: false) editor.insertText(contents, select: true) editor.toggleLineCommentsInSelection() editor.setCursorBufferPosition( editor.getSelectedBufferRange().end) editor.insertText("\n") if headerbool headerpath = atom.config.get("atom-oss-license.xheaderpath") if headerpath? fs.readFile headerpath, 'utf8', (err, headercontents) -> if not err editor.insertText("\n\n#{headercontents}") else console.log err else console.log err
true
# Copyright (c) 2015 - 2017 PI:NAME:<NAME>END_PI (mmk2410) and friends # # MIT License # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. {CompositeDisposable} = require 'atom' {Point} = require 'atom' {Range} = require 'atom' YearRange = require './year-range' module.exports = AtomOssLicense = subscriptions: null config: copyright: title: "Copyright Line" description: "This shows the copyright line at the beginning of the license" type: 'boolean' default: true name: title: "Your name", description: "Your name as shown in the copyright line (only if enabled)" type: 'string' default: '' xheader: title: "Custom Header" description: "Add a custom header after the license text" type: "boolean" default: false xheaderpath: title: "Custom Header Path" description: "Absolute path to the header file" type: 'string' default: '' activate: (state) -> @subscriptions = new CompositeDisposable @subscriptions.add atom.commands.add 'atom-workspace', 'License: MIT': => @mit() 'License: Apache': => @apache() 'License: Artistic': => @artistic() 'License: BSD ISC': => @bsd_isc() 'License: BSD v2': => @bsd_v2() 'License: BSD v3': => @bsd_v3() 'License: CC0': => @cc0() 'License: Eclipse': => @eclipse() 'License: GPL v2': => @gpl_v2() 'License: GPL v3': => @gpl_v3() 'License: GPL Affero v3': => @gpl_affero() 'License: LGPL v2.1': => @lgpl_v2_1() 'License: LGPL v3': => @lgpl_v3() 'License: Mozilla': => @mozilla() 'License: no license': => @no_license() 'License: The Unlicense': => @unlicense() 'License: Academic Free License': => @academic_free_license() 'License: Apple Public Source 2 License': => @apple_public_source_2() 'License: Boost Software License': => @boost_software_license() 'License: CeCILL': => @CeCILL() 'License: Common Development and Distribution License': => @common_dev_and_dist_license() 'License: Common Public License': => @common_public_license() 'License: Cryptix General License': => @cryptix_general_license() 'License: Educational Community License': => @educational_community_license() 'License: Eiffel Forum License': => @eiffel_forum_license() 'License: IBM Public License': => @IBM_public_license() 'License: Intel Open Source License': => @intel_open_source_license() 'License: LaTeX Project Public License': => @LaTeX_project_public_license() 'License: Microsoft Public License': => @microsoft_public_license() 'License: Microsoft Reciprocal License': => @microsoft_reciprocal_license() 'License: Netscape Public License': => @netscape_public_license() 'License: Open Software License': => @open_software_license() 'License: OpenSSL License': => @openssl_license() 'License: PHP License': => @php_license() 'License: Python Software Foundation License': => @python_software_foundation_license() 'License: Q Public License': => @q_public_license() 'License: SUN Industry Standards Source License': => @sun_industry_standards_source_license() 'License: SUN Public License': => @sun_public_license() 'License: W3C License': => @w3c_license() 'License: WTFPL': => @wtfpl() 'License: xFree86 License': => @xfree86_license() 'License: zlib/libpng License': => @zlib_libpng_license() 'License: Zope Public License': => @zope_public_license() 'License: Berkeley Database License': => @berkeley_database_license() 'License: Open Font License': => @ofl() 'License: Creative Commons 4.0 BY': => @cc_by() 'License: Creative Commons 4.0 BY-SA': => @cc_by_sa() 'License: Open Recipe License': => @open_recipe_license() 'License: Toogle Copyright line': => @toggle_copyright() 'License: Toggle Header': => @toggle_header() 'License: Update Year': => @updateCopyright(atom.workspace.getActiveTextEditor()) deactivate: -> @subscriptions.dispose() academic_free_license: -> @addLicense('academic_free_license') apple_public_source_2: -> @addLicense('apple_public_source_2') boost_software_license: -> @addLicense('boost_software_license') CeCILL: -> @addLicense('CeCILL') common_dev_and_dist_license: -> @addLicense('common_dev_and_dist_license') common_public_license: -> @addLicense('common_public_license') cryptix_general_license: -> @addLicense('cryptix_general_license') educational_community_license: -> @addLicense('educational_community_license') eiffel_forum_license: -> @addLicense('eiffel_forum_license') IBM_public_license: -> @addLicense('IBM_public_license') intel_open_source_license: -> @addLicense('intel_open_source_license') LaTeX_project_public_license: -> @addLicense('LaTeX_project_public_license') microsoft_public_license: -> @addLicense('microsoft_public_license') microsoft_reciprocal_license: -> @addLicense('microsoft_reciprocal_license') netscape_public_license: -> @addLicense('netscape_public_license') open_software_license: -> @addLicense('open_software_license') openssl_license: -> @addLicense('openssl_license') php_license: -> @addLicense('php_license') python_software_foundation_license: -> @addLicense('python_software_foundation_license') q_public_license: -> @addLicense('q_public_license') sun_industry_standards_source_license: -> @addLicense('sun_industry_standards_source_license') sun_public_license: -> @addLicense('sun_public_license') w3c_license: -> @addLicense('w3c_license') wtfpl: -> @addLicense('wtfpl') xfree86_license: -> @addLicense('xfree86_license') zlib_libpng_license: -> @addLicense('zlib_libpng_license') zope_public_license: -> @addLicense('zope_public_license') apache: -> @addLicense('apache') artistic: -> @addLicense('artistic') berkeley_database_license: -> @addLicense('berkeley_database_license') bsd_isc: -> @addLicense('bsd_isc') bsd_v2: -> @addLicense('bsd_v2') bsd_v3: -> @addLicense('bsd_v3') cc0: -> @addLicense('cc0') eclipse: -> @addLicense('eclipse') gpl_v2: -> @addLicense('gpl_v2') gpl_v3: -> @addLicense('gpl_v3') gpl_affero: -> @addLicense('gpl_affero') lgpl_v2_1: -> @addLicense('lgpl_v2_1') lgpl_v3: -> @addLicense('lgpl_v3') mit: -> @addLicense('mit') mozilla: -> @addLicense('mozilla') no_license: -> @addLicense('no_license') unlicense: -> @addLicense('unlicense') ofl: -> @addLicense('ofl') cc_by: -> @addLicense('cc_by') cc_by_sa: -> @addLicense('cc_by_sa') open_recipe_license: -> @addLicense('open_recipe_license') toggle_copyright: -> if atom.config.get("atom-oss-license.copyright") is true atom.config.set("atom-oss-license.copyright", false) else atom.config.set("atom-oss-license.copyright", true) toggle_header: -> if atom.config.get("atom-oss-license.xheader") is true atom.config.set("atom-oss-license.xheader", false) else atom.config.set("atom-oss-license.xheader", true) # Determines if the supplied object already contains a copyright notice. # Only checks for a copyright notice in the first ten lines of the file. # # * `obj` Buffer to check for a copyright notice, # either a {TextEditor} or {TextBuffer}. # # Returns a {Boolean} indicating whether this buffer has a copyright notice. hasCopyright: (obj) -> return @hasCopyright(obj.buffer) if obj.buffer? # earlier (until 1.1.2) @hasCopyrightInText was called with [[0,0],[10,0]] # but due to some strange change in (presumably) Atom 1.19.2 this no longer # works range = new Range(new Point(0,0), new Point(10,0)) @hasCopyrightInText(obj.getTextInRange(range)) # Determines if the supplied text has a copyright notice. # # * `text` {String} of the text within which to search for a copyright notice. # # Returns {Boolean} indicating whether this text has a copyright notice. hasCopyrightInText: (text) -> text.match(/Copyright \(c\)/m) # After `callback` is called, puts the cursor back where it was before. # # * `editor` {TextEditor} where the cursor is. # * `callback` A {Function} that manipulates the cursor position. restoreCursor: (editor, callback) -> marker = editor.markBufferPosition( editor.getCursorBufferPosition(), persistent: false) callback() editor.setCursorBufferPosition(marker.getHeadBufferPosition()) marker.destroy() # Updates copyright in the first ten lines. # # * `editor` {TextEditor} where the copyright should be updated. updateCopyright: (editor = atom.workspace.getActiveTextEditor()) -> if @hasCopyright(editor) editor.scanInBufferRange YearRange.pattern, [[0, 0], [10, 0]], ({matchText, replace}) -> yearRange = new YearRange(matchText) yearRange.addYear(new Date().getFullYear()) replace(yearRange.toString()) addLicense: (license) -> editor = atom.workspace.getActiveTextEditor() unless @hasCopyright(editor) @restoreCursor editor, -> editor.transact -> fs = require 'fs' filename = __dirname + "/license/" + license + ".txt" fs.readFile filename, 'utf8', (err, contents) -> if not err copybool = atom.config.get("atom-oss-license.copyright") headerbool = atom.config.get("atom-oss-license.xheader") if copybool year = new YearRange(new Date().getFullYear()) name = atom.config.get("atom-oss-license.name") if name is "" name = "<YOUR NAME>" copyright = "Copyright (c) #{year} #{name}" contents = "#{copyright}\n\n#{contents}" editor.setCursorBufferPosition([0, 0], autoscroll: false) editor.insertText(contents, select: true) editor.toggleLineCommentsInSelection() editor.setCursorBufferPosition( editor.getSelectedBufferRange().end) editor.insertText("\n") if headerbool headerpath = atom.config.get("atom-oss-license.xheaderpath") if headerpath? fs.readFile headerpath, 'utf8', (err, headercontents) -> if not err editor.insertText("\n\n#{headercontents}") else console.log err else console.log err
[ { "context": "class Connectfour\n\n name: hugo\n\n dosomthing: (@name) =>\n @name = \"bla\"\n", "end": 31, "score": 0.9903815984725952, "start": 27, "tag": "NAME", "value": "hugo" }, { "context": "class Connectfour\n\n name: hugo\n\n dosomthing: (@name) =>\n @name = \"bla\"...
app/assets/javascripts/connectfour.coffee
StefanoD/connect4-web
0
class Connectfour name: hugo dosomthing: (@name) => @name = "bla"
127967
class Connectfour name: <NAME> dosomthing: (@name) => @name = "bla"
true
class Connectfour name: PI:NAME:<NAME>END_PI dosomthing: (@name) => @name = "bla"
[ { "context": "###\nCopyright (c) Jim Garvin (http://github.com/coderifous), 2008.\nDual licens", "end": 28, "score": 0.9998837113380432, "start": 18, "tag": "NAME", "value": "Jim Garvin" }, { "context": "###\nCopyright (c) Jim Garvin (http://github.com/coderifous), 2008.\nDual licens...
app/assets/components/jquery-localize-i18n/src/jquery.localize.coffee
RadiusNetworks/radius-rails
2
### Copyright (c) Jim Garvin (http://github.com/coderifous), 2008. Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses. Written by Jim Garvin (@coderifous) for use on LMGTFY.com. http://github.com/coderifous/jquery-localize Based off of Keith Wood's Localisation jQuery plugin. http://keith-wood.name/localisation.html ### do ($ = jQuery) -> # Ensures language code is in the format aa-AA. normaliseLang = (lang) -> lang = lang.replace(/_/, '-').toLowerCase() if lang.length > 3 lang = lang.substring(0, 3) + lang.substring(3).toUpperCase() lang # Mozilla uses .language, IE uses .userLanguage $.defaultLanguage = normaliseLang(if navigator.languages then navigator.languages[0] else navigator.language or navigator.userLanguage) $.localize = (pkg, options = {}) -> wrappedSet = this intermediateLangData = {} fileExtension = options.fileExtension || "json" loadLanguage = (pkg, lang, level = 1) -> switch level when 1 intermediateLangData = {} if options.loadBase file = pkg + ".#{fileExtension}" jsonCall(file, pkg, lang, level) else loadLanguage(pkg, lang, 2) when 2 if lang.length >= 2 file = "#{pkg}-#{lang.substring(0, 2)}.#{fileExtension}" jsonCall(file, pkg, lang, level) when 3 if lang.length >= 5 file = "#{pkg}-#{lang.substring(0, 5)}.#{fileExtension}" jsonCall(file, pkg, lang, level) jsonCall = (file, pkg, lang, level) -> file = "#{options.pathPrefix}/#{file}" if options.pathPrefix? successFunc = (d) -> $.extend(intermediateLangData, d) notifyDelegateLanguageLoaded(intermediateLangData) loadLanguage(pkg, lang, level + 1) errorFunc = -> if options.fallback && options.fallback != lang loadLanguage(pkg, options.fallback) ajaxOptions = url: file dataType: "json" async: false timeout: if options.timeout? then options.timeout else 500 success: successFunc error: errorFunc # hack to work with serving from local file system. # local file:// urls won't work in chrome: # http://code.google.com/p/chromium/issues/detail?id=40787 if window.location.protocol == "file:" ajaxOptions.error = (xhr) -> successFunc($.parseJSON(xhr.responseText)) $.ajax(ajaxOptions) notifyDelegateLanguageLoaded = (data) -> if options.callback? options.callback(data, defaultCallback) else defaultCallback(data) defaultCallback = (data) -> $.localize.data[pkg] = data wrappedSet.each -> elem = $(this) key = elem.data("localize") key ||= elem.attr("rel").match(/localize\[(.*?)\]/)[1] value = valueForKey(key, data) localizeElement(elem, key, value) if value? localizeElement = (elem, key, value) -> if elem.is('input') then localizeInputElement(elem, key, value) else if elem.is('textarea') then localizeInputElement(elem, key, value) else if elem.is('img') then localizeImageElement(elem, key, value) else if elem.is('optgroup') then localizeOptgroupElement(elem, key, value) else unless $.isPlainObject(value) then elem.html(value) localizeForSpecialKeys(elem, value) if $.isPlainObject(value) localizeInputElement = (elem, key, value) -> val = if $.isPlainObject(value) then value.value else value if elem.is("[placeholder]") elem.attr("placeholder", val) else elem.val(val) localizeForSpecialKeys = (elem, value) -> setAttrFromValueForKey(elem, "title", value) setAttrFromValueForKey(elem, "href", value) setTextFromValueForKey(elem, "text", value) localizeOptgroupElement = (elem, key, value) -> elem.attr("label", value) localizeImageElement = (elem, key, value) -> setAttrFromValueForKey(elem, "alt", value) setAttrFromValueForKey(elem, "src", value) valueForKey = (key, data) -> keys = key.split(/\./) value = data for key in keys value = if value? then value[key] else null value setAttrFromValueForKey = (elem, key, value) -> value = valueForKey(key, value) elem.attr(key, value) if value? setTextFromValueForKey = (elem, key, value) -> value = valueForKey(key, value) elem.text(value) if value? regexify = (string_or_regex_or_array) -> if typeof(string_or_regex_or_array) == "string" "^" + string_or_regex_or_array + "$" else if string_or_regex_or_array.length? (regexify(thing) for thing in string_or_regex_or_array).join("|") else string_or_regex_or_array lang = normaliseLang(if options.language then options.language else $.defaultLanguage) loadLanguage(pkg, lang, 1) unless (options.skipLanguage && lang.match(regexify(options.skipLanguage))) wrappedSet $.fn.localize = $.localize $.localize.data = {}
41961
### Copyright (c) <NAME> (http://github.com/coderifous), 2008. Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses. Written by <NAME> (@coderifous) for use on LMGTFY.com. http://github.com/coderifous/jquery-localize Based off of Keith Wood's Localisation jQuery plugin. http://keith-wood.name/localisation.html ### do ($ = jQuery) -> # Ensures language code is in the format aa-AA. normaliseLang = (lang) -> lang = lang.replace(/_/, '-').toLowerCase() if lang.length > 3 lang = lang.substring(0, 3) + lang.substring(3).toUpperCase() lang # Mozilla uses .language, IE uses .userLanguage $.defaultLanguage = normaliseLang(if navigator.languages then navigator.languages[0] else navigator.language or navigator.userLanguage) $.localize = (pkg, options = {}) -> wrappedSet = this intermediateLangData = {} fileExtension = options.fileExtension || "json" loadLanguage = (pkg, lang, level = 1) -> switch level when 1 intermediateLangData = {} if options.loadBase file = pkg + ".#{fileExtension}" jsonCall(file, pkg, lang, level) else loadLanguage(pkg, lang, 2) when 2 if lang.length >= 2 file = "#{pkg}-#{lang.substring(0, 2)}.#{fileExtension}" jsonCall(file, pkg, lang, level) when 3 if lang.length >= 5 file = "#{pkg}-#{lang.substring(0, 5)}.#{fileExtension}" jsonCall(file, pkg, lang, level) jsonCall = (file, pkg, lang, level) -> file = "#{options.pathPrefix}/#{file}" if options.pathPrefix? successFunc = (d) -> $.extend(intermediateLangData, d) notifyDelegateLanguageLoaded(intermediateLangData) loadLanguage(pkg, lang, level + 1) errorFunc = -> if options.fallback && options.fallback != lang loadLanguage(pkg, options.fallback) ajaxOptions = url: file dataType: "json" async: false timeout: if options.timeout? then options.timeout else 500 success: successFunc error: errorFunc # hack to work with serving from local file system. # local file:// urls won't work in chrome: # http://code.google.com/p/chromium/issues/detail?id=40787 if window.location.protocol == "file:" ajaxOptions.error = (xhr) -> successFunc($.parseJSON(xhr.responseText)) $.ajax(ajaxOptions) notifyDelegateLanguageLoaded = (data) -> if options.callback? options.callback(data, defaultCallback) else defaultCallback(data) defaultCallback = (data) -> $.localize.data[pkg] = data wrappedSet.each -> elem = $(this) key = elem.data("localize") key ||= elem.attr("rel").match(/localize\[(.*?)\]/)[1] value = valueForKey(key, data) localizeElement(elem, key, value) if value? localizeElement = (elem, key, value) -> if elem.is('input') then localizeInputElement(elem, key, value) else if elem.is('textarea') then localizeInputElement(elem, key, value) else if elem.is('img') then localizeImageElement(elem, key, value) else if elem.is('optgroup') then localizeOptgroupElement(elem, key, value) else unless $.isPlainObject(value) then elem.html(value) localizeForSpecialKeys(elem, value) if $.isPlainObject(value) localizeInputElement = (elem, key, value) -> val = if $.isPlainObject(value) then value.value else value if elem.is("[placeholder]") elem.attr("placeholder", val) else elem.val(val) localizeForSpecialKeys = (elem, value) -> setAttrFromValueForKey(elem, "title", value) setAttrFromValueForKey(elem, "href", value) setTextFromValueForKey(elem, "text", value) localizeOptgroupElement = (elem, key, value) -> elem.attr("label", value) localizeImageElement = (elem, key, value) -> setAttrFromValueForKey(elem, "alt", value) setAttrFromValueForKey(elem, "src", value) valueForKey = (key, data) -> keys = key.split(/\./) value = data for key in keys value = if value? then value[key] else null value setAttrFromValueForKey = (elem, key, value) -> value = valueForKey(key, value) elem.attr(key, value) if value? setTextFromValueForKey = (elem, key, value) -> value = valueForKey(key, value) elem.text(value) if value? regexify = (string_or_regex_or_array) -> if typeof(string_or_regex_or_array) == "string" "^" + string_or_regex_or_array + "$" else if string_or_regex_or_array.length? (regexify(thing) for thing in string_or_regex_or_array).join("|") else string_or_regex_or_array lang = normaliseLang(if options.language then options.language else $.defaultLanguage) loadLanguage(pkg, lang, 1) unless (options.skipLanguage && lang.match(regexify(options.skipLanguage))) wrappedSet $.fn.localize = $.localize $.localize.data = {}
true
### Copyright (c) PI:NAME:<NAME>END_PI (http://github.com/coderifous), 2008. Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses. Written by PI:NAME:<NAME>END_PI (@coderifous) for use on LMGTFY.com. http://github.com/coderifous/jquery-localize Based off of Keith Wood's Localisation jQuery plugin. http://keith-wood.name/localisation.html ### do ($ = jQuery) -> # Ensures language code is in the format aa-AA. normaliseLang = (lang) -> lang = lang.replace(/_/, '-').toLowerCase() if lang.length > 3 lang = lang.substring(0, 3) + lang.substring(3).toUpperCase() lang # Mozilla uses .language, IE uses .userLanguage $.defaultLanguage = normaliseLang(if navigator.languages then navigator.languages[0] else navigator.language or navigator.userLanguage) $.localize = (pkg, options = {}) -> wrappedSet = this intermediateLangData = {} fileExtension = options.fileExtension || "json" loadLanguage = (pkg, lang, level = 1) -> switch level when 1 intermediateLangData = {} if options.loadBase file = pkg + ".#{fileExtension}" jsonCall(file, pkg, lang, level) else loadLanguage(pkg, lang, 2) when 2 if lang.length >= 2 file = "#{pkg}-#{lang.substring(0, 2)}.#{fileExtension}" jsonCall(file, pkg, lang, level) when 3 if lang.length >= 5 file = "#{pkg}-#{lang.substring(0, 5)}.#{fileExtension}" jsonCall(file, pkg, lang, level) jsonCall = (file, pkg, lang, level) -> file = "#{options.pathPrefix}/#{file}" if options.pathPrefix? successFunc = (d) -> $.extend(intermediateLangData, d) notifyDelegateLanguageLoaded(intermediateLangData) loadLanguage(pkg, lang, level + 1) errorFunc = -> if options.fallback && options.fallback != lang loadLanguage(pkg, options.fallback) ajaxOptions = url: file dataType: "json" async: false timeout: if options.timeout? then options.timeout else 500 success: successFunc error: errorFunc # hack to work with serving from local file system. # local file:// urls won't work in chrome: # http://code.google.com/p/chromium/issues/detail?id=40787 if window.location.protocol == "file:" ajaxOptions.error = (xhr) -> successFunc($.parseJSON(xhr.responseText)) $.ajax(ajaxOptions) notifyDelegateLanguageLoaded = (data) -> if options.callback? options.callback(data, defaultCallback) else defaultCallback(data) defaultCallback = (data) -> $.localize.data[pkg] = data wrappedSet.each -> elem = $(this) key = elem.data("localize") key ||= elem.attr("rel").match(/localize\[(.*?)\]/)[1] value = valueForKey(key, data) localizeElement(elem, key, value) if value? localizeElement = (elem, key, value) -> if elem.is('input') then localizeInputElement(elem, key, value) else if elem.is('textarea') then localizeInputElement(elem, key, value) else if elem.is('img') then localizeImageElement(elem, key, value) else if elem.is('optgroup') then localizeOptgroupElement(elem, key, value) else unless $.isPlainObject(value) then elem.html(value) localizeForSpecialKeys(elem, value) if $.isPlainObject(value) localizeInputElement = (elem, key, value) -> val = if $.isPlainObject(value) then value.value else value if elem.is("[placeholder]") elem.attr("placeholder", val) else elem.val(val) localizeForSpecialKeys = (elem, value) -> setAttrFromValueForKey(elem, "title", value) setAttrFromValueForKey(elem, "href", value) setTextFromValueForKey(elem, "text", value) localizeOptgroupElement = (elem, key, value) -> elem.attr("label", value) localizeImageElement = (elem, key, value) -> setAttrFromValueForKey(elem, "alt", value) setAttrFromValueForKey(elem, "src", value) valueForKey = (key, data) -> keys = key.split(/\./) value = data for key in keys value = if value? then value[key] else null value setAttrFromValueForKey = (elem, key, value) -> value = valueForKey(key, value) elem.attr(key, value) if value? setTextFromValueForKey = (elem, key, value) -> value = valueForKey(key, value) elem.text(value) if value? regexify = (string_or_regex_or_array) -> if typeof(string_or_regex_or_array) == "string" "^" + string_or_regex_or_array + "$" else if string_or_regex_or_array.length? (regexify(thing) for thing in string_or_regex_or_array).join("|") else string_or_regex_or_array lang = normaliseLang(if options.language then options.language else $.defaultLanguage) loadLanguage(pkg, lang, 1) unless (options.skipLanguage && lang.match(regexify(options.skipLanguage))) wrappedSet $.fn.localize = $.localize $.localize.data = {}
[ { "context": "le()\", ->\n testData = {\n name: \"test\",\n number: 2\n }\n it \"sho", "end": 127, "score": 0.9983453750610352, "start": 123, "tag": "NAME", "value": "test" } ]
test/file.coffee
impleri/sow
18
file = require "../src/file" describe "file ::", -> describe "saveFile()", -> testData = { name: "test", number: 2 } it "should save a file to the storage directory", -> expect(file.save "test", testData).to.be.true it "should not save a file to a non-existent directory", -> expect(file.save "test/bad", testData).to.be.false describe "readFile()", -> it "should read a file", -> expect(file.read "test").to.not.be.empty it "should not read a file from a non-existent directory", -> expect(file.read "test/bad").to.be.empty
142645
file = require "../src/file" describe "file ::", -> describe "saveFile()", -> testData = { name: "<NAME>", number: 2 } it "should save a file to the storage directory", -> expect(file.save "test", testData).to.be.true it "should not save a file to a non-existent directory", -> expect(file.save "test/bad", testData).to.be.false describe "readFile()", -> it "should read a file", -> expect(file.read "test").to.not.be.empty it "should not read a file from a non-existent directory", -> expect(file.read "test/bad").to.be.empty
true
file = require "../src/file" describe "file ::", -> describe "saveFile()", -> testData = { name: "PI:NAME:<NAME>END_PI", number: 2 } it "should save a file to the storage directory", -> expect(file.save "test", testData).to.be.true it "should not save a file to a non-existent directory", -> expect(file.save "test/bad", testData).to.be.false describe "readFile()", -> it "should read a file", -> expect(file.read "test").to.not.be.empty it "should not read a file from a non-existent directory", -> expect(file.read "test/bad").to.be.empty
[ { "context": "essage\n message.rawMessage.text = 'foo <mailto:name@example.com> bar'\n message.buildText @client, () ->\n ", "end": 2136, "score": 0.9999176263809204, "start": 2120, "tag": "EMAIL", "value": "name@example.com" }, { "context": "client, () ->\n message.t...
test/message.coffee
LaudateCorpus1/hubot-slack
1,371
should = require 'should' SlackMention = require('../src/mention') describe 'buildText()', -> it 'Should decode entities', -> message = @slacktextmessage message.rawMessage.text = 'foo &gt; &amp; &lt; &gt;&amp;&lt;' message.buildText @client, () -> message.text.should.equal('foo > & < >&<') it 'Should remove formatting around <http> links', -> message = @slacktextmessage message.rawMessage.text = 'foo <http://www.example.com> bar' message.buildText @client, () -> message.text.should.equal 'foo http://www.example.com bar' it 'Should remove formatting around <https> links', -> message = @slacktextmessage message.rawMessage.text = 'foo <https://www.example.com> bar' message.buildText @client, () -> message.text.should.equal 'foo https://www.example.com bar' it 'Should remove formatting around <skype> links', -> message = @slacktextmessage message.rawMessage.text = 'foo <skype:echo123?call> bar' message.buildText @client, () -> message.text.should.equal 'foo skype:echo123?call bar' it 'Should remove formatting around <https> links with a label', -> message = @slacktextmessage message.rawMessage.text = 'foo <https://www.example.com|label> bar' message.buildText @client, () -> message.text.should.equal 'foo label (https://www.example.com) bar' it 'Should remove formatting around <https> links with a substring label', -> message = @slacktextmessage message.rawMessage.text = 'foo <https://www.example.com|example.com> bar' message.buildText @client, () -> message.text.should.equal 'foo https://www.example.com bar' it 'Should remove formatting around <https> links with a label containing entities', -> message = @slacktextmessage message.rawMessage.text = 'foo <https://www.example.com|label &gt; &amp; &lt;> bar' message.buildText @client, () -> message.text.should.equal 'foo label > & < (https://www.example.com) bar' it 'Should remove formatting around <mailto> links', -> message = @slacktextmessage message.rawMessage.text = 'foo <mailto:name@example.com> bar' message.buildText @client, () -> message.text.should.equal 'foo name@example.com bar' it 'Should remove formatting around <mailto> links with an email label', -> message = @slacktextmessage message.rawMessage.text = 'foo <mailto:name@example.com|name@example.com> bar' message.buildText @client, () -> message.text.should.equal 'foo name@example.com bar' it 'Should handle empty text with attachments', -> message = @slacktextmessage message.rawMessage.text = undefined message.rawMessage.attachments = [ { fallback: 'first' }, ] message.buildText @client, () -> message.text.should.equal '\nfirst' it 'Should handle an empty set of attachments', -> message = @slacktextmessage message.rawMessage.text = 'foo' message.rawMessage.attachments = [] message.buildText @client, () -> message.text.should.equal 'foo' it 'Should change multiple links at once', -> message = @slacktextmessage message.rawMessage.text = 'foo <@U123|label> bar <#C123> <!channel> <https://www.example.com|label>' message.buildText @client, () -> message.text.should.equal 'foo @label bar #general @channel label (https://www.example.com)' it 'Should populate mentions with simple SlackMention object', -> message = @slacktextmessage message.rawMessage.text = 'foo <@U123> bar' message.buildText @client, () -> message.mentions.length.should.equal 1 message.mentions[0].type.should.equal 'user' message.mentions[0].id.should.equal 'U123' should.equal (message.mentions[0] instanceof SlackMention), true it 'Should populate mentions with simple SlackMention object with label', -> message = @slacktextmessage message.rawMessage.text = 'foo <@U123|label> bar' message.buildText @client, () -> message.mentions.length.should.equal 1 message.mentions[0].type.should.equal 'user' message.mentions[0].id.should.equal 'U123' should.equal message.mentions[0].info, undefined should.equal (message.mentions[0] instanceof SlackMention), true it 'Should populate mentions with multiple SlackMention objects', -> message = @slacktextmessage message.rawMessage.text = 'foo <@U123> bar <#C123> baz <@U123|label> qux' message.buildText @client, () -> message.mentions.length.should.equal 3 should.equal (message.mentions[0] instanceof SlackMention), true should.equal (message.mentions[1] instanceof SlackMention), true should.equal (message.mentions[2] instanceof SlackMention), true it 'Should populate mentions with simple SlackMention object if user in brain', -> @client.updateUserInBrain(@stubs.user) message = @slacktextmessage message.rawMessage.text = 'foo <@U123> bar' message.buildText @client, () -> message.mentions.length.should.equal 1 message.mentions[0].type.should.equal 'user' message.mentions[0].id.should.equal 'U123' should.equal (message.mentions[0] instanceof SlackMention), true it 'Should add conversation to cache', -> message = @slacktextmessage client = @client message.rawMessage.text = 'foo bar' message.buildText @client, () -> message.text.should.equal('foo bar') client.channelData.should.have.key('C123') it 'Should not modify conversation if it is not expired', -> message = @slacktextmessage client = @client client.channelData[@stubs.channel.id] = { channel: {id: @stubs.channel.id, name: 'baz'}, updated: Date.now() } message.rawMessage.text = 'foo bar' message.buildText @client, () -> message.text.should.equal('foo bar') client.channelData.should.have.key('C123') client.channelData['C123'].channel.name.should.equal 'baz' it 'Should handle conversation errors', -> message = @slacktextmessage_invalid_conversation client = @client message.rawMessage.text = 'foo bar' message.buildText @client, () -> client.robot.logger.logs?.error.length.should.equal 1 it 'Should flatten attachments', -> message = @slacktextmessage client = @client message.rawMessage.text = 'foo bar' message.rawMessage.attachments = [ { fallback: 'first' }, { fallback: 'second' } ] message.buildText @client, () -> message.text.should.equal 'foo bar\nfirst\nsecond' describe 'replaceLinks()', -> it 'Should change <@U123> links to @name', -> @slacktextmessage.replaceLinks @client, 'foo <@U123> bar' .then((text) -> text.should.equal 'foo @name bar') it 'Should change <@U123|label> links to @label', -> @slacktextmessage.replaceLinks @client, 'foo <@U123|label> bar' .then((text) -> text.should.equal 'foo @label bar') it 'Should handle invalid User ID gracefully', -> @slacktextmessage.replaceLinks @client, 'foo <@U555> bar' .then((text) -> text.should.equal 'foo <@U555> bar') it 'Should handle empty User API response', -> @slacktextmessage.replaceLinks @client, 'foo <@U789> bar' .then((text) -> text.should.equal 'foo <@U789> bar') it 'Should change <#C123> links to #general', -> @slacktextmessage.replaceLinks @client, 'foo <#C123> bar' .then((text) -> text.should.equal 'foo #general bar') it 'Should change <#C123|label> links to #label', -> @slacktextmessage.replaceLinks @client, 'foo <#C123|label> bar' .then((text) -> text.should.equal 'foo #label bar') it 'Should handle invalid Conversation ID gracefully', -> @slacktextmessage.replaceLinks @client, 'foo <#C555> bar' .then((text) -> text.should.equal 'foo <#C555> bar') it 'Should handle empty Conversation API response', -> @slacktextmessage.replaceLinks @client, 'foo <#C789> bar' .then((text) -> text.should.equal 'foo <#C789> bar') it 'Should change <!everyone> links to @everyone', -> @slacktextmessage.replaceLinks @client, 'foo <!everyone> bar' .then((text) -> text.should.equal 'foo @everyone bar') it 'Should change <!channel> links to @channel', -> @slacktextmessage.replaceLinks @client, 'foo <!channel> bar' .then((text) -> text.should.equal 'foo @channel bar') it 'Should change <!group> links to @group', -> @slacktextmessage.replaceLinks @client, 'foo <!group> bar' .then((text) -> text.should.equal 'foo @group bar') it 'Should change <!here> links to @here', -> @slacktextmessage.replaceLinks @client, 'foo <!here> bar' .then((text) -> text.should.equal 'foo @here bar') it 'Should change <!subteam^S123|@subteam> links to @subteam', -> @slacktextmessage.replaceLinks @client, 'foo <!subteam^S123|@subteam> bar' .then((text) -> text.should.equal 'foo @subteam bar') it 'Should change <!foobar|hello> links to hello', -> @slacktextmessage.replaceLinks @client, 'foo <!foobar|hello> bar' .then((text) -> text.should.equal 'foo hello bar') it 'Should leave <!foobar> links as-is when no label is provided', -> @slacktextmessage.replaceLinks @client, 'foo <!foobar> bar' .then((text) -> text.should.equal 'foo <!foobar> bar')
31200
should = require 'should' SlackMention = require('../src/mention') describe 'buildText()', -> it 'Should decode entities', -> message = @slacktextmessage message.rawMessage.text = 'foo &gt; &amp; &lt; &gt;&amp;&lt;' message.buildText @client, () -> message.text.should.equal('foo > & < >&<') it 'Should remove formatting around <http> links', -> message = @slacktextmessage message.rawMessage.text = 'foo <http://www.example.com> bar' message.buildText @client, () -> message.text.should.equal 'foo http://www.example.com bar' it 'Should remove formatting around <https> links', -> message = @slacktextmessage message.rawMessage.text = 'foo <https://www.example.com> bar' message.buildText @client, () -> message.text.should.equal 'foo https://www.example.com bar' it 'Should remove formatting around <skype> links', -> message = @slacktextmessage message.rawMessage.text = 'foo <skype:echo123?call> bar' message.buildText @client, () -> message.text.should.equal 'foo skype:echo123?call bar' it 'Should remove formatting around <https> links with a label', -> message = @slacktextmessage message.rawMessage.text = 'foo <https://www.example.com|label> bar' message.buildText @client, () -> message.text.should.equal 'foo label (https://www.example.com) bar' it 'Should remove formatting around <https> links with a substring label', -> message = @slacktextmessage message.rawMessage.text = 'foo <https://www.example.com|example.com> bar' message.buildText @client, () -> message.text.should.equal 'foo https://www.example.com bar' it 'Should remove formatting around <https> links with a label containing entities', -> message = @slacktextmessage message.rawMessage.text = 'foo <https://www.example.com|label &gt; &amp; &lt;> bar' message.buildText @client, () -> message.text.should.equal 'foo label > & < (https://www.example.com) bar' it 'Should remove formatting around <mailto> links', -> message = @slacktextmessage message.rawMessage.text = 'foo <mailto:<EMAIL>> bar' message.buildText @client, () -> message.text.should.equal 'foo <EMAIL> bar' it 'Should remove formatting around <mailto> links with an email label', -> message = @slacktextmessage message.rawMessage.text = 'foo <mailto:<EMAIL>|<EMAIL>> bar' message.buildText @client, () -> message.text.should.equal 'foo <EMAIL> bar' it 'Should handle empty text with attachments', -> message = @slacktextmessage message.rawMessage.text = undefined message.rawMessage.attachments = [ { fallback: 'first' }, ] message.buildText @client, () -> message.text.should.equal '\nfirst' it 'Should handle an empty set of attachments', -> message = @slacktextmessage message.rawMessage.text = 'foo' message.rawMessage.attachments = [] message.buildText @client, () -> message.text.should.equal 'foo' it 'Should change multiple links at once', -> message = @slacktextmessage message.rawMessage.text = 'foo <@U123|label> bar <#C123> <!channel> <https://www.example.com|label>' message.buildText @client, () -> message.text.should.equal 'foo @label bar #general @channel label (https://www.example.com)' it 'Should populate mentions with simple SlackMention object', -> message = @slacktextmessage message.rawMessage.text = 'foo <@U123> bar' message.buildText @client, () -> message.mentions.length.should.equal 1 message.mentions[0].type.should.equal 'user' message.mentions[0].id.should.equal 'U123' should.equal (message.mentions[0] instanceof SlackMention), true it 'Should populate mentions with simple SlackMention object with label', -> message = @slacktextmessage message.rawMessage.text = 'foo <@U123|label> bar' message.buildText @client, () -> message.mentions.length.should.equal 1 message.mentions[0].type.should.equal 'user' message.mentions[0].id.should.equal 'U123' should.equal message.mentions[0].info, undefined should.equal (message.mentions[0] instanceof SlackMention), true it 'Should populate mentions with multiple SlackMention objects', -> message = @slacktextmessage message.rawMessage.text = 'foo <@U123> bar <#C123> baz <@U123|label> qux' message.buildText @client, () -> message.mentions.length.should.equal 3 should.equal (message.mentions[0] instanceof SlackMention), true should.equal (message.mentions[1] instanceof SlackMention), true should.equal (message.mentions[2] instanceof SlackMention), true it 'Should populate mentions with simple SlackMention object if user in brain', -> @client.updateUserInBrain(@stubs.user) message = @slacktextmessage message.rawMessage.text = 'foo <@U123> bar' message.buildText @client, () -> message.mentions.length.should.equal 1 message.mentions[0].type.should.equal 'user' message.mentions[0].id.should.equal 'U123' should.equal (message.mentions[0] instanceof SlackMention), true it 'Should add conversation to cache', -> message = @slacktextmessage client = @client message.rawMessage.text = 'foo bar' message.buildText @client, () -> message.text.should.equal('foo bar') client.channelData.should.have.key('C123') it 'Should not modify conversation if it is not expired', -> message = @slacktextmessage client = @client client.channelData[@stubs.channel.id] = { channel: {id: @stubs.channel.id, name: 'baz'}, updated: Date.now() } message.rawMessage.text = 'foo bar' message.buildText @client, () -> message.text.should.equal('foo bar') client.channelData.should.have.key('C123') client.channelData['C123'].channel.name.should.equal 'baz' it 'Should handle conversation errors', -> message = @slacktextmessage_invalid_conversation client = @client message.rawMessage.text = 'foo bar' message.buildText @client, () -> client.robot.logger.logs?.error.length.should.equal 1 it 'Should flatten attachments', -> message = @slacktextmessage client = @client message.rawMessage.text = 'foo bar' message.rawMessage.attachments = [ { fallback: 'first' }, { fallback: 'second' } ] message.buildText @client, () -> message.text.should.equal 'foo bar\nfirst\nsecond' describe 'replaceLinks()', -> it 'Should change <@U123> links to @name', -> @slacktextmessage.replaceLinks @client, 'foo <@U123> bar' .then((text) -> text.should.equal 'foo @name bar') it 'Should change <@U123|label> links to @label', -> @slacktextmessage.replaceLinks @client, 'foo <@U123|label> bar' .then((text) -> text.should.equal 'foo @label bar') it 'Should handle invalid User ID gracefully', -> @slacktextmessage.replaceLinks @client, 'foo <@U555> bar' .then((text) -> text.should.equal 'foo <@U555> bar') it 'Should handle empty User API response', -> @slacktextmessage.replaceLinks @client, 'foo <@U789> bar' .then((text) -> text.should.equal 'foo <@U789> bar') it 'Should change <#C123> links to #general', -> @slacktextmessage.replaceLinks @client, 'foo <#C123> bar' .then((text) -> text.should.equal 'foo #general bar') it 'Should change <#C123|label> links to #label', -> @slacktextmessage.replaceLinks @client, 'foo <#C123|label> bar' .then((text) -> text.should.equal 'foo #label bar') it 'Should handle invalid Conversation ID gracefully', -> @slacktextmessage.replaceLinks @client, 'foo <#C555> bar' .then((text) -> text.should.equal 'foo <#C555> bar') it 'Should handle empty Conversation API response', -> @slacktextmessage.replaceLinks @client, 'foo <#C789> bar' .then((text) -> text.should.equal 'foo <#C789> bar') it 'Should change <!everyone> links to @everyone', -> @slacktextmessage.replaceLinks @client, 'foo <!everyone> bar' .then((text) -> text.should.equal 'foo @everyone bar') it 'Should change <!channel> links to @channel', -> @slacktextmessage.replaceLinks @client, 'foo <!channel> bar' .then((text) -> text.should.equal 'foo @channel bar') it 'Should change <!group> links to @group', -> @slacktextmessage.replaceLinks @client, 'foo <!group> bar' .then((text) -> text.should.equal 'foo @group bar') it 'Should change <!here> links to @here', -> @slacktextmessage.replaceLinks @client, 'foo <!here> bar' .then((text) -> text.should.equal 'foo @here bar') it 'Should change <!subteam^S123|@subteam> links to @subteam', -> @slacktextmessage.replaceLinks @client, 'foo <!subteam^S123|@subteam> bar' .then((text) -> text.should.equal 'foo @subteam bar') it 'Should change <!foobar|hello> links to hello', -> @slacktextmessage.replaceLinks @client, 'foo <!foobar|hello> bar' .then((text) -> text.should.equal 'foo hello bar') it 'Should leave <!foobar> links as-is when no label is provided', -> @slacktextmessage.replaceLinks @client, 'foo <!foobar> bar' .then((text) -> text.should.equal 'foo <!foobar> bar')
true
should = require 'should' SlackMention = require('../src/mention') describe 'buildText()', -> it 'Should decode entities', -> message = @slacktextmessage message.rawMessage.text = 'foo &gt; &amp; &lt; &gt;&amp;&lt;' message.buildText @client, () -> message.text.should.equal('foo > & < >&<') it 'Should remove formatting around <http> links', -> message = @slacktextmessage message.rawMessage.text = 'foo <http://www.example.com> bar' message.buildText @client, () -> message.text.should.equal 'foo http://www.example.com bar' it 'Should remove formatting around <https> links', -> message = @slacktextmessage message.rawMessage.text = 'foo <https://www.example.com> bar' message.buildText @client, () -> message.text.should.equal 'foo https://www.example.com bar' it 'Should remove formatting around <skype> links', -> message = @slacktextmessage message.rawMessage.text = 'foo <skype:echo123?call> bar' message.buildText @client, () -> message.text.should.equal 'foo skype:echo123?call bar' it 'Should remove formatting around <https> links with a label', -> message = @slacktextmessage message.rawMessage.text = 'foo <https://www.example.com|label> bar' message.buildText @client, () -> message.text.should.equal 'foo label (https://www.example.com) bar' it 'Should remove formatting around <https> links with a substring label', -> message = @slacktextmessage message.rawMessage.text = 'foo <https://www.example.com|example.com> bar' message.buildText @client, () -> message.text.should.equal 'foo https://www.example.com bar' it 'Should remove formatting around <https> links with a label containing entities', -> message = @slacktextmessage message.rawMessage.text = 'foo <https://www.example.com|label &gt; &amp; &lt;> bar' message.buildText @client, () -> message.text.should.equal 'foo label > & < (https://www.example.com) bar' it 'Should remove formatting around <mailto> links', -> message = @slacktextmessage message.rawMessage.text = 'foo <mailto:PI:EMAIL:<EMAIL>END_PI> bar' message.buildText @client, () -> message.text.should.equal 'foo PI:EMAIL:<EMAIL>END_PI bar' it 'Should remove formatting around <mailto> links with an email label', -> message = @slacktextmessage message.rawMessage.text = 'foo <mailto:PI:EMAIL:<EMAIL>END_PI|PI:EMAIL:<EMAIL>END_PI> bar' message.buildText @client, () -> message.text.should.equal 'foo PI:EMAIL:<EMAIL>END_PI bar' it 'Should handle empty text with attachments', -> message = @slacktextmessage message.rawMessage.text = undefined message.rawMessage.attachments = [ { fallback: 'first' }, ] message.buildText @client, () -> message.text.should.equal '\nfirst' it 'Should handle an empty set of attachments', -> message = @slacktextmessage message.rawMessage.text = 'foo' message.rawMessage.attachments = [] message.buildText @client, () -> message.text.should.equal 'foo' it 'Should change multiple links at once', -> message = @slacktextmessage message.rawMessage.text = 'foo <@U123|label> bar <#C123> <!channel> <https://www.example.com|label>' message.buildText @client, () -> message.text.should.equal 'foo @label bar #general @channel label (https://www.example.com)' it 'Should populate mentions with simple SlackMention object', -> message = @slacktextmessage message.rawMessage.text = 'foo <@U123> bar' message.buildText @client, () -> message.mentions.length.should.equal 1 message.mentions[0].type.should.equal 'user' message.mentions[0].id.should.equal 'U123' should.equal (message.mentions[0] instanceof SlackMention), true it 'Should populate mentions with simple SlackMention object with label', -> message = @slacktextmessage message.rawMessage.text = 'foo <@U123|label> bar' message.buildText @client, () -> message.mentions.length.should.equal 1 message.mentions[0].type.should.equal 'user' message.mentions[0].id.should.equal 'U123' should.equal message.mentions[0].info, undefined should.equal (message.mentions[0] instanceof SlackMention), true it 'Should populate mentions with multiple SlackMention objects', -> message = @slacktextmessage message.rawMessage.text = 'foo <@U123> bar <#C123> baz <@U123|label> qux' message.buildText @client, () -> message.mentions.length.should.equal 3 should.equal (message.mentions[0] instanceof SlackMention), true should.equal (message.mentions[1] instanceof SlackMention), true should.equal (message.mentions[2] instanceof SlackMention), true it 'Should populate mentions with simple SlackMention object if user in brain', -> @client.updateUserInBrain(@stubs.user) message = @slacktextmessage message.rawMessage.text = 'foo <@U123> bar' message.buildText @client, () -> message.mentions.length.should.equal 1 message.mentions[0].type.should.equal 'user' message.mentions[0].id.should.equal 'U123' should.equal (message.mentions[0] instanceof SlackMention), true it 'Should add conversation to cache', -> message = @slacktextmessage client = @client message.rawMessage.text = 'foo bar' message.buildText @client, () -> message.text.should.equal('foo bar') client.channelData.should.have.key('C123') it 'Should not modify conversation if it is not expired', -> message = @slacktextmessage client = @client client.channelData[@stubs.channel.id] = { channel: {id: @stubs.channel.id, name: 'baz'}, updated: Date.now() } message.rawMessage.text = 'foo bar' message.buildText @client, () -> message.text.should.equal('foo bar') client.channelData.should.have.key('C123') client.channelData['C123'].channel.name.should.equal 'baz' it 'Should handle conversation errors', -> message = @slacktextmessage_invalid_conversation client = @client message.rawMessage.text = 'foo bar' message.buildText @client, () -> client.robot.logger.logs?.error.length.should.equal 1 it 'Should flatten attachments', -> message = @slacktextmessage client = @client message.rawMessage.text = 'foo bar' message.rawMessage.attachments = [ { fallback: 'first' }, { fallback: 'second' } ] message.buildText @client, () -> message.text.should.equal 'foo bar\nfirst\nsecond' describe 'replaceLinks()', -> it 'Should change <@U123> links to @name', -> @slacktextmessage.replaceLinks @client, 'foo <@U123> bar' .then((text) -> text.should.equal 'foo @name bar') it 'Should change <@U123|label> links to @label', -> @slacktextmessage.replaceLinks @client, 'foo <@U123|label> bar' .then((text) -> text.should.equal 'foo @label bar') it 'Should handle invalid User ID gracefully', -> @slacktextmessage.replaceLinks @client, 'foo <@U555> bar' .then((text) -> text.should.equal 'foo <@U555> bar') it 'Should handle empty User API response', -> @slacktextmessage.replaceLinks @client, 'foo <@U789> bar' .then((text) -> text.should.equal 'foo <@U789> bar') it 'Should change <#C123> links to #general', -> @slacktextmessage.replaceLinks @client, 'foo <#C123> bar' .then((text) -> text.should.equal 'foo #general bar') it 'Should change <#C123|label> links to #label', -> @slacktextmessage.replaceLinks @client, 'foo <#C123|label> bar' .then((text) -> text.should.equal 'foo #label bar') it 'Should handle invalid Conversation ID gracefully', -> @slacktextmessage.replaceLinks @client, 'foo <#C555> bar' .then((text) -> text.should.equal 'foo <#C555> bar') it 'Should handle empty Conversation API response', -> @slacktextmessage.replaceLinks @client, 'foo <#C789> bar' .then((text) -> text.should.equal 'foo <#C789> bar') it 'Should change <!everyone> links to @everyone', -> @slacktextmessage.replaceLinks @client, 'foo <!everyone> bar' .then((text) -> text.should.equal 'foo @everyone bar') it 'Should change <!channel> links to @channel', -> @slacktextmessage.replaceLinks @client, 'foo <!channel> bar' .then((text) -> text.should.equal 'foo @channel bar') it 'Should change <!group> links to @group', -> @slacktextmessage.replaceLinks @client, 'foo <!group> bar' .then((text) -> text.should.equal 'foo @group bar') it 'Should change <!here> links to @here', -> @slacktextmessage.replaceLinks @client, 'foo <!here> bar' .then((text) -> text.should.equal 'foo @here bar') it 'Should change <!subteam^S123|@subteam> links to @subteam', -> @slacktextmessage.replaceLinks @client, 'foo <!subteam^S123|@subteam> bar' .then((text) -> text.should.equal 'foo @subteam bar') it 'Should change <!foobar|hello> links to hello', -> @slacktextmessage.replaceLinks @client, 'foo <!foobar|hello> bar' .then((text) -> text.should.equal 'foo hello bar') it 'Should leave <!foobar> links as-is when no label is provided', -> @slacktextmessage.replaceLinks @client, 'foo <!foobar> bar' .then((text) -> text.should.equal 'foo <!foobar> bar')
[ { "context": " <p>\n Jane Doe - Web Developer\n <smal", "end": 2666, "score": 0.9998056888580322, "start": 2658, "tag": "NAME", "value": "Jane Doe" } ]
src/components/header.coffee
brianshaler/kerplunk-nav
0
_ = require 'lodash' React = require 'react' {DOM} = React module.exports = React.createFactory React.createClass render: -> topBarComponents = [] navbar = @props.globals.public.navbar ? {} for componentName, active of navbar Component = @props.getComponent componentName topBarComponents.push Component _.extend {key: componentName}, @props DOM.header className: 'header' , DOM.a href: '/admin' className: 'logo' , DOM.img src: '/images/kerplunk/header_logo.png' alt: 'Kerplunk!' style: display: 'none' DOM.nav className: 'navbar navbar-static-top' role: 'navigation' , DOM.a href: '#' onClick: @props.toggleNav className: 'navbar-btn sidebar-toggle' role: 'button' , DOM.span {className: 'sr-only'}, 'Toggle navigation' DOM.span className: 'icon-bar' DOM.span className: 'icon-bar' DOM.span className: 'icon-bar' DOM.div className: 'navbar-right' , DOM.ul className: 'nav navbar-nav' , topBarComponents ### <nav class="navbar navbar-static-top" role="navigation"> <!-- Sidebar toggle button--> <a href="#" class="navbar-btn sidebar-toggle" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <div class="navbar-right"> <ul class="nav navbar-nav"> <!-- Messages: style can be found in dropdown.less--> <%= (1==1 ? '' : Kerplunk.getTemplate('kerplunk-dashboard-skin.navbarMessages')({Kerplunk: Kerplunk})) %> <!-- Notifications: style can be found in dropdown.less --> <%= Kerplunk.getTemplate('kerplunk-dashboard-skin.navbarNotifications')({Kerplunk: Kerplunk}) %> <!-- User Account: style can be found in dropdown.less --> <li class="dropdown user user-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="glyphicon glyphicon-user"></i> <span><span class="hidden-mobile">User</span> <i class="caret"></i></span> </a> <ul class="dropdown-menu"> <!-- User image --> <li class="user-header bg-light-blue"> <img class="img-circle" alt="User Image" /> <p> Jane Doe - Web Developer <small>Member since Nov. 2012</small> </p> </li> <!-- Menu Body --> <li class="user-body"> <div class="col-xs-4 text-center"> <a href="#">123<br />Followers</a> </div> <div class="col-xs-4 text-center"> <a href="#">123<br />Sales</a> </div> <div class="col-xs-4 text-center"> <a href="#"><strong>123</strong>Friends</a> </div> </li> <!-- Menu Footer--> <li class="user-footer"> <div class="pull-left"> <a href="#" class="btn btn-default btn-flat">Profile</a> </div> <div class="pull-right"> <a href="#" class="btn btn-default btn-flat">Sign out</a> </div> </li> </ul> </li> </ul> </div> </nav> ###
84044
_ = require 'lodash' React = require 'react' {DOM} = React module.exports = React.createFactory React.createClass render: -> topBarComponents = [] navbar = @props.globals.public.navbar ? {} for componentName, active of navbar Component = @props.getComponent componentName topBarComponents.push Component _.extend {key: componentName}, @props DOM.header className: 'header' , DOM.a href: '/admin' className: 'logo' , DOM.img src: '/images/kerplunk/header_logo.png' alt: 'Kerplunk!' style: display: 'none' DOM.nav className: 'navbar navbar-static-top' role: 'navigation' , DOM.a href: '#' onClick: @props.toggleNav className: 'navbar-btn sidebar-toggle' role: 'button' , DOM.span {className: 'sr-only'}, 'Toggle navigation' DOM.span className: 'icon-bar' DOM.span className: 'icon-bar' DOM.span className: 'icon-bar' DOM.div className: 'navbar-right' , DOM.ul className: 'nav navbar-nav' , topBarComponents ### <nav class="navbar navbar-static-top" role="navigation"> <!-- Sidebar toggle button--> <a href="#" class="navbar-btn sidebar-toggle" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <div class="navbar-right"> <ul class="nav navbar-nav"> <!-- Messages: style can be found in dropdown.less--> <%= (1==1 ? '' : Kerplunk.getTemplate('kerplunk-dashboard-skin.navbarMessages')({Kerplunk: Kerplunk})) %> <!-- Notifications: style can be found in dropdown.less --> <%= Kerplunk.getTemplate('kerplunk-dashboard-skin.navbarNotifications')({Kerplunk: Kerplunk}) %> <!-- User Account: style can be found in dropdown.less --> <li class="dropdown user user-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="glyphicon glyphicon-user"></i> <span><span class="hidden-mobile">User</span> <i class="caret"></i></span> </a> <ul class="dropdown-menu"> <!-- User image --> <li class="user-header bg-light-blue"> <img class="img-circle" alt="User Image" /> <p> <NAME> - Web Developer <small>Member since Nov. 2012</small> </p> </li> <!-- Menu Body --> <li class="user-body"> <div class="col-xs-4 text-center"> <a href="#">123<br />Followers</a> </div> <div class="col-xs-4 text-center"> <a href="#">123<br />Sales</a> </div> <div class="col-xs-4 text-center"> <a href="#"><strong>123</strong>Friends</a> </div> </li> <!-- Menu Footer--> <li class="user-footer"> <div class="pull-left"> <a href="#" class="btn btn-default btn-flat">Profile</a> </div> <div class="pull-right"> <a href="#" class="btn btn-default btn-flat">Sign out</a> </div> </li> </ul> </li> </ul> </div> </nav> ###
true
_ = require 'lodash' React = require 'react' {DOM} = React module.exports = React.createFactory React.createClass render: -> topBarComponents = [] navbar = @props.globals.public.navbar ? {} for componentName, active of navbar Component = @props.getComponent componentName topBarComponents.push Component _.extend {key: componentName}, @props DOM.header className: 'header' , DOM.a href: '/admin' className: 'logo' , DOM.img src: '/images/kerplunk/header_logo.png' alt: 'Kerplunk!' style: display: 'none' DOM.nav className: 'navbar navbar-static-top' role: 'navigation' , DOM.a href: '#' onClick: @props.toggleNav className: 'navbar-btn sidebar-toggle' role: 'button' , DOM.span {className: 'sr-only'}, 'Toggle navigation' DOM.span className: 'icon-bar' DOM.span className: 'icon-bar' DOM.span className: 'icon-bar' DOM.div className: 'navbar-right' , DOM.ul className: 'nav navbar-nav' , topBarComponents ### <nav class="navbar navbar-static-top" role="navigation"> <!-- Sidebar toggle button--> <a href="#" class="navbar-btn sidebar-toggle" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <div class="navbar-right"> <ul class="nav navbar-nav"> <!-- Messages: style can be found in dropdown.less--> <%= (1==1 ? '' : Kerplunk.getTemplate('kerplunk-dashboard-skin.navbarMessages')({Kerplunk: Kerplunk})) %> <!-- Notifications: style can be found in dropdown.less --> <%= Kerplunk.getTemplate('kerplunk-dashboard-skin.navbarNotifications')({Kerplunk: Kerplunk}) %> <!-- User Account: style can be found in dropdown.less --> <li class="dropdown user user-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="glyphicon glyphicon-user"></i> <span><span class="hidden-mobile">User</span> <i class="caret"></i></span> </a> <ul class="dropdown-menu"> <!-- User image --> <li class="user-header bg-light-blue"> <img class="img-circle" alt="User Image" /> <p> PI:NAME:<NAME>END_PI - Web Developer <small>Member since Nov. 2012</small> </p> </li> <!-- Menu Body --> <li class="user-body"> <div class="col-xs-4 text-center"> <a href="#">123<br />Followers</a> </div> <div class="col-xs-4 text-center"> <a href="#">123<br />Sales</a> </div> <div class="col-xs-4 text-center"> <a href="#"><strong>123</strong>Friends</a> </div> </li> <!-- Menu Footer--> <li class="user-footer"> <div class="pull-left"> <a href="#" class="btn btn-default btn-flat">Profile</a> </div> <div class="pull-right"> <a href="#" class="btn btn-default btn-flat">Sign out</a> </div> </li> </ul> </li> </ul> </div> </nav> ###
[ { "context": "\n# \t\tuser:\n# \t\t\ttype: \"master_detail\"\n# \t\t\tlabel:\"用户\"\n# \t\t\treference_to: \"users\"\n# \t\tyear:\n# \t\t\ttype:\"", "end": 169, "score": 0.7318292856216431, "start": 167, "tag": "NAME", "value": "用户" } ]
creator/packages/steedos-app-workflow/models/statistic_instance.coffee
yicone/steedos-platform
42
# Creator.Objects.instances_statistic = # name: "instances_statistic" # icon: "metrics" # label: "审批效率" # fields: # user: # type: "master_detail" # label:"用户" # reference_to: "users" # year: # type:"number" # label:"年度" # month: # type:"number" # label:"月度" # month_finished_count: # type:"number" # label:"已处理总数" # inbox_count: # type:"number" # label:"待处理总数" # month_finished_time: # type:"number" # scale:2 # label:"已处理总耗时" # inbox_time: # type:"number" # scale:2 # label:"待审核总耗时" # month_finished_avg: # type:"number" # scale:2 # label:"已处理平均耗时" # inbox_avg: # type:"number" # scale:2 # label:"待处理平均耗时" # avg_time: # type:"number" # scale:2 # label:"总平均耗时" # owner_organization: # label:"主部门" # type: "lookup" # reference_to: "organizations" # owner_organizations: # label:"所属部门" # type: "lookup" # reference_to: "organizations" # multiple: true # defaultValue: [] # company_id: # required: Meteor.settings?.public?.is_group_company # omit: false # hidden: false # list_views: # all: # label: "所有" # filter_scope: "space" # columns: ["user","year","month", # "month_finished_count","inbox_count", # "month_finished_time","inbox_time", # "month_finished_avg","inbox_avg","avg_time", # "owner_organization", # "owner_organizations","company_id"] # permission_set: # user: # allowCreate: false # allowDelete: false # allowEdit: false # allowRead: true # modifyAllRecords: false # viewAllRecords: false # admin: # allowCreate: false # allowDelete: false # allowEdit: false # allowRead: false # modifyAllRecords: false # viewAllRecords: true # workflow_admin: # allowCreate: false # allowDelete: false # allowEdit: false # allowRead: false # modifyAllRecords: false # viewAllRecords: false # modifyCompanyRecords: true # viewCompanyRecords: true # disabled_list_views: [] # disabled_actions: [] # unreadable_fields: [] # uneditable_fields: [] # unrelated_objects: []
189182
# Creator.Objects.instances_statistic = # name: "instances_statistic" # icon: "metrics" # label: "审批效率" # fields: # user: # type: "master_detail" # label:"<NAME>" # reference_to: "users" # year: # type:"number" # label:"年度" # month: # type:"number" # label:"月度" # month_finished_count: # type:"number" # label:"已处理总数" # inbox_count: # type:"number" # label:"待处理总数" # month_finished_time: # type:"number" # scale:2 # label:"已处理总耗时" # inbox_time: # type:"number" # scale:2 # label:"待审核总耗时" # month_finished_avg: # type:"number" # scale:2 # label:"已处理平均耗时" # inbox_avg: # type:"number" # scale:2 # label:"待处理平均耗时" # avg_time: # type:"number" # scale:2 # label:"总平均耗时" # owner_organization: # label:"主部门" # type: "lookup" # reference_to: "organizations" # owner_organizations: # label:"所属部门" # type: "lookup" # reference_to: "organizations" # multiple: true # defaultValue: [] # company_id: # required: Meteor.settings?.public?.is_group_company # omit: false # hidden: false # list_views: # all: # label: "所有" # filter_scope: "space" # columns: ["user","year","month", # "month_finished_count","inbox_count", # "month_finished_time","inbox_time", # "month_finished_avg","inbox_avg","avg_time", # "owner_organization", # "owner_organizations","company_id"] # permission_set: # user: # allowCreate: false # allowDelete: false # allowEdit: false # allowRead: true # modifyAllRecords: false # viewAllRecords: false # admin: # allowCreate: false # allowDelete: false # allowEdit: false # allowRead: false # modifyAllRecords: false # viewAllRecords: true # workflow_admin: # allowCreate: false # allowDelete: false # allowEdit: false # allowRead: false # modifyAllRecords: false # viewAllRecords: false # modifyCompanyRecords: true # viewCompanyRecords: true # disabled_list_views: [] # disabled_actions: [] # unreadable_fields: [] # uneditable_fields: [] # unrelated_objects: []
true
# Creator.Objects.instances_statistic = # name: "instances_statistic" # icon: "metrics" # label: "审批效率" # fields: # user: # type: "master_detail" # label:"PI:NAME:<NAME>END_PI" # reference_to: "users" # year: # type:"number" # label:"年度" # month: # type:"number" # label:"月度" # month_finished_count: # type:"number" # label:"已处理总数" # inbox_count: # type:"number" # label:"待处理总数" # month_finished_time: # type:"number" # scale:2 # label:"已处理总耗时" # inbox_time: # type:"number" # scale:2 # label:"待审核总耗时" # month_finished_avg: # type:"number" # scale:2 # label:"已处理平均耗时" # inbox_avg: # type:"number" # scale:2 # label:"待处理平均耗时" # avg_time: # type:"number" # scale:2 # label:"总平均耗时" # owner_organization: # label:"主部门" # type: "lookup" # reference_to: "organizations" # owner_organizations: # label:"所属部门" # type: "lookup" # reference_to: "organizations" # multiple: true # defaultValue: [] # company_id: # required: Meteor.settings?.public?.is_group_company # omit: false # hidden: false # list_views: # all: # label: "所有" # filter_scope: "space" # columns: ["user","year","month", # "month_finished_count","inbox_count", # "month_finished_time","inbox_time", # "month_finished_avg","inbox_avg","avg_time", # "owner_organization", # "owner_organizations","company_id"] # permission_set: # user: # allowCreate: false # allowDelete: false # allowEdit: false # allowRead: true # modifyAllRecords: false # viewAllRecords: false # admin: # allowCreate: false # allowDelete: false # allowEdit: false # allowRead: false # modifyAllRecords: false # viewAllRecords: true # workflow_admin: # allowCreate: false # allowDelete: false # allowEdit: false # allowRead: false # modifyAllRecords: false # viewAllRecords: false # modifyCompanyRecords: true # viewCompanyRecords: true # disabled_list_views: [] # disabled_actions: [] # unreadable_fields: [] # uneditable_fields: [] # unrelated_objects: []
[ { "context": "collection 'posts'\n\nPost.create text: 'Zerg on Tarsonis!'\n\n#\n\n# Simple and flexible [Queries and Scopes](", "end": 390, "score": 0.6496192812919617, "start": 385, "tag": "NAME", "value": "sonis" }, { "context": "basics.html)):\n#\n# git clone git://github.com/...
examples/model.coffee
wanbok/mongo-model
1
# Domain Model for MongoDB (Node.JS). # # [Slides, introduction](presentations/introduction/index.html) (with [video](http://www.youtube.com/watch?v=HB2Bkcgdjms)). # # [Slides from MoscowJS 2012](presentations/moscowjs12/index.html). # ### Features # [Models](basics.html) are JavaScript Objects. class global.Post extends Model @collection 'posts' Post.create text: 'Zerg on Tarsonis!' # # Simple and flexible [Queries and Scopes](queries.html). Post.first status: 'published' Post.find(status: 'published').sort(createdAt: -1). limit(25).all() # # [Embedded Models](embedded.html) with [validations](validations.html), # and [callbacks](callbacks.html). post.comments = [] comment = new Comment text: "Can't believe it!" post.comments.push comment post.save() # # [Associations](associations.html), 1 to 1, 1 to N, N to M. post.comments().create text: "Can't believe it!" # # [Callbacks](callback.html) and [Validations](validations.html) class global.Post extends Model @after 'delete', (callback) -> @comments().delete callback # # Same API for [Driver](driver.html) and Model. posts = db.collection 'posts' posts.find(status: 'published').sort(createdAt: -1). limit(25).all() # # Use it with plain JavaScript and Callbacks or in [synchronous mode](synchronous.html) with Fibers. Post.first {status: 'published'}, (err, post) -> console.log post console.log Post.first(status: 'published') # ### Installation # # npm install mongo-model # # ### Examples # # [Basics](basics.html), [Embedded Models](embedded.html), [Queries and Scopes](queries.html), # [Validations](validations.html), [Callbacks](callbacks.html), [Associations](associations.html), # [Attribute Assignment & Mass Assignment](assignment.html), [Upsersts and Modifiers](modifiers.html), # [Working with Connnections and Databases](database.html), [Optional Synchronous Mode](synchronous.html). # # You may also consider using only part of the Model - the [Driver](driver.html). It's independent from # the Model. # # All examples written in **optional** [synchronous](synchronous.html) mode (with Fibers), it's made # for simplicity and to demonstrate how to use Model with Fibers & CoffeeScript. # # Note: Model itself doesn't depends on Fibers or CoffeeScript, **You can use it with plain old JavaScript and # asynchronous callbacks**. # # But, You need to install Fibers, Underscore & CoffeeScript to run examples: # # npm install coffee-script fibers underscore # # Next clone project, go to `docs/samples` folder and run any example (I recommend You to start # with [basics](basics.html)): # # git clone git://github.com/alexeypetrushin/mongo-model.git # cd mongo-model/docs/samples # coffee basics.coffee # # Note: if there will be error like `no coffee command` - try install coffee-script # as global package `npm install coffee-script -g`. # # ### Project # # The project is [hosted on GitHub](https://github.com/alexeypetrushin/mongo-model). # You can report bugs and discuss features # on the [issues page](https://github.com/alexeypetrushin/mongo-model/issues).
86183
# Domain Model for MongoDB (Node.JS). # # [Slides, introduction](presentations/introduction/index.html) (with [video](http://www.youtube.com/watch?v=HB2Bkcgdjms)). # # [Slides from MoscowJS 2012](presentations/moscowjs12/index.html). # ### Features # [Models](basics.html) are JavaScript Objects. class global.Post extends Model @collection 'posts' Post.create text: 'Zerg on Tar<NAME>!' # # Simple and flexible [Queries and Scopes](queries.html). Post.first status: 'published' Post.find(status: 'published').sort(createdAt: -1). limit(25).all() # # [Embedded Models](embedded.html) with [validations](validations.html), # and [callbacks](callbacks.html). post.comments = [] comment = new Comment text: "Can't believe it!" post.comments.push comment post.save() # # [Associations](associations.html), 1 to 1, 1 to N, N to M. post.comments().create text: "Can't believe it!" # # [Callbacks](callback.html) and [Validations](validations.html) class global.Post extends Model @after 'delete', (callback) -> @comments().delete callback # # Same API for [Driver](driver.html) and Model. posts = db.collection 'posts' posts.find(status: 'published').sort(createdAt: -1). limit(25).all() # # Use it with plain JavaScript and Callbacks or in [synchronous mode](synchronous.html) with Fibers. Post.first {status: 'published'}, (err, post) -> console.log post console.log Post.first(status: 'published') # ### Installation # # npm install mongo-model # # ### Examples # # [Basics](basics.html), [Embedded Models](embedded.html), [Queries and Scopes](queries.html), # [Validations](validations.html), [Callbacks](callbacks.html), [Associations](associations.html), # [Attribute Assignment & Mass Assignment](assignment.html), [Upsersts and Modifiers](modifiers.html), # [Working with Connnections and Databases](database.html), [Optional Synchronous Mode](synchronous.html). # # You may also consider using only part of the Model - the [Driver](driver.html). It's independent from # the Model. # # All examples written in **optional** [synchronous](synchronous.html) mode (with Fibers), it's made # for simplicity and to demonstrate how to use Model with Fibers & CoffeeScript. # # Note: Model itself doesn't depends on Fibers or CoffeeScript, **You can use it with plain old JavaScript and # asynchronous callbacks**. # # But, You need to install Fibers, Underscore & CoffeeScript to run examples: # # npm install coffee-script fibers underscore # # Next clone project, go to `docs/samples` folder and run any example (I recommend You to start # with [basics](basics.html)): # # git clone git://github.com/alexeypetrushin/mongo-model.git # cd mongo-model/docs/samples # coffee basics.coffee # # Note: if there will be error like `no coffee command` - try install coffee-script # as global package `npm install coffee-script -g`. # # ### Project # # The project is [hosted on GitHub](https://github.com/alexeypetrushin/mongo-model). # You can report bugs and discuss features # on the [issues page](https://github.com/alexeypetrushin/mongo-model/issues).
true
# Domain Model for MongoDB (Node.JS). # # [Slides, introduction](presentations/introduction/index.html) (with [video](http://www.youtube.com/watch?v=HB2Bkcgdjms)). # # [Slides from MoscowJS 2012](presentations/moscowjs12/index.html). # ### Features # [Models](basics.html) are JavaScript Objects. class global.Post extends Model @collection 'posts' Post.create text: 'Zerg on TarPI:NAME:<NAME>END_PI!' # # Simple and flexible [Queries and Scopes](queries.html). Post.first status: 'published' Post.find(status: 'published').sort(createdAt: -1). limit(25).all() # # [Embedded Models](embedded.html) with [validations](validations.html), # and [callbacks](callbacks.html). post.comments = [] comment = new Comment text: "Can't believe it!" post.comments.push comment post.save() # # [Associations](associations.html), 1 to 1, 1 to N, N to M. post.comments().create text: "Can't believe it!" # # [Callbacks](callback.html) and [Validations](validations.html) class global.Post extends Model @after 'delete', (callback) -> @comments().delete callback # # Same API for [Driver](driver.html) and Model. posts = db.collection 'posts' posts.find(status: 'published').sort(createdAt: -1). limit(25).all() # # Use it with plain JavaScript and Callbacks or in [synchronous mode](synchronous.html) with Fibers. Post.first {status: 'published'}, (err, post) -> console.log post console.log Post.first(status: 'published') # ### Installation # # npm install mongo-model # # ### Examples # # [Basics](basics.html), [Embedded Models](embedded.html), [Queries and Scopes](queries.html), # [Validations](validations.html), [Callbacks](callbacks.html), [Associations](associations.html), # [Attribute Assignment & Mass Assignment](assignment.html), [Upsersts and Modifiers](modifiers.html), # [Working with Connnections and Databases](database.html), [Optional Synchronous Mode](synchronous.html). # # You may also consider using only part of the Model - the [Driver](driver.html). It's independent from # the Model. # # All examples written in **optional** [synchronous](synchronous.html) mode (with Fibers), it's made # for simplicity and to demonstrate how to use Model with Fibers & CoffeeScript. # # Note: Model itself doesn't depends on Fibers or CoffeeScript, **You can use it with plain old JavaScript and # asynchronous callbacks**. # # But, You need to install Fibers, Underscore & CoffeeScript to run examples: # # npm install coffee-script fibers underscore # # Next clone project, go to `docs/samples` folder and run any example (I recommend You to start # with [basics](basics.html)): # # git clone git://github.com/alexeypetrushin/mongo-model.git # cd mongo-model/docs/samples # coffee basics.coffee # # Note: if there will be error like `no coffee command` - try install coffee-script # as global package `npm install coffee-script -g`. # # ### Project # # The project is [hosted on GitHub](https://github.com/alexeypetrushin/mongo-model). # You can report bugs and discuss features # on the [issues page](https://github.com/alexeypetrushin/mongo-model/issues).
[ { "context": "te('departure', {\n key: 'departureAirport._id'\n operator: '$in'\n value: parsedCod", "end": 15934, "score": 0.6984644532203674, "start": 15932, "tag": "KEY", "value": "id" } ]
app/packages/grits-net-meteor/client/grits_filter_criteria.coffee
billdmcconnell/fliightData
4
_ignoreFields = [] _validFields = ['departure', 'effectiveDate', 'discontinuedDate'] _validOperators = ['$gte', '$gt', '$lte', '$lt', '$eq', '$ne', '$in', '$near', null] _state = null # keeps track of the query string state # local/private minimongo collection _Collection = new (Mongo.Collection)(null) # local/private Astronomy model for maintaining filter criteria _Filter = Astro.Class( name: 'FilterCriteria' collection: _Collection transform: true fields: ['key', 'operator', 'value'] validators: { key: [ Validators.required(), Validators.string() ], operator: [ Validators.required(), Validators.string(), Validators.choice(_validOperators) ], value: Validators.required() } ) # GritsFilterCriteria, this object provides the interface for # accessing the UI filter box. The setter methods may be called # programmatically or the reactive var can be set by event handers # within the UI. The entire object maintains its own state. # # @note exports as a 'singleton' class GritsFilterCriteria constructor: () -> self = this # reactive var used to update the UI when the query state has changed self.stateChanged = new ReactiveVar(null) # setup an instance variable that contains todays date. This will be used # to set the initial Start and End dates to the Operating Date Range now = new Date() month = now.getMonth() date = now.getDate() year = now.getFullYear() self._today = new Date(year, month, date) # this._baseState keeps track of the initial plugin state after any init # methods have run self._baseState = {} # processing queue self._queue = null # reactive vars to track form binding # departures self.departures = new ReactiveVar([]) self.trackDepartures() # operatingDateRangeStart self.operatingDateRangeStart = new ReactiveVar(null) self.trackOperatingDateRangeStart() # operatingDateRangeEnd self.operatingDateRangeEnd = new ReactiveVar(null) self.trackOperatingDateRangeEnd() # airportCounts # during a simulation the airports are counted to update the heatmap self.airportCounts = {} # is the simulation running? self.isSimulatorRunning = new ReactiveVar(false) return # initialize the start date of the filter 'discontinuedDate' # # @return [String] dateString, formatted MM/DD/YY initStart: () -> self = this start = self._today self.createOrUpdate('discontinuedDate', {key: 'discontinuedDate', operator: '$gte', value: start}) query = @getQueryObject() # update the state logic for the indicator _state = JSON.stringify(query) self._baseState = JSON.stringify(query) month = start.getMonth() + 1 date = start.getDate() year = start.getFullYear() yearStr = year.toString().slice(2,4) self.operatingDateRangeStart.set(new Date(year, month, date)) return "#{month}/#{date}/#{yearStr}" # initialize the end date through the 'effectiveDate' filter # # @return [String] dateString, formatted MM/DD/YY initEnd: () -> self = this end = moment(@_today).add(7, 'd').toDate() self.createOrUpdate('effectiveDate', {key: 'effectiveDate', operator: '$lte', value: end}) # get the query object query = self.getQueryObject() # update the state logic for the indicator _state = JSON.stringify(query) self._baseState = JSON.stringify(query) month = end.getMonth() + 1 date = end.getDate() year = end.getFullYear() yearStr = year.toString().slice(2,4) self.operatingDateRangeEnd.set(new Date(year, month, date)) return "#{month}/#{date}/#{yearStr}" # Creates a new filter criteria and adds it to the collection or updates # the collection if it already exists # # @param [String] id, the name of the filter criteria # @return [Object] Astronomy model 'FilterCriteria' createOrUpdate: (id, fields) -> self = this if _.indexOf(_validFields, id) < 0 throw new Error('Invalid filter: ' + id) obj = _Collection.findOne({_id: id}) if obj obj.set(fields) if obj.validate() == false throw new Error(_.values(obj.getValidationErrors())) obj.save() return obj else _.extend(fields, {_id: id}) obj = new _Filter(fields) if obj.validate() == false throw new Error(_.values(obj.getValidationErrors())) obj.save() return obj # removes a FilterCriteria from the collection # # @param [String] id, the name of the filter criteria # @optional [Function] cb, the callback method if removing async remove: (id, cb) -> self = this obj = _Collection.findOne({_id: id}) if obj and cb obj.remove(cb) return if obj return obj.remove() else return 0 # returns the query object used to filter the server-side collection # # @return [Object] query, a mongoDB query object getQueryObject: () -> self = this criteria = _Collection.find({}) result = {} criteria.forEach((filter) -> value = {} k = filter.get('key') o = filter.get('operator') v = filter.get('value') if _.indexOf(['$eq'], o) >= 0 value = v else value[o] = v result[k] = value ) return result # compares the current state vs. the original/previous state compareStates: () -> self = this # postone execution to avoid 'flash' for the fast draw case. this happens # when the user clicks a node or presses enter on the search and the # draw completes faster than the debounce timeout async.nextTick(() -> current = self.getCurrentState() if current != _state # do not notifiy on an empty query or the base state if current == "{}" || current == self._baseState self.stateChanged.set(false) else self.stateChanged.set(true) # disable [More...] button when filter has changed $('#loadMore').prop('disabled', true) else self.stateChanged.set(false) ) return # gets the current state of the filter # # @return [String] the query object JSON.strigify getCurrentState: () -> self = this query = self.getQueryObject() return JSON.stringify(query) # get the original/previous state of the filter # # @return [String] the query object JSON.strigify getState: () -> _state # sets the original/previous state of the filter, this method will read the # current query object and store is as a JSON string setState: () -> self = this query = self.getQueryObject() _state = JSON.stringify(query) return # process the results of the meteor methods to get flights # # @param [Array] flights, an Array of flights to process process: (flights) -> self = this if self._queue != null self._queue.kill() async.nextTick(() -> self._queue = null ) map = Template.gritsMap.getInstance() layerGroup = GritsLayerGroup.getCurrentLayerGroup() heatmapLayerGroup = Template.gritsMap.getInstance().getGritsLayerGroup(GritsConstants.HEATMAP_GROUP_LAYER_ID) count = Session.get(GritsConstants.SESSION_KEY_LOADED_RECORDS) throttleDraw = _.throttle(-> layerGroup.draw() heatmapLayerGroup.draw() , 500) self._queue = async.queue(((flight, callback) -> # convert the flight into a node/path layerGroup.convertFlight(flight, 1, self.departures.get()) # update the layer throttleDraw() # update the counter Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS , ++count) # done processing async.nextTick(-> callback()) ), 4) # final method for when all items within the queue are processed self._queue.drain = -> layerGroup.finish() heatmapLayerGroup.finish() Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS, count) Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) # add the flights to thet queue which will start processing self._queue.push(flights) return # applies the filter # # @param [Function] cb, the callback function more: (cb, limit=3000) -> # applying the filter is always EXPLORE mode Session.set(GritsConstants.SESSION_KEY_MODE, GritsConstants.MODE_EXPLORE) query = @getQueryObject() if _.isUndefined(query) or _.isEmpty(query) toastr.error(i18n.get('toastMessages.departureRequired')) Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) return if Object.keys(query).every((k)-> !k.startsWith('departureAirport')) toastr.error(i18n.get('toastMessages.departureRequired')) Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) return # set the state @setState() @compareStates() # remove the ignoreFields from the query _.each(_ignoreFields, (field) -> if query.hasOwnProperty(field) delete query[field] ) # show the loading indicator and call the server-side method Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, true) Meteor.call 'flightsByQuery', query, limit, (err, result) => if err Meteor.gritsUtil.errorHandler(err) return {totalRecords, flights} = result if totalRecords > limit and limit != 0 Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) data = totalRecords: totalRecords flights: flights callback: cb Blaze.renderWithData Template.gritsConfirmModal, data, $('body')[0] return if Meteor.gritsUtil.debug console.log 'totalRecords: ', totalRecords Session.set(GritsConstants.SESSION_KEY_TOTAL_RECORDS, totalRecords) if totalRecords.length <= 0 toastr.info(i18n.get('toastMessages.noResults')) Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) return if _.isUndefined(flights) || flights.length <= 0 toastr.info(i18n.get('toastMessages.noResults')) Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) return # call the original callback function if its defined if cb && _.isFunction(cb) cb(null, flights) # process the flights @process(flights) # applies the filter; resets loadedRecords, and totalRecords # # @param [Function] cb, the callback function apply: (cb) -> self = this # allow the reactive var to be set before continue @resetLayerGroup() async.nextTick(() -> # reset the loadedRecords and totalRecords Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS, 0) Session.set(GritsConstants.SESSION_KEY_TOTAL_RECORDS, 0) # re-enable the loadMore button when a new filter is applied $('#loadMore').prop('disabled', false) # pass the callback function if its defined if cb && _.isFunction(cb) self.more(cb) else self.more() ) return resetLayerGroup: -> layerGroup = GritsLayerGroup.getCurrentLayerGroup() # clears the sub-layers and resets the layer group if layerGroup layerGroup.reset() # sets the 'start' date from the filter and updates the filter criteria # # @param [Object] date, Date object or null to clear the criteria setOperatingDateRangeStart: (date) -> self = this # do not allow this to run prior to jQuery/DOM if _.isUndefined($) || _.isUndefined(Template.gritsSearch) return discontinuedDatePicker = Template.gritsSearch.getDiscontinuedDatePicker() if _.isNull(discontinuedDatePicker) return discontinuedDate = discontinuedDatePicker.data('DateTimePicker').date().toISOString() if _.isNull(date) || _.isNull(discontinuedDate) if _.isEqual(date, discontinuedDate) self.remove('discontinuedDate') else discontinuedDatePicker.data('DateTimePicker').date(null) self.operatingDateRangeStart.set(null) return if _.isEqual(date.toISOString(), discontinuedDate) # the reactive var is already set, change is from the UI self.createOrUpdate('discontinuedDate', {key: 'discontinuedDate', operator: '$gte', value: discontinuedDate}) else discontinuedDatePicker.data('DateTimePicker').date(date) self.operatingDateRangeStart.set(date) return trackOperatingDateRangeStart: () -> self = this Meteor.autorun -> obj = self.operatingDateRangeStart.get() self.setOperatingDateRangeStart(obj) async.nextTick(() -> self.compareStates() ) return # sets the 'end' date from the filter and updates the filter criteria # # @param [Object] date, Date object or null to clear the criteria setOperatingDateRangeEnd: (date) -> self = this # do not allow this to run prior to jQuery/DOM if _.isUndefined($) || _.isUndefined(Template.gritsSearch) return effectiveDatePicker = Template.gritsSearch.getEffectiveDatePicker() if _.isNull(effectiveDatePicker) return effectiveDate = effectiveDatePicker.data('DateTimePicker').date().toISOString() if _.isNull(date) || _.isNull(effectiveDate) if _.isEqual(date, effectiveDate) self.remove('effectiveDate') else effectiveDatePicker.data('DateTimePicker').date(null) self.operatingDateRangeEnd.set(null) return if _.isEqual(date.toISOString(), effectiveDate) # the reactive var is already set, change is from the UI self.createOrUpdate('effectiveDate', { key: 'effectiveDate' operator: '$lte' value: effectiveDate }) else effectiveDatePicker.data('DateTimePicker').date(date) self.operatingDateRangeEnd.set(date) return trackOperatingDateRangeEnd: () -> self = this Meteor.autorun -> obj = self.operatingDateRangeEnd.get() self.setOperatingDateRangeEnd(obj) async.nextTick(() -> self.compareStates() ) return # sets the departure input on the UI to the 'code' # specified, as well as, updating the underlying FilterCriteria. # # @param [String] code, an airport IATA code # @see http://www.iata.org/Pages/airports.aspx setDepartures: (code) -> # do not allow this to run prior to jQuery/DOM if _.isUndefined($) return if _.isUndefined(code) throw new Error('A code must be defined or null.') if _.isEqual(@departures.get(), code) # the call is from the UI if _.isNull(code) @remove('departure') return if _.isEmpty(code) @remove('departure') return if _.isArray(code) codes = code else codes = [code] departures = [] # Clear all the property meta-nodes and recreate them. GritsMetaNode.resetPropertyNodes() allNodes = Template.gritsMap.getInstance() .getGritsLayerGroup(GritsConstants.ALL_NODES_GROUP_LAYER_ID) .getNodeLayer().getNodes() parsedCodes = _.chain(codes) .map (_id)-> if _.contains(_id, ":") [field, value] = _id.split(":") airportIds = _.chain(Meteor.gritsUtil.airports) .map((airport)-> if airport[field] == value [airport._id, true] else null ) .compact() .object() .value() filteredNodes = allNodes.filter (x)->airportIds[x._id] metaNode = GritsMetaNode.create(filteredNodes, _id) return Object.keys(airportIds) else if _id.indexOf(GritsMetaNode.PREFIX) >= 0 node = GritsMetaNode.find(_id) return _.pluck(node?._children or [], '_id') else return [_id.toUpperCase()] .flatten() .value() @createOrUpdate('departure', { key: 'departureAirport._id' operator: '$in' value: parsedCodes }) else if _.isNull(code) Template.gritsSearch.getDepartureSearchMain().tokenfield('setTokens', []) @departures.set([]) else if _.isEmpty(code) Template.gritsSearch.getDepartureSearchMain().tokenfield('setTokens', []) @departures.set([]) else if _.isArray(code) Template.gritsSearch.getDepartureSearchMain().tokenfield('setTokens', code) @departures.set(code) else Template.gritsSearch.getDepartureSearchMain().tokenfield('setTokens', [code]) @departures.set([code]) trackDepartures: () -> self = this Meteor.autorun -> obj = self.departures.get() if _.isEmpty(obj) # checks are necessary as Tracker autorun will fire before the DOM # is ready and the Template.gritsMap.onRenered is called if !(_.isUndefined(Template.gritsMap) || _.isUndefined(Template.gritsMap.getInstance)) map = Template.gritsMap.getInstance() if !_.isNull(map) self.resetLayerGroup() self.setDepartures(obj) async.nextTick () -> self.compareStates() # returns a unique list of tokens from the search bar getOriginIds: () -> query = @getQueryObject() query['departureAirport._id']['$in'] # handle setup of subscription to SimulatedIteneraries and process the results processSimulation: (simPas, simId) -> # get the heatmapLayerGroup heatmapLayerGroup = Template.gritsMap.getInstance().getGritsLayerGroup(GritsConstants.HEATMAP_GROUP_LAYER_ID) # get the current mode groupLayer layerGroup = GritsLayerGroup.getCurrentLayerGroup() if layerGroup == null return # reset the layers/counters layerGroup.reset() heatmapLayerGroup.reset() loaded = 0 # initialize the status-bar counter Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS, loaded) # reset the airportCounts @airportCounts = {} @trackDepartures() originIds = @getOriginIds() _updateHeatmap = _.throttle(=> Heatmaps.remove({}) # map the airportCounts object to one with percentage values airportPercentages = _.object([key, val / loaded] for key, val of @airportCounts) # key the heatmap to the departure airports so it can be filtered # out if the query changes. airportPercentages._id = originIds.sort().join("") Heatmap.createFromDoc(airportPercentages, Meteor.gritsUtil.airportsToLocations) , 500) _throttledDraw = _.throttle(-> layerGroup.draw() heatmapLayerGroup.draw() , 500) @simulationItineraries = Meteor.subscribe('SimulationItineraries', simId) options = transform: null _doWork = (id, fields) => if @airportCounts[fields.destination] @airportCounts[fields.destination]++ else @airportCounts[fields.destination] = 1 loaded += 1 layerGroup.convertItineraries(fields, fields.origin) # update the simulatorProgress bar if simPas > 0 progress = Math.ceil((loaded / simPas) * 100) Template.gritsSearch.simulationProgress.set(progress) Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS, loaded) if loaded == simPas #finaldraw Template.gritsSearch.simulationProgress.set(100) Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS, loaded) _updateHeatmap() layerGroup.finish() heatmapLayerGroup.finish() @isSimulatorRunning.set(false) else _updateHeatmap() _throttledDraw() itineraryQuery = Itineraries.find({'simulationId': simId}, options) numItineraries = itineraryQuery.count() if numItineraries == simPas itineraryQuery.forEach Meteor.gritsUtil.smoothRate (itinerary) -> _doWork(itinerary._id, itinerary) else itineraryQuery.observeChanges({ added: Meteor.gritsUtil.smoothRate (id, fields) -> _doWork(id, fields) }) return # starting a simulation startSimulation: (simPas, startDate, endDate, email) -> departures = @departures.get() if departures.length == 0 toastr.error(i18n.get('toastMessages.departureRequired')) return if @isSimulatorRunning.get() return # switch mode Session.set(GritsConstants.SESSION_KEY_MODE, GritsConstants.MODE_ANALYZE) # let the user know the simulation started Template.gritsSearch.simulationProgress.set(1) # set the simulation as running @isSimulatorRunning.set(true) Meteor.call('startSimulation', simPas, startDate, endDate, @getOriginIds(), email, (err, res) => # handle any errors if err Meteor.gritsUtil.errorHandler(err) console.error(err) return if res.hasOwnProperty('error') Meteor.gritsUtil.errorHandler(res) console.error(res) return # set the reactive var on the template Template.gritsDataTable.simId.set(res.simId) # update the url, this will trigger processing of the simulation. FlowRouter.go('/simulation/'+res.simId) # set the status-bar total counter Session.set(GritsConstants.SESSION_KEY_TOTAL_RECORDS, simPas) ) # reset the start date of the filter resetStart: () -> self = this start = self._today month = start.getMonth() date = start.getDate() year = start.getFullYear() self.operatingDateRangeStart.set(new Date(year, month, date)) return # reset the end date of the filter resetEnd: () -> self = this end = moment(self._today).add(7, 'd').toDate() month = end.getMonth() date = end.getDate() year = end.getFullYear() self.operatingDateRangeEnd.set(new Date(year, month, date)) return # resets the filter reset: () -> self = this # reset the departures self.setDepartures null # reset the start and end dates self.resetStart() self.resetEnd() # reset counters Session.set GritsConstants.SESSION_KEY_LOADED_RECORDS, 0 Session.set GritsConstants.SESSION_KEY_TOTAL_RECORDS, 0 # reset includeNearby $('#includeNearbyAirports').prop 'checked', false $("#includeNearbyAirportsRadius").val 50 # determine the current mode mode = Session.get GritsConstants.SESSION_KEY_MODE if mode == GritsConstants.MODE_ANALYZE # set isSimulatorRunning to false self.isSimulatorRunning.set(false) # stop any existing subscription if self.simulationItineraries != null self.simulationItineraries.stop() self.simulationItineraries = null; # remove disabled class $('#startSimulation').removeClass('disabled') # reset number of passengers $('#simulatedPassengersInputSlider').slider('setValue', 1000) $('#simulatedPassengersInputSliderValIndicator').html(1000) FlowRouter.route('/') return GritsFilterCriteria = new GritsFilterCriteria() # exports as a singleton
92761
_ignoreFields = [] _validFields = ['departure', 'effectiveDate', 'discontinuedDate'] _validOperators = ['$gte', '$gt', '$lte', '$lt', '$eq', '$ne', '$in', '$near', null] _state = null # keeps track of the query string state # local/private minimongo collection _Collection = new (Mongo.Collection)(null) # local/private Astronomy model for maintaining filter criteria _Filter = Astro.Class( name: 'FilterCriteria' collection: _Collection transform: true fields: ['key', 'operator', 'value'] validators: { key: [ Validators.required(), Validators.string() ], operator: [ Validators.required(), Validators.string(), Validators.choice(_validOperators) ], value: Validators.required() } ) # GritsFilterCriteria, this object provides the interface for # accessing the UI filter box. The setter methods may be called # programmatically or the reactive var can be set by event handers # within the UI. The entire object maintains its own state. # # @note exports as a 'singleton' class GritsFilterCriteria constructor: () -> self = this # reactive var used to update the UI when the query state has changed self.stateChanged = new ReactiveVar(null) # setup an instance variable that contains todays date. This will be used # to set the initial Start and End dates to the Operating Date Range now = new Date() month = now.getMonth() date = now.getDate() year = now.getFullYear() self._today = new Date(year, month, date) # this._baseState keeps track of the initial plugin state after any init # methods have run self._baseState = {} # processing queue self._queue = null # reactive vars to track form binding # departures self.departures = new ReactiveVar([]) self.trackDepartures() # operatingDateRangeStart self.operatingDateRangeStart = new ReactiveVar(null) self.trackOperatingDateRangeStart() # operatingDateRangeEnd self.operatingDateRangeEnd = new ReactiveVar(null) self.trackOperatingDateRangeEnd() # airportCounts # during a simulation the airports are counted to update the heatmap self.airportCounts = {} # is the simulation running? self.isSimulatorRunning = new ReactiveVar(false) return # initialize the start date of the filter 'discontinuedDate' # # @return [String] dateString, formatted MM/DD/YY initStart: () -> self = this start = self._today self.createOrUpdate('discontinuedDate', {key: 'discontinuedDate', operator: '$gte', value: start}) query = @getQueryObject() # update the state logic for the indicator _state = JSON.stringify(query) self._baseState = JSON.stringify(query) month = start.getMonth() + 1 date = start.getDate() year = start.getFullYear() yearStr = year.toString().slice(2,4) self.operatingDateRangeStart.set(new Date(year, month, date)) return "#{month}/#{date}/#{yearStr}" # initialize the end date through the 'effectiveDate' filter # # @return [String] dateString, formatted MM/DD/YY initEnd: () -> self = this end = moment(@_today).add(7, 'd').toDate() self.createOrUpdate('effectiveDate', {key: 'effectiveDate', operator: '$lte', value: end}) # get the query object query = self.getQueryObject() # update the state logic for the indicator _state = JSON.stringify(query) self._baseState = JSON.stringify(query) month = end.getMonth() + 1 date = end.getDate() year = end.getFullYear() yearStr = year.toString().slice(2,4) self.operatingDateRangeEnd.set(new Date(year, month, date)) return "#{month}/#{date}/#{yearStr}" # Creates a new filter criteria and adds it to the collection or updates # the collection if it already exists # # @param [String] id, the name of the filter criteria # @return [Object] Astronomy model 'FilterCriteria' createOrUpdate: (id, fields) -> self = this if _.indexOf(_validFields, id) < 0 throw new Error('Invalid filter: ' + id) obj = _Collection.findOne({_id: id}) if obj obj.set(fields) if obj.validate() == false throw new Error(_.values(obj.getValidationErrors())) obj.save() return obj else _.extend(fields, {_id: id}) obj = new _Filter(fields) if obj.validate() == false throw new Error(_.values(obj.getValidationErrors())) obj.save() return obj # removes a FilterCriteria from the collection # # @param [String] id, the name of the filter criteria # @optional [Function] cb, the callback method if removing async remove: (id, cb) -> self = this obj = _Collection.findOne({_id: id}) if obj and cb obj.remove(cb) return if obj return obj.remove() else return 0 # returns the query object used to filter the server-side collection # # @return [Object] query, a mongoDB query object getQueryObject: () -> self = this criteria = _Collection.find({}) result = {} criteria.forEach((filter) -> value = {} k = filter.get('key') o = filter.get('operator') v = filter.get('value') if _.indexOf(['$eq'], o) >= 0 value = v else value[o] = v result[k] = value ) return result # compares the current state vs. the original/previous state compareStates: () -> self = this # postone execution to avoid 'flash' for the fast draw case. this happens # when the user clicks a node or presses enter on the search and the # draw completes faster than the debounce timeout async.nextTick(() -> current = self.getCurrentState() if current != _state # do not notifiy on an empty query or the base state if current == "{}" || current == self._baseState self.stateChanged.set(false) else self.stateChanged.set(true) # disable [More...] button when filter has changed $('#loadMore').prop('disabled', true) else self.stateChanged.set(false) ) return # gets the current state of the filter # # @return [String] the query object JSON.strigify getCurrentState: () -> self = this query = self.getQueryObject() return JSON.stringify(query) # get the original/previous state of the filter # # @return [String] the query object JSON.strigify getState: () -> _state # sets the original/previous state of the filter, this method will read the # current query object and store is as a JSON string setState: () -> self = this query = self.getQueryObject() _state = JSON.stringify(query) return # process the results of the meteor methods to get flights # # @param [Array] flights, an Array of flights to process process: (flights) -> self = this if self._queue != null self._queue.kill() async.nextTick(() -> self._queue = null ) map = Template.gritsMap.getInstance() layerGroup = GritsLayerGroup.getCurrentLayerGroup() heatmapLayerGroup = Template.gritsMap.getInstance().getGritsLayerGroup(GritsConstants.HEATMAP_GROUP_LAYER_ID) count = Session.get(GritsConstants.SESSION_KEY_LOADED_RECORDS) throttleDraw = _.throttle(-> layerGroup.draw() heatmapLayerGroup.draw() , 500) self._queue = async.queue(((flight, callback) -> # convert the flight into a node/path layerGroup.convertFlight(flight, 1, self.departures.get()) # update the layer throttleDraw() # update the counter Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS , ++count) # done processing async.nextTick(-> callback()) ), 4) # final method for when all items within the queue are processed self._queue.drain = -> layerGroup.finish() heatmapLayerGroup.finish() Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS, count) Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) # add the flights to thet queue which will start processing self._queue.push(flights) return # applies the filter # # @param [Function] cb, the callback function more: (cb, limit=3000) -> # applying the filter is always EXPLORE mode Session.set(GritsConstants.SESSION_KEY_MODE, GritsConstants.MODE_EXPLORE) query = @getQueryObject() if _.isUndefined(query) or _.isEmpty(query) toastr.error(i18n.get('toastMessages.departureRequired')) Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) return if Object.keys(query).every((k)-> !k.startsWith('departureAirport')) toastr.error(i18n.get('toastMessages.departureRequired')) Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) return # set the state @setState() @compareStates() # remove the ignoreFields from the query _.each(_ignoreFields, (field) -> if query.hasOwnProperty(field) delete query[field] ) # show the loading indicator and call the server-side method Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, true) Meteor.call 'flightsByQuery', query, limit, (err, result) => if err Meteor.gritsUtil.errorHandler(err) return {totalRecords, flights} = result if totalRecords > limit and limit != 0 Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) data = totalRecords: totalRecords flights: flights callback: cb Blaze.renderWithData Template.gritsConfirmModal, data, $('body')[0] return if Meteor.gritsUtil.debug console.log 'totalRecords: ', totalRecords Session.set(GritsConstants.SESSION_KEY_TOTAL_RECORDS, totalRecords) if totalRecords.length <= 0 toastr.info(i18n.get('toastMessages.noResults')) Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) return if _.isUndefined(flights) || flights.length <= 0 toastr.info(i18n.get('toastMessages.noResults')) Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) return # call the original callback function if its defined if cb && _.isFunction(cb) cb(null, flights) # process the flights @process(flights) # applies the filter; resets loadedRecords, and totalRecords # # @param [Function] cb, the callback function apply: (cb) -> self = this # allow the reactive var to be set before continue @resetLayerGroup() async.nextTick(() -> # reset the loadedRecords and totalRecords Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS, 0) Session.set(GritsConstants.SESSION_KEY_TOTAL_RECORDS, 0) # re-enable the loadMore button when a new filter is applied $('#loadMore').prop('disabled', false) # pass the callback function if its defined if cb && _.isFunction(cb) self.more(cb) else self.more() ) return resetLayerGroup: -> layerGroup = GritsLayerGroup.getCurrentLayerGroup() # clears the sub-layers and resets the layer group if layerGroup layerGroup.reset() # sets the 'start' date from the filter and updates the filter criteria # # @param [Object] date, Date object or null to clear the criteria setOperatingDateRangeStart: (date) -> self = this # do not allow this to run prior to jQuery/DOM if _.isUndefined($) || _.isUndefined(Template.gritsSearch) return discontinuedDatePicker = Template.gritsSearch.getDiscontinuedDatePicker() if _.isNull(discontinuedDatePicker) return discontinuedDate = discontinuedDatePicker.data('DateTimePicker').date().toISOString() if _.isNull(date) || _.isNull(discontinuedDate) if _.isEqual(date, discontinuedDate) self.remove('discontinuedDate') else discontinuedDatePicker.data('DateTimePicker').date(null) self.operatingDateRangeStart.set(null) return if _.isEqual(date.toISOString(), discontinuedDate) # the reactive var is already set, change is from the UI self.createOrUpdate('discontinuedDate', {key: 'discontinuedDate', operator: '$gte', value: discontinuedDate}) else discontinuedDatePicker.data('DateTimePicker').date(date) self.operatingDateRangeStart.set(date) return trackOperatingDateRangeStart: () -> self = this Meteor.autorun -> obj = self.operatingDateRangeStart.get() self.setOperatingDateRangeStart(obj) async.nextTick(() -> self.compareStates() ) return # sets the 'end' date from the filter and updates the filter criteria # # @param [Object] date, Date object or null to clear the criteria setOperatingDateRangeEnd: (date) -> self = this # do not allow this to run prior to jQuery/DOM if _.isUndefined($) || _.isUndefined(Template.gritsSearch) return effectiveDatePicker = Template.gritsSearch.getEffectiveDatePicker() if _.isNull(effectiveDatePicker) return effectiveDate = effectiveDatePicker.data('DateTimePicker').date().toISOString() if _.isNull(date) || _.isNull(effectiveDate) if _.isEqual(date, effectiveDate) self.remove('effectiveDate') else effectiveDatePicker.data('DateTimePicker').date(null) self.operatingDateRangeEnd.set(null) return if _.isEqual(date.toISOString(), effectiveDate) # the reactive var is already set, change is from the UI self.createOrUpdate('effectiveDate', { key: 'effectiveDate' operator: '$lte' value: effectiveDate }) else effectiveDatePicker.data('DateTimePicker').date(date) self.operatingDateRangeEnd.set(date) return trackOperatingDateRangeEnd: () -> self = this Meteor.autorun -> obj = self.operatingDateRangeEnd.get() self.setOperatingDateRangeEnd(obj) async.nextTick(() -> self.compareStates() ) return # sets the departure input on the UI to the 'code' # specified, as well as, updating the underlying FilterCriteria. # # @param [String] code, an airport IATA code # @see http://www.iata.org/Pages/airports.aspx setDepartures: (code) -> # do not allow this to run prior to jQuery/DOM if _.isUndefined($) return if _.isUndefined(code) throw new Error('A code must be defined or null.') if _.isEqual(@departures.get(), code) # the call is from the UI if _.isNull(code) @remove('departure') return if _.isEmpty(code) @remove('departure') return if _.isArray(code) codes = code else codes = [code] departures = [] # Clear all the property meta-nodes and recreate them. GritsMetaNode.resetPropertyNodes() allNodes = Template.gritsMap.getInstance() .getGritsLayerGroup(GritsConstants.ALL_NODES_GROUP_LAYER_ID) .getNodeLayer().getNodes() parsedCodes = _.chain(codes) .map (_id)-> if _.contains(_id, ":") [field, value] = _id.split(":") airportIds = _.chain(Meteor.gritsUtil.airports) .map((airport)-> if airport[field] == value [airport._id, true] else null ) .compact() .object() .value() filteredNodes = allNodes.filter (x)->airportIds[x._id] metaNode = GritsMetaNode.create(filteredNodes, _id) return Object.keys(airportIds) else if _id.indexOf(GritsMetaNode.PREFIX) >= 0 node = GritsMetaNode.find(_id) return _.pluck(node?._children or [], '_id') else return [_id.toUpperCase()] .flatten() .value() @createOrUpdate('departure', { key: 'departureAirport._<KEY>' operator: '$in' value: parsedCodes }) else if _.isNull(code) Template.gritsSearch.getDepartureSearchMain().tokenfield('setTokens', []) @departures.set([]) else if _.isEmpty(code) Template.gritsSearch.getDepartureSearchMain().tokenfield('setTokens', []) @departures.set([]) else if _.isArray(code) Template.gritsSearch.getDepartureSearchMain().tokenfield('setTokens', code) @departures.set(code) else Template.gritsSearch.getDepartureSearchMain().tokenfield('setTokens', [code]) @departures.set([code]) trackDepartures: () -> self = this Meteor.autorun -> obj = self.departures.get() if _.isEmpty(obj) # checks are necessary as Tracker autorun will fire before the DOM # is ready and the Template.gritsMap.onRenered is called if !(_.isUndefined(Template.gritsMap) || _.isUndefined(Template.gritsMap.getInstance)) map = Template.gritsMap.getInstance() if !_.isNull(map) self.resetLayerGroup() self.setDepartures(obj) async.nextTick () -> self.compareStates() # returns a unique list of tokens from the search bar getOriginIds: () -> query = @getQueryObject() query['departureAirport._id']['$in'] # handle setup of subscription to SimulatedIteneraries and process the results processSimulation: (simPas, simId) -> # get the heatmapLayerGroup heatmapLayerGroup = Template.gritsMap.getInstance().getGritsLayerGroup(GritsConstants.HEATMAP_GROUP_LAYER_ID) # get the current mode groupLayer layerGroup = GritsLayerGroup.getCurrentLayerGroup() if layerGroup == null return # reset the layers/counters layerGroup.reset() heatmapLayerGroup.reset() loaded = 0 # initialize the status-bar counter Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS, loaded) # reset the airportCounts @airportCounts = {} @trackDepartures() originIds = @getOriginIds() _updateHeatmap = _.throttle(=> Heatmaps.remove({}) # map the airportCounts object to one with percentage values airportPercentages = _.object([key, val / loaded] for key, val of @airportCounts) # key the heatmap to the departure airports so it can be filtered # out if the query changes. airportPercentages._id = originIds.sort().join("") Heatmap.createFromDoc(airportPercentages, Meteor.gritsUtil.airportsToLocations) , 500) _throttledDraw = _.throttle(-> layerGroup.draw() heatmapLayerGroup.draw() , 500) @simulationItineraries = Meteor.subscribe('SimulationItineraries', simId) options = transform: null _doWork = (id, fields) => if @airportCounts[fields.destination] @airportCounts[fields.destination]++ else @airportCounts[fields.destination] = 1 loaded += 1 layerGroup.convertItineraries(fields, fields.origin) # update the simulatorProgress bar if simPas > 0 progress = Math.ceil((loaded / simPas) * 100) Template.gritsSearch.simulationProgress.set(progress) Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS, loaded) if loaded == simPas #finaldraw Template.gritsSearch.simulationProgress.set(100) Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS, loaded) _updateHeatmap() layerGroup.finish() heatmapLayerGroup.finish() @isSimulatorRunning.set(false) else _updateHeatmap() _throttledDraw() itineraryQuery = Itineraries.find({'simulationId': simId}, options) numItineraries = itineraryQuery.count() if numItineraries == simPas itineraryQuery.forEach Meteor.gritsUtil.smoothRate (itinerary) -> _doWork(itinerary._id, itinerary) else itineraryQuery.observeChanges({ added: Meteor.gritsUtil.smoothRate (id, fields) -> _doWork(id, fields) }) return # starting a simulation startSimulation: (simPas, startDate, endDate, email) -> departures = @departures.get() if departures.length == 0 toastr.error(i18n.get('toastMessages.departureRequired')) return if @isSimulatorRunning.get() return # switch mode Session.set(GritsConstants.SESSION_KEY_MODE, GritsConstants.MODE_ANALYZE) # let the user know the simulation started Template.gritsSearch.simulationProgress.set(1) # set the simulation as running @isSimulatorRunning.set(true) Meteor.call('startSimulation', simPas, startDate, endDate, @getOriginIds(), email, (err, res) => # handle any errors if err Meteor.gritsUtil.errorHandler(err) console.error(err) return if res.hasOwnProperty('error') Meteor.gritsUtil.errorHandler(res) console.error(res) return # set the reactive var on the template Template.gritsDataTable.simId.set(res.simId) # update the url, this will trigger processing of the simulation. FlowRouter.go('/simulation/'+res.simId) # set the status-bar total counter Session.set(GritsConstants.SESSION_KEY_TOTAL_RECORDS, simPas) ) # reset the start date of the filter resetStart: () -> self = this start = self._today month = start.getMonth() date = start.getDate() year = start.getFullYear() self.operatingDateRangeStart.set(new Date(year, month, date)) return # reset the end date of the filter resetEnd: () -> self = this end = moment(self._today).add(7, 'd').toDate() month = end.getMonth() date = end.getDate() year = end.getFullYear() self.operatingDateRangeEnd.set(new Date(year, month, date)) return # resets the filter reset: () -> self = this # reset the departures self.setDepartures null # reset the start and end dates self.resetStart() self.resetEnd() # reset counters Session.set GritsConstants.SESSION_KEY_LOADED_RECORDS, 0 Session.set GritsConstants.SESSION_KEY_TOTAL_RECORDS, 0 # reset includeNearby $('#includeNearbyAirports').prop 'checked', false $("#includeNearbyAirportsRadius").val 50 # determine the current mode mode = Session.get GritsConstants.SESSION_KEY_MODE if mode == GritsConstants.MODE_ANALYZE # set isSimulatorRunning to false self.isSimulatorRunning.set(false) # stop any existing subscription if self.simulationItineraries != null self.simulationItineraries.stop() self.simulationItineraries = null; # remove disabled class $('#startSimulation').removeClass('disabled') # reset number of passengers $('#simulatedPassengersInputSlider').slider('setValue', 1000) $('#simulatedPassengersInputSliderValIndicator').html(1000) FlowRouter.route('/') return GritsFilterCriteria = new GritsFilterCriteria() # exports as a singleton
true
_ignoreFields = [] _validFields = ['departure', 'effectiveDate', 'discontinuedDate'] _validOperators = ['$gte', '$gt', '$lte', '$lt', '$eq', '$ne', '$in', '$near', null] _state = null # keeps track of the query string state # local/private minimongo collection _Collection = new (Mongo.Collection)(null) # local/private Astronomy model for maintaining filter criteria _Filter = Astro.Class( name: 'FilterCriteria' collection: _Collection transform: true fields: ['key', 'operator', 'value'] validators: { key: [ Validators.required(), Validators.string() ], operator: [ Validators.required(), Validators.string(), Validators.choice(_validOperators) ], value: Validators.required() } ) # GritsFilterCriteria, this object provides the interface for # accessing the UI filter box. The setter methods may be called # programmatically or the reactive var can be set by event handers # within the UI. The entire object maintains its own state. # # @note exports as a 'singleton' class GritsFilterCriteria constructor: () -> self = this # reactive var used to update the UI when the query state has changed self.stateChanged = new ReactiveVar(null) # setup an instance variable that contains todays date. This will be used # to set the initial Start and End dates to the Operating Date Range now = new Date() month = now.getMonth() date = now.getDate() year = now.getFullYear() self._today = new Date(year, month, date) # this._baseState keeps track of the initial plugin state after any init # methods have run self._baseState = {} # processing queue self._queue = null # reactive vars to track form binding # departures self.departures = new ReactiveVar([]) self.trackDepartures() # operatingDateRangeStart self.operatingDateRangeStart = new ReactiveVar(null) self.trackOperatingDateRangeStart() # operatingDateRangeEnd self.operatingDateRangeEnd = new ReactiveVar(null) self.trackOperatingDateRangeEnd() # airportCounts # during a simulation the airports are counted to update the heatmap self.airportCounts = {} # is the simulation running? self.isSimulatorRunning = new ReactiveVar(false) return # initialize the start date of the filter 'discontinuedDate' # # @return [String] dateString, formatted MM/DD/YY initStart: () -> self = this start = self._today self.createOrUpdate('discontinuedDate', {key: 'discontinuedDate', operator: '$gte', value: start}) query = @getQueryObject() # update the state logic for the indicator _state = JSON.stringify(query) self._baseState = JSON.stringify(query) month = start.getMonth() + 1 date = start.getDate() year = start.getFullYear() yearStr = year.toString().slice(2,4) self.operatingDateRangeStart.set(new Date(year, month, date)) return "#{month}/#{date}/#{yearStr}" # initialize the end date through the 'effectiveDate' filter # # @return [String] dateString, formatted MM/DD/YY initEnd: () -> self = this end = moment(@_today).add(7, 'd').toDate() self.createOrUpdate('effectiveDate', {key: 'effectiveDate', operator: '$lte', value: end}) # get the query object query = self.getQueryObject() # update the state logic for the indicator _state = JSON.stringify(query) self._baseState = JSON.stringify(query) month = end.getMonth() + 1 date = end.getDate() year = end.getFullYear() yearStr = year.toString().slice(2,4) self.operatingDateRangeEnd.set(new Date(year, month, date)) return "#{month}/#{date}/#{yearStr}" # Creates a new filter criteria and adds it to the collection or updates # the collection if it already exists # # @param [String] id, the name of the filter criteria # @return [Object] Astronomy model 'FilterCriteria' createOrUpdate: (id, fields) -> self = this if _.indexOf(_validFields, id) < 0 throw new Error('Invalid filter: ' + id) obj = _Collection.findOne({_id: id}) if obj obj.set(fields) if obj.validate() == false throw new Error(_.values(obj.getValidationErrors())) obj.save() return obj else _.extend(fields, {_id: id}) obj = new _Filter(fields) if obj.validate() == false throw new Error(_.values(obj.getValidationErrors())) obj.save() return obj # removes a FilterCriteria from the collection # # @param [String] id, the name of the filter criteria # @optional [Function] cb, the callback method if removing async remove: (id, cb) -> self = this obj = _Collection.findOne({_id: id}) if obj and cb obj.remove(cb) return if obj return obj.remove() else return 0 # returns the query object used to filter the server-side collection # # @return [Object] query, a mongoDB query object getQueryObject: () -> self = this criteria = _Collection.find({}) result = {} criteria.forEach((filter) -> value = {} k = filter.get('key') o = filter.get('operator') v = filter.get('value') if _.indexOf(['$eq'], o) >= 0 value = v else value[o] = v result[k] = value ) return result # compares the current state vs. the original/previous state compareStates: () -> self = this # postone execution to avoid 'flash' for the fast draw case. this happens # when the user clicks a node or presses enter on the search and the # draw completes faster than the debounce timeout async.nextTick(() -> current = self.getCurrentState() if current != _state # do not notifiy on an empty query or the base state if current == "{}" || current == self._baseState self.stateChanged.set(false) else self.stateChanged.set(true) # disable [More...] button when filter has changed $('#loadMore').prop('disabled', true) else self.stateChanged.set(false) ) return # gets the current state of the filter # # @return [String] the query object JSON.strigify getCurrentState: () -> self = this query = self.getQueryObject() return JSON.stringify(query) # get the original/previous state of the filter # # @return [String] the query object JSON.strigify getState: () -> _state # sets the original/previous state of the filter, this method will read the # current query object and store is as a JSON string setState: () -> self = this query = self.getQueryObject() _state = JSON.stringify(query) return # process the results of the meteor methods to get flights # # @param [Array] flights, an Array of flights to process process: (flights) -> self = this if self._queue != null self._queue.kill() async.nextTick(() -> self._queue = null ) map = Template.gritsMap.getInstance() layerGroup = GritsLayerGroup.getCurrentLayerGroup() heatmapLayerGroup = Template.gritsMap.getInstance().getGritsLayerGroup(GritsConstants.HEATMAP_GROUP_LAYER_ID) count = Session.get(GritsConstants.SESSION_KEY_LOADED_RECORDS) throttleDraw = _.throttle(-> layerGroup.draw() heatmapLayerGroup.draw() , 500) self._queue = async.queue(((flight, callback) -> # convert the flight into a node/path layerGroup.convertFlight(flight, 1, self.departures.get()) # update the layer throttleDraw() # update the counter Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS , ++count) # done processing async.nextTick(-> callback()) ), 4) # final method for when all items within the queue are processed self._queue.drain = -> layerGroup.finish() heatmapLayerGroup.finish() Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS, count) Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) # add the flights to thet queue which will start processing self._queue.push(flights) return # applies the filter # # @param [Function] cb, the callback function more: (cb, limit=3000) -> # applying the filter is always EXPLORE mode Session.set(GritsConstants.SESSION_KEY_MODE, GritsConstants.MODE_EXPLORE) query = @getQueryObject() if _.isUndefined(query) or _.isEmpty(query) toastr.error(i18n.get('toastMessages.departureRequired')) Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) return if Object.keys(query).every((k)-> !k.startsWith('departureAirport')) toastr.error(i18n.get('toastMessages.departureRequired')) Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) return # set the state @setState() @compareStates() # remove the ignoreFields from the query _.each(_ignoreFields, (field) -> if query.hasOwnProperty(field) delete query[field] ) # show the loading indicator and call the server-side method Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, true) Meteor.call 'flightsByQuery', query, limit, (err, result) => if err Meteor.gritsUtil.errorHandler(err) return {totalRecords, flights} = result if totalRecords > limit and limit != 0 Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) data = totalRecords: totalRecords flights: flights callback: cb Blaze.renderWithData Template.gritsConfirmModal, data, $('body')[0] return if Meteor.gritsUtil.debug console.log 'totalRecords: ', totalRecords Session.set(GritsConstants.SESSION_KEY_TOTAL_RECORDS, totalRecords) if totalRecords.length <= 0 toastr.info(i18n.get('toastMessages.noResults')) Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) return if _.isUndefined(flights) || flights.length <= 0 toastr.info(i18n.get('toastMessages.noResults')) Session.set(GritsConstants.SESSION_KEY_IS_UPDATING, false) return # call the original callback function if its defined if cb && _.isFunction(cb) cb(null, flights) # process the flights @process(flights) # applies the filter; resets loadedRecords, and totalRecords # # @param [Function] cb, the callback function apply: (cb) -> self = this # allow the reactive var to be set before continue @resetLayerGroup() async.nextTick(() -> # reset the loadedRecords and totalRecords Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS, 0) Session.set(GritsConstants.SESSION_KEY_TOTAL_RECORDS, 0) # re-enable the loadMore button when a new filter is applied $('#loadMore').prop('disabled', false) # pass the callback function if its defined if cb && _.isFunction(cb) self.more(cb) else self.more() ) return resetLayerGroup: -> layerGroup = GritsLayerGroup.getCurrentLayerGroup() # clears the sub-layers and resets the layer group if layerGroup layerGroup.reset() # sets the 'start' date from the filter and updates the filter criteria # # @param [Object] date, Date object or null to clear the criteria setOperatingDateRangeStart: (date) -> self = this # do not allow this to run prior to jQuery/DOM if _.isUndefined($) || _.isUndefined(Template.gritsSearch) return discontinuedDatePicker = Template.gritsSearch.getDiscontinuedDatePicker() if _.isNull(discontinuedDatePicker) return discontinuedDate = discontinuedDatePicker.data('DateTimePicker').date().toISOString() if _.isNull(date) || _.isNull(discontinuedDate) if _.isEqual(date, discontinuedDate) self.remove('discontinuedDate') else discontinuedDatePicker.data('DateTimePicker').date(null) self.operatingDateRangeStart.set(null) return if _.isEqual(date.toISOString(), discontinuedDate) # the reactive var is already set, change is from the UI self.createOrUpdate('discontinuedDate', {key: 'discontinuedDate', operator: '$gte', value: discontinuedDate}) else discontinuedDatePicker.data('DateTimePicker').date(date) self.operatingDateRangeStart.set(date) return trackOperatingDateRangeStart: () -> self = this Meteor.autorun -> obj = self.operatingDateRangeStart.get() self.setOperatingDateRangeStart(obj) async.nextTick(() -> self.compareStates() ) return # sets the 'end' date from the filter and updates the filter criteria # # @param [Object] date, Date object or null to clear the criteria setOperatingDateRangeEnd: (date) -> self = this # do not allow this to run prior to jQuery/DOM if _.isUndefined($) || _.isUndefined(Template.gritsSearch) return effectiveDatePicker = Template.gritsSearch.getEffectiveDatePicker() if _.isNull(effectiveDatePicker) return effectiveDate = effectiveDatePicker.data('DateTimePicker').date().toISOString() if _.isNull(date) || _.isNull(effectiveDate) if _.isEqual(date, effectiveDate) self.remove('effectiveDate') else effectiveDatePicker.data('DateTimePicker').date(null) self.operatingDateRangeEnd.set(null) return if _.isEqual(date.toISOString(), effectiveDate) # the reactive var is already set, change is from the UI self.createOrUpdate('effectiveDate', { key: 'effectiveDate' operator: '$lte' value: effectiveDate }) else effectiveDatePicker.data('DateTimePicker').date(date) self.operatingDateRangeEnd.set(date) return trackOperatingDateRangeEnd: () -> self = this Meteor.autorun -> obj = self.operatingDateRangeEnd.get() self.setOperatingDateRangeEnd(obj) async.nextTick(() -> self.compareStates() ) return # sets the departure input on the UI to the 'code' # specified, as well as, updating the underlying FilterCriteria. # # @param [String] code, an airport IATA code # @see http://www.iata.org/Pages/airports.aspx setDepartures: (code) -> # do not allow this to run prior to jQuery/DOM if _.isUndefined($) return if _.isUndefined(code) throw new Error('A code must be defined or null.') if _.isEqual(@departures.get(), code) # the call is from the UI if _.isNull(code) @remove('departure') return if _.isEmpty(code) @remove('departure') return if _.isArray(code) codes = code else codes = [code] departures = [] # Clear all the property meta-nodes and recreate them. GritsMetaNode.resetPropertyNodes() allNodes = Template.gritsMap.getInstance() .getGritsLayerGroup(GritsConstants.ALL_NODES_GROUP_LAYER_ID) .getNodeLayer().getNodes() parsedCodes = _.chain(codes) .map (_id)-> if _.contains(_id, ":") [field, value] = _id.split(":") airportIds = _.chain(Meteor.gritsUtil.airports) .map((airport)-> if airport[field] == value [airport._id, true] else null ) .compact() .object() .value() filteredNodes = allNodes.filter (x)->airportIds[x._id] metaNode = GritsMetaNode.create(filteredNodes, _id) return Object.keys(airportIds) else if _id.indexOf(GritsMetaNode.PREFIX) >= 0 node = GritsMetaNode.find(_id) return _.pluck(node?._children or [], '_id') else return [_id.toUpperCase()] .flatten() .value() @createOrUpdate('departure', { key: 'departureAirport._PI:KEY:<KEY>END_PI' operator: '$in' value: parsedCodes }) else if _.isNull(code) Template.gritsSearch.getDepartureSearchMain().tokenfield('setTokens', []) @departures.set([]) else if _.isEmpty(code) Template.gritsSearch.getDepartureSearchMain().tokenfield('setTokens', []) @departures.set([]) else if _.isArray(code) Template.gritsSearch.getDepartureSearchMain().tokenfield('setTokens', code) @departures.set(code) else Template.gritsSearch.getDepartureSearchMain().tokenfield('setTokens', [code]) @departures.set([code]) trackDepartures: () -> self = this Meteor.autorun -> obj = self.departures.get() if _.isEmpty(obj) # checks are necessary as Tracker autorun will fire before the DOM # is ready and the Template.gritsMap.onRenered is called if !(_.isUndefined(Template.gritsMap) || _.isUndefined(Template.gritsMap.getInstance)) map = Template.gritsMap.getInstance() if !_.isNull(map) self.resetLayerGroup() self.setDepartures(obj) async.nextTick () -> self.compareStates() # returns a unique list of tokens from the search bar getOriginIds: () -> query = @getQueryObject() query['departureAirport._id']['$in'] # handle setup of subscription to SimulatedIteneraries and process the results processSimulation: (simPas, simId) -> # get the heatmapLayerGroup heatmapLayerGroup = Template.gritsMap.getInstance().getGritsLayerGroup(GritsConstants.HEATMAP_GROUP_LAYER_ID) # get the current mode groupLayer layerGroup = GritsLayerGroup.getCurrentLayerGroup() if layerGroup == null return # reset the layers/counters layerGroup.reset() heatmapLayerGroup.reset() loaded = 0 # initialize the status-bar counter Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS, loaded) # reset the airportCounts @airportCounts = {} @trackDepartures() originIds = @getOriginIds() _updateHeatmap = _.throttle(=> Heatmaps.remove({}) # map the airportCounts object to one with percentage values airportPercentages = _.object([key, val / loaded] for key, val of @airportCounts) # key the heatmap to the departure airports so it can be filtered # out if the query changes. airportPercentages._id = originIds.sort().join("") Heatmap.createFromDoc(airportPercentages, Meteor.gritsUtil.airportsToLocations) , 500) _throttledDraw = _.throttle(-> layerGroup.draw() heatmapLayerGroup.draw() , 500) @simulationItineraries = Meteor.subscribe('SimulationItineraries', simId) options = transform: null _doWork = (id, fields) => if @airportCounts[fields.destination] @airportCounts[fields.destination]++ else @airportCounts[fields.destination] = 1 loaded += 1 layerGroup.convertItineraries(fields, fields.origin) # update the simulatorProgress bar if simPas > 0 progress = Math.ceil((loaded / simPas) * 100) Template.gritsSearch.simulationProgress.set(progress) Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS, loaded) if loaded == simPas #finaldraw Template.gritsSearch.simulationProgress.set(100) Session.set(GritsConstants.SESSION_KEY_LOADED_RECORDS, loaded) _updateHeatmap() layerGroup.finish() heatmapLayerGroup.finish() @isSimulatorRunning.set(false) else _updateHeatmap() _throttledDraw() itineraryQuery = Itineraries.find({'simulationId': simId}, options) numItineraries = itineraryQuery.count() if numItineraries == simPas itineraryQuery.forEach Meteor.gritsUtil.smoothRate (itinerary) -> _doWork(itinerary._id, itinerary) else itineraryQuery.observeChanges({ added: Meteor.gritsUtil.smoothRate (id, fields) -> _doWork(id, fields) }) return # starting a simulation startSimulation: (simPas, startDate, endDate, email) -> departures = @departures.get() if departures.length == 0 toastr.error(i18n.get('toastMessages.departureRequired')) return if @isSimulatorRunning.get() return # switch mode Session.set(GritsConstants.SESSION_KEY_MODE, GritsConstants.MODE_ANALYZE) # let the user know the simulation started Template.gritsSearch.simulationProgress.set(1) # set the simulation as running @isSimulatorRunning.set(true) Meteor.call('startSimulation', simPas, startDate, endDate, @getOriginIds(), email, (err, res) => # handle any errors if err Meteor.gritsUtil.errorHandler(err) console.error(err) return if res.hasOwnProperty('error') Meteor.gritsUtil.errorHandler(res) console.error(res) return # set the reactive var on the template Template.gritsDataTable.simId.set(res.simId) # update the url, this will trigger processing of the simulation. FlowRouter.go('/simulation/'+res.simId) # set the status-bar total counter Session.set(GritsConstants.SESSION_KEY_TOTAL_RECORDS, simPas) ) # reset the start date of the filter resetStart: () -> self = this start = self._today month = start.getMonth() date = start.getDate() year = start.getFullYear() self.operatingDateRangeStart.set(new Date(year, month, date)) return # reset the end date of the filter resetEnd: () -> self = this end = moment(self._today).add(7, 'd').toDate() month = end.getMonth() date = end.getDate() year = end.getFullYear() self.operatingDateRangeEnd.set(new Date(year, month, date)) return # resets the filter reset: () -> self = this # reset the departures self.setDepartures null # reset the start and end dates self.resetStart() self.resetEnd() # reset counters Session.set GritsConstants.SESSION_KEY_LOADED_RECORDS, 0 Session.set GritsConstants.SESSION_KEY_TOTAL_RECORDS, 0 # reset includeNearby $('#includeNearbyAirports').prop 'checked', false $("#includeNearbyAirportsRadius").val 50 # determine the current mode mode = Session.get GritsConstants.SESSION_KEY_MODE if mode == GritsConstants.MODE_ANALYZE # set isSimulatorRunning to false self.isSimulatorRunning.set(false) # stop any existing subscription if self.simulationItineraries != null self.simulationItineraries.stop() self.simulationItineraries = null; # remove disabled class $('#startSimulation').removeClass('disabled') # reset number of passengers $('#simulatedPassengersInputSlider').slider('setValue', 1000) $('#simulatedPassengersInputSliderValIndicator').html(1000) FlowRouter.route('/') return GritsFilterCriteria = new GritsFilterCriteria() # exports as a singleton
[ { "context": "n of tag should be placed inside braces.\n# @author Ben Vinegar\n###\n'use strict'\n\ndocsUrl = require 'eslint-plugi", "end": 114, "score": 0.9998420476913452, "start": 103, "tag": "NAME", "value": "Ben Vinegar" } ]
src/rules/jsx-no-comment-textnodes.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Comments inside children section of tag should be placed inside braces. # @author Ben Vinegar ### 'use strict' docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = meta: docs: description: 'Comments inside children section of tag should be placed inside braces' category: 'Possible Errors' recommended: yes url: docsUrl 'jsx-no-comment-textnodes' schema: [ type: 'object' properties: {} additionalProperties: no ] create: (context) -> reportLiteralNode = (node) -> context.report( node 'Comments inside children section of tag should be placed inside braces' ) check = (node) -> sourceCode = context.getSourceCode() # since babel-eslint has the wrong node.raw, we'll get the source text rawValue = sourceCode.getText node if /^\s*(#|###)/m.test rawValue # inside component, e.g. <div>literal</div> if ( node.parent.type isnt 'JSXAttribute' and node.parent.type isnt 'JSXExpressionContainer' and node.parent.type.indexOf('JSX') isnt -1 ) reportLiteralNode node # -------------------------------------------------------------------------- # Public # -------------------------------------------------------------------------- Literal: check JSXText: check
141201
###* # @fileoverview Comments inside children section of tag should be placed inside braces. # @author <NAME> ### 'use strict' docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = meta: docs: description: 'Comments inside children section of tag should be placed inside braces' category: 'Possible Errors' recommended: yes url: docsUrl 'jsx-no-comment-textnodes' schema: [ type: 'object' properties: {} additionalProperties: no ] create: (context) -> reportLiteralNode = (node) -> context.report( node 'Comments inside children section of tag should be placed inside braces' ) check = (node) -> sourceCode = context.getSourceCode() # since babel-eslint has the wrong node.raw, we'll get the source text rawValue = sourceCode.getText node if /^\s*(#|###)/m.test rawValue # inside component, e.g. <div>literal</div> if ( node.parent.type isnt 'JSXAttribute' and node.parent.type isnt 'JSXExpressionContainer' and node.parent.type.indexOf('JSX') isnt -1 ) reportLiteralNode node # -------------------------------------------------------------------------- # Public # -------------------------------------------------------------------------- Literal: check JSXText: check
true
###* # @fileoverview Comments inside children section of tag should be placed inside braces. # @author PI:NAME:<NAME>END_PI ### 'use strict' docsUrl = require 'eslint-plugin-react/lib/util/docsUrl' # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = meta: docs: description: 'Comments inside children section of tag should be placed inside braces' category: 'Possible Errors' recommended: yes url: docsUrl 'jsx-no-comment-textnodes' schema: [ type: 'object' properties: {} additionalProperties: no ] create: (context) -> reportLiteralNode = (node) -> context.report( node 'Comments inside children section of tag should be placed inside braces' ) check = (node) -> sourceCode = context.getSourceCode() # since babel-eslint has the wrong node.raw, we'll get the source text rawValue = sourceCode.getText node if /^\s*(#|###)/m.test rawValue # inside component, e.g. <div>literal</div> if ( node.parent.type isnt 'JSXAttribute' and node.parent.type isnt 'JSXExpressionContainer' and node.parent.type.indexOf('JSX') isnt -1 ) reportLiteralNode node # -------------------------------------------------------------------------- # Public # -------------------------------------------------------------------------- Literal: check JSXText: check
[ { "context": "data.browsers, reqs, opts)\n key = browsers.selected.join(', ') + options.cascade\n cache[key] ||= new Prefi", "end": 883, "score": 0.7169076800346375, "start": 867, "tag": "KEY", "value": "selected.join('," } ]
lib/autoprefixer.coffee
javifelices/autoprefixer
0
browserslist = require('browserslist') postcss = require('postcss') Browsers = require('./browsers') Prefixes = require('./prefixes') isPlainObject = (obj) -> Object.prototype.toString.apply(obj) == '[object Object]' cache = { } module.exports = postcss.plugin 'autoprefixer', (reqs...) -> if reqs.length == 1 and isPlainObject(reqs[0]) options = reqs[0] reqs = undefined else if reqs.length == 0 or (reqs.length == 1 and not reqs[0]?) reqs = undefined else if reqs.length <= 2 and (reqs[0] instanceof Array or not reqs[0]?) options = reqs[1] reqs = reqs[0] else if typeof(reqs[reqs.length - 1]) == 'object' options = reqs.pop() options ||= { } reqs = options.browsers if options.browsers? loadPrefixes = (opts) -> browsers = new Browsers(module.exports.data.browsers, reqs, opts) key = browsers.selected.join(', ') + options.cascade cache[key] ||= new Prefixes(module.exports.data.prefixes, browsers, options) plugin = (css, result) -> prefixes = loadPrefixes(from: css.source?.input.file) prefixes.processor.remove(css) if options.remove != false prefixes.processor.add(css, result) if options.add != false plugin.options = options plugin.info = (opts) -> require('./info')(loadPrefixes(opts)) plugin # Autoprefixer data module.exports.data = browsers: require('caniuse-db/data').agents prefixes: require('../data/prefixes') # Autoprefixer default browsers module.exports.defaults = browserslist.defaults # Inspect with default Autoprefixer module.exports.info = -> module.exports().info()
23397
browserslist = require('browserslist') postcss = require('postcss') Browsers = require('./browsers') Prefixes = require('./prefixes') isPlainObject = (obj) -> Object.prototype.toString.apply(obj) == '[object Object]' cache = { } module.exports = postcss.plugin 'autoprefixer', (reqs...) -> if reqs.length == 1 and isPlainObject(reqs[0]) options = reqs[0] reqs = undefined else if reqs.length == 0 or (reqs.length == 1 and not reqs[0]?) reqs = undefined else if reqs.length <= 2 and (reqs[0] instanceof Array or not reqs[0]?) options = reqs[1] reqs = reqs[0] else if typeof(reqs[reqs.length - 1]) == 'object' options = reqs.pop() options ||= { } reqs = options.browsers if options.browsers? loadPrefixes = (opts) -> browsers = new Browsers(module.exports.data.browsers, reqs, opts) key = browsers.<KEY> ') + options.cascade cache[key] ||= new Prefixes(module.exports.data.prefixes, browsers, options) plugin = (css, result) -> prefixes = loadPrefixes(from: css.source?.input.file) prefixes.processor.remove(css) if options.remove != false prefixes.processor.add(css, result) if options.add != false plugin.options = options plugin.info = (opts) -> require('./info')(loadPrefixes(opts)) plugin # Autoprefixer data module.exports.data = browsers: require('caniuse-db/data').agents prefixes: require('../data/prefixes') # Autoprefixer default browsers module.exports.defaults = browserslist.defaults # Inspect with default Autoprefixer module.exports.info = -> module.exports().info()
true
browserslist = require('browserslist') postcss = require('postcss') Browsers = require('./browsers') Prefixes = require('./prefixes') isPlainObject = (obj) -> Object.prototype.toString.apply(obj) == '[object Object]' cache = { } module.exports = postcss.plugin 'autoprefixer', (reqs...) -> if reqs.length == 1 and isPlainObject(reqs[0]) options = reqs[0] reqs = undefined else if reqs.length == 0 or (reqs.length == 1 and not reqs[0]?) reqs = undefined else if reqs.length <= 2 and (reqs[0] instanceof Array or not reqs[0]?) options = reqs[1] reqs = reqs[0] else if typeof(reqs[reqs.length - 1]) == 'object' options = reqs.pop() options ||= { } reqs = options.browsers if options.browsers? loadPrefixes = (opts) -> browsers = new Browsers(module.exports.data.browsers, reqs, opts) key = browsers.PI:KEY:<KEY>END_PI ') + options.cascade cache[key] ||= new Prefixes(module.exports.data.prefixes, browsers, options) plugin = (css, result) -> prefixes = loadPrefixes(from: css.source?.input.file) prefixes.processor.remove(css) if options.remove != false prefixes.processor.add(css, result) if options.add != false plugin.options = options plugin.info = (opts) -> require('./info')(loadPrefixes(opts)) plugin # Autoprefixer data module.exports.data = browsers: require('caniuse-db/data').agents prefixes: require('../data/prefixes') # Autoprefixer default browsers module.exports.defaults = browserslist.defaults # Inspect with default Autoprefixer module.exports.info = -> module.exports().info()